Java JLabel and GUI assignment Write a program which displays a window containin
ID: 639929 • Letter: J
Question
Java JLabel and GUI assignment
Write a program which displays a window containing two buttons, labeled "one" and "two". When a button is pressed, a report of this event should be printed on the console (e.g. "Button two has been pressed"). You should be able to press the buttons as often as you like, in any order, and wind up with a sequence of printed messages. When you click the close button at the corner of the window (marked X), the program should stop.
For the assignment, you want to arrange for the window's close button to exit the program. You also want to change the JButton's ActionListener so that it prints a message to System.out rather than calling System.exit(). At that point, you should be able to test the one button.
Then, add a second button. Remember it will need its own ActionListener to print the slightly different message.
Explanation / Answer
A button is a GUI component that looks like a button and that can do something when you click it with your mouse. In this subsection we tell you how to add buttons to your GUI. In the next subsection we tell you how to specify what happens when the button is clicked.
A button object is created in the same way that any other object is created, but you use the classJButton when you want buttons. For example, the following example from Display 12 creates a button:
The argument to the construct, in this case "Red", is a string that will be written on the button when the button is displayed. The string argument to the constructor, in this example "Red", specifies the string that will appear on the button when it is displayed on the screen. If you look at the GUI in Display 12, you will see that the two buttons are labeled "Red" and "Green".
The button is added to the content pane with the following:
There is no second argument to the method add because we are using the FlowLayout manager class. If we had instead used the BorderLayout manager class, then we would have used some second argument, such as BorderLayout.NORTH.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.