在制作游戏之前,从来没有真正依赖过 Swings 布局管理器来绘制绘图,所以出于好奇和无聊,我开始这样做。我只是在面板上设置了一个具有不同颜色的按钮矩阵,其想法是稍后按钮将打开并显示您必须拍摄的动物。
问题是我添加到其中一个 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。