Section 4.8 Exercises
Exercises IO Exercises
Fill in the blank.
Fill in the blanks in each of the following sentences:
2.
Java GUIs utilize a form of control known as programming.
3.
When the user clicks on a programโs
JButton, an will automatically be generated.
4.
Two kinds of objects that generate
ActionEvent s are and . JButtons, JTextFields, and JLabels are all subclasses of .
5.
The
JFrame class is a subclass of .
6.
If a Java class intends to handle
ActionEvent s, it must implement the interface.
7.
8.
Look up the documentation for the
JButton class on Oracleโs Web site: https://docs.oracle.com/javase/8/docs/api/javax/swing/JButton.html. List the signatures of all its constructors.
9.
10.
11.
12.
Suppose you have a program containing a
JButton named button. Describe what happens, in terms of Javaโs event handling model, when the user clicks the button.
13.
14.
Modify the GUI in the previous exercise so that it contains three
JButton s, initially labeled โFirst,โ โSecond,โ and โThird.โ Each time the user clicks one of the buttons, the labels on the buttons should be rotated. Second should get firstโs label, third should get secondโs, and first should get thirdโs label.
15.
Design and implement a GUI that contains a
JTextField and two JButton s, initially labeled โLeftโ and โRight.โ Each time the user clicks a button, display its label in the JTextField. A JButton()โs label can be gotten with the getText() method.
16.
You can change the size of a
JFrame by using the setSize(int h, int v) method, where h and v give its horizontal and vertical dimensions pixels. Write a GUI application that contains two JButton s, labeled โBigโ and โSmall.โ Whenever the user clicks on small, set the JFrame's dimensions to 200 ร 100, and whenever the user clicks on big, set the dimensions to 300 ร 200.
17.
Rewrite your solution to the previous exercise so that it uses a single button whose label is toggled appropriately each time it is clicked. Obviously, when the
JButton is labeled โBig,โ clicking it should give the JFrame its big dimensions.
18.
Challenge: Design and write a Java GUI application that allows the user to change the
JFrameโs background color to one of three choices, indicated by buttons. Like all other Java Component s, JFrameโs have an associated background color, which can be set by the following commands: setBackground(Color.red);
setBackground(Color.yellow);
The
setBackground() method is defined in the Component class, and 13 primary colorsโblack, blue, cyan, darkGray, gray, green, lightGray, magenta, orange, pink, red, white, yellowโare defined in the java.awt.Color class.
You have attempted of activities on this page.

