Reputation: 1709
I am very new to GUI and am wondering how to change the BG color of a JButton when that respective button is pressed. I am not sure how to even properly structure GUI for this my first time.
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
}
}
Upvotes: 1
Views: 661
Reputation: 324088
Your ActionListener
might look something like:
public void actionPerformed(ActionEvent e)
{
JButton button = (JButton)e.getSource();
button.setBackground( Color.RED );
}
And you only need one ActionListener
because the code is generic since the button clicked will come from the event.
Also, Don't use Action for the Class name. There is an interface by that name so it gets confusing. Use a more descriptive name.
Upvotes: 3