Question
create a JFrame with dimensions of 400x300 pixels. Create a JButton object and a JPanel object. Add the JButton to the JPanel object. Set the
create a JFrame with dimensions of 400x300 pixels. Create a JButton object and a JPanel object. Add the JButton to the JPanel object. Set the contentPane of the JFrame to the JPanel you have created.
Set the layout for the JPanel you created to a FlowLayout ( setLayout(new FlowLayout() ) ). Create a label for the JButton (look up JButton in Javadocs for this) that says "Change Color."
Add a WindowListener to the JFrame and an ActionListener to the JButton and have these point to a separate listener object that you have created (this must implement the WindowListener and ActionListener interfaces). In the listener class, you need to provide bodies for all methods. Only the windowClosing and actionPerformed methods will have any code.
The windowClosing event should close the application, just as in the example. The actionPerformed event, should toggle the background color of the JButton from light grey to red (and back). That is, if the current color of the button is light grey, change it to red. If the current color is red, change it to grey. You will need to use the getSource() method of the ActionEvent object sent via the parameter. This method returns the Object that generated the Event. To access the JButton that generated, you will need to cast the result of getSource() to a JButton. For example:
JButton btn = (JButton)e.getSource();
You can now use btn to access method(s) to change the color.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started