Java Swing开发国际象棋时如何判断二维JPanel数组元素是否包含JLabel
问题原因分析
contains()方法误用:Container.contains()的作用是判断坐标点是否在组件范围内,或者判断已存在的子组件实例是否属于当前容器,你代码中直接new JLabel()创建了全新的JLabel实例,和棋盘上已添加的棋子JLabel不是同一个对象,判断永远返回false,因此逻辑不生效。- 匿名内部类变量引用规则问题:Java要求匿名内部类(这里的MouseAdapter)引用的外部局部变量必须是final或实际不可变,你直接在监听器中使用循环变量
i、j会触发编译错误。 - 额外注意:JPanel默认是透明的,直接设置背景色不会生效,需要先设置为不透明。
正确实现方案
package mainBoard; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class SetSquaresToClickable { InitializeBoard initializeBoard = new InitializeBoard(); JPanel[][] squares = initializeBoard.getSquares(); SetSquaresToClickable() { for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { JPanel currentSquare = squares[i][j]; boolean hasPiece = false; // 遍历当前方格的所有子组件,判断是否存在承载棋子的JLabel for (Component comp : currentSquare.getComponents()) { // 额外判断JLabel携带ImageIcon,避免误判其他非棋子标签 if (comp instanceof JLabel && ((JLabel) comp).getIcon() != null) { hasPiece = true; break; } } if (hasPiece) { // 声明final临时变量供匿名监听器使用 final int finalI = i; final int finalJ = j; currentSquare.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { squares[finalI][finalJ].setOpaque(true); squares[finalI][finalJ].setBackground(Color.BLUE); squares[finalI][finalJ].repaint(); } }); } } } } public static void main(String[] args) { // 请确保InitializeBoard实例已经完成棋盘渲染、棋子添加操作后再调用本类,否则squares可能为空 new SetSquaresToClickable(); } }
内容的提问来源于stack exchange,提问作者Kayhan Kolhatkar
相关产品推荐
相关产品推荐

