Question

I need to have three buttons in my program (the last one is an exit button and it already works) the other two need to change the color of the JPanel background between blue and red.

I need to know what goes in the AtionListeners so that when the buttons are pressed it changes the background color.

This is the class so far :

package myPackageNameGoesHere;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

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

public class EventPanel extends JPanel {
private static final long serialVersionUID = 123796234;

private JButton blueButton;
private JButton redButton;
private JButton exitButton;

public EventPanel() {
    this.setPreferredSize(new Dimension(200, 300));

    this.blueButton = new JButton("Blue");
    this.add(this.blueButton);

    this.redButton = new JButton("Red");
    this.add(this.redButton);

    this.exitButton = new JButton("Exit");
    this.exitButton.addActionListener(new ExitListener());
    this.add(this.exitButton);
}

private class BlueListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent blue) {
        // What goes here?????

    }
}

private class RedListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent red) {
        // What goes here????

    }
}
private class ExitListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent exit) {
        System.exit(0);
    }
}
}
Was it helpful?

Solution

You don't have to declare a listener class for each button, you can just use the same one and add if statement to determine from which button the action come from.

if (e.getSource() == blueButton) {// e is the ActionEvent
    blueButton.getParent().setBackground(Color.BLUE);
} else if(e.getSource() == redButton) {
    redButton.getParent().setBackground(Color.RED);
}

OTHER TIPS

You could set the background color of the button's parent component

Component component = (Component) event.getSource();
component.getParent().setBackground(Color.BLUE);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top