Question: home / study / engineering / computer science / computer science questions and answers / create a jframe with dimensions of 400x300 pixels. create a
home / study / engineering / computer science / computer science questions and answers / create a jframe with dimensions of 400x300 pixels. create a jbutton object and a jpanel object. ...
Your question has been answered
Let us know if you got a helpful answer. Rate this answer
Question: Create a JFrame with dimensions of 400x300 pixels. Create a JButton object and a JPanel object. A...
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
Get step-by-step solutions from verified subject matter experts
