Mouselistener没有响应jpanel

时间:2013-05-31 00:57:27

标签: java swing jpanel mouse-listeners

在制作游戏之前,从来没有真正依靠摇摆布局管理员来绘制游戏,因此出于好奇和无聊,我开始着手这样做。我只需要在面板上设置不同颜色的按钮矩阵,其想法是稍后按钮将打开并显示您必须拍摄的动物。

问题是我添加到其中一个jpanels的mouselistener不会响应按钮上的点击(或框架内的任何其他位置),而只会在框架调整大小时对框架的边框作出响应,因此存在黑色区域可见。

监听器(除了将监听器添加到Board之外没什么作用)。

public class Game implements MouseListener {
JFrame frame;
Board board;

public Game() {
    this.frame = new JFrame("Shoot a Tile");
    this.board = new Board(20, 20);
    this.board.addMouseListener(this);
    this.frame.getContentPane().add(board);
    this.frame.pack();
    this.frame.setLocationRelativeTo(null);
    this.frame.setVisible(true);
    this.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String[] args) {
    new Game();
}

@Override
public void mouseClicked(MouseEvent e) {
    System.out.println("HELLO I WAS CLICKED AT: " + e.getPoint());

}

@Override
public void mouseEntered(MouseEvent e) {
    System.out.println("HELLO I ENTERED AT: " + e.getPoint());

}

@Override
public void mouseExited(MouseEvent e) {
    System.out.println("HELLO I EXITED AT: " + e.getPoint());

}

@Override
public void mousePressed(MouseEvent e) {
    System.out.println("HELLO I WAS PRESSED AT: " + e.getPoint());

}

@Override
public void mouseReleased(MouseEvent e) {
    System.out.println("HELLO I WAS RELEASED AT: " + e.getPoint());

}

董事会

public class Board extends JPanel {

private Tile[][] tiles;
private int row, column;
public static final Random rnd = new Random();

public Board(int row, int column) {
    this.row = row;
    this.column = column;
    this.tiles = new Tile[row][column];
    setBackground(Color.black);
    setLayout(new GridLayout(row, column));
    setTiles();
}

private void setTiles() {
    for (int i = 0; i < row; i++) {
        Color color = new Color(rnd.nextInt(256), rnd.nextInt(256),
                rnd.nextInt(256));
        for (int j = 0; j < column; j++) {
            tiles[i][j] = new Tile(color);
            add(tiles[i][j]);
        }
    }
}

}

瓷砖

public class Tile extends JButton {

private Color color;
private List<Particle> particles;
private int x, y, width, height;
private boolean destroyed;

public Tile(Color color) {
    this.color = color;
}

@Override
@Transient
public Color getBackground() {
    return color;
}

public void destroy() {
    this.destroyed = true;
}

public boolean isDestroyed() {
    return destroyed;
}

@Override
@Transient
public Dimension getPreferredSize() {
    return new Dimension(50, 40);
}}

代码非常简单,即使它在很多行上,最短的SSCEE。

0 个答案:

没有答案