从二维数组中选择JButton后执行操作

时间:2016-10-13 13:17:13

标签: java arrays jbutton

我有一个JButtons的二维数组,我希望能够使用我的鼠标所在的按钮来执行操作,例如更改颜色。我怎样才能做到这一点?感谢。

以下是我创建按钮的方法:

for(int r = 0;r<10;r++){
        for(int c = 0;c<10;c++){
            buttonArray[r][c] = new JButton();
        }
    }

1 个答案:

答案 0 :(得分:1)

以下是使用循环和MouseAdapter的示例(因为您不需要MouseListener中的所有方法):

import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class JButtonHighlighter extends JPanel {

    public static void main(final String[] args) {

        JFrame frame = new JFrame();

        JPanel contentPanel = new JPanel();
        contentPanel.setLayout(new GridLayout(10, 10));

        JButton[][] buttonArray = new JButton[10][10];

        for (int r = 0; r < 10; r++) {
            for (int c = 0; c < 10; c++) {

                final JButton newButton = new JButton();

                final Color originalColor = newButton.getBackground();
                final Color highlightColor = Color.GREEN;

                newButton.addMouseListener(new MouseAdapter() {

                    @Override
                    public void mouseEntered(final MouseEvent e) {
                        newButton.setBackground(highlightColor);

                    }

                    @Override
                    public void mouseExited(final MouseEvent e) {
                        newButton.setBackground(originalColor);

                    }

                });

                buttonArray[r][c] = newButton;

                contentPanel.add(newButton);
            }
        }

        frame.setContentPane(contentPanel);
        frame.setSize(100, 100);
        frame.setVisible(true);

    }

}