我是 GUI 的新手,想知道如何在按下相应按钮时更改 JButton 的 BG 颜色。我第一次不确定如何正确构建 GUI。
public static void createWindow(int x)
{
JFrame frame = new JFrame("WINDOW");
frame.setSize(40*x, 40*x);
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
for(int i = 0; i < x * x; i++)
{
JButton button = new JButton();
button.setPreferredSize(new Dimension(40, 40));
panel.add(button);
button.addActionListener(new Action());
}
frame.add(panel);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
static class Action implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
//changes color of button
}
}
最佳答案
您的 ActionListener
可能类似于:
public void actionPerformed(ActionEvent e)
{
JButton button = (JButton)e.getSource();
button.setBackground( Color.RED );
}
而且您只需要一个 ActionListener
,因为该代码是通用的,因为单击的按钮将来自该事件。
另外,不要使用 Action 作为类名。有一个同名的接口(interface),所以它会让人感到困惑。使用更具描述性的名称。
关于java - 在按下 JAVA 时更改 JButton 的 BG 颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33136262/