找到点击位置并解决“从内部类引用的局部变量必须是最终的或实际上是最终的”错误

时间:2019-05-16 14:24:47

标签: java multidimensional-array custom-controls

我正在尝试创建一个扫雷游戏,目前我只是在跨10 mines个按钮随机生成10 by 10 array

按钮位于JPanel中(使用网格布局),因此下面的代码来自该JPanel的自定义代码。

我正在努力做到这一点,以便程序可以判断用户单击了哪个按钮,但这是我目前似乎在努力的部分。

我不断收到以下错误

  从内部类引用的

“局部变量必须是final或   有效地最终。”

我知道我的代码有些混乱,因为它是从各种互联网建议中拼凑而成的。任何帮助将不胜感激。

mainPanel = new javax.swing.JPanel();
mainPanel.setLayout(new java.awt.GridLayout(10, 10));

// Code of sub-components and layout - not shown here
// Code adding the component to the parent container - not shown here
int[][] cells = new int[10][10];
int mines = 10;
int n = 0;
int state;

while (n<mines){
    for (int i = 0; i < 10; i++) {
        for (int j = 0; j < 10; j++) {
            while (n<mines) {
                state = (Math.random() <= 0.5) ? 1 : 2;
                cells [i][j]= state;
                if (state == 2){
                    n++;
                }
            }
        }
    }

    final JButton buttons [][] = new JButton [10][10];
    String[] names =    {"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten    "};

    for (int i = 0; i < 10; i++) {
        for (int j = 0; j < 10; j++) {
            //JButton aButton = new JButton();
            //mainPanel.add(aButton);
            buttons[i][j] = new JButton(names[i]);
            buttons[i][j].putClientProperty( "firstIndex", new Integer( i ) );
            buttons[i][j].putClientProperty( "secondIndex", new Integer( j ) );

            mainPanel.add(buttons[i][j]);

            buttons[i][j].addMouseListener(new MouseListener() {
                public void mousePressed(MouseEvent me) { }
                public void mouseReleased(MouseEvent me) { }
                public void mouseEntered(MouseEvent me) { }
                public void mouseExited(MouseEvent me) { }

                public void mouseClicked(MouseEvent me) { 
                    if(me.getButton() == MouseEvent.BUTTON1) {
                        JButton buttons[i][j] = (JButton) MouseEvent.getSource();
                        Integer firstIndex = buttons[i][j].getClientProperty( "firstIndex" );
                        Integer secondIndex = buttons[i][j].getClientProperty( "secondIndex" );
                        System.out.println(firstIndex+""+secondIndex);
                    }
                    if(me.getButton() == MouseEvent.BUTTON2) {
                        //buttons[i][j].setText("Middle Click!");
                    }
                    if(me.getButton() == MouseEvent.BUTTON3) {
                        //buttons[i][j].setText("Right Click!");
                    }
                }
            });

            mainPanel.revalidate();
            mainPanel.repaint();
        }
    }
}

0 个答案:

没有答案