Page 697 - Introduction to Programming with Java: A Problem Solving Approach
P. 697
The JButton class needs the javax.swing package, but that should be available already, since it’s needed for the JFrame class. The ActionListener interface and the ActionEvent class need the java.awt.event package, so import that package.
Methods
Here are API headings and descriptions for some of the more useful JButton methods: public String getText()
Returns the button’s label.
public void setText(String text)
Assigns the button’s label.
public void setVisible(boolean flag)
Makes the button visible or invisible.
public void addActionListener(ActionListener listener)
Adds a listener to the button. The listener “listens” for the button being clicked.
FactorialButton Program
It’s time to put all this JButton syntax into practice by showing you how it’s used within a complete pro- gram. We’ve written a FacAtorpiaalBugtton proPgrDamFthatEusnesha JaBunttcoen cromponent to calculate the factorial
3
forauser-enterednumber. Togiveyouabetterideaofhowtheprogramoperates,seethesamplesessionin
Figure 16.7.
Figures 16.8a and 16.8b contain the FactorialButton program listing. Most of the code should already
make sense since the program’s structure parallels the structure in our previous GUI programs. We’ll skip the more familiar code and focus on the more difficult code.
We declare most of our GUI variables locally within createContents, but we declare the two text box components as instance variables at the top of the program. Why the difference? As discussed earlier, normally you should declare components as local variables to help with encapsulation. But if a component is needed in createContents and also in an event handler, it’s fine to declare it as an instance variable where it can be shared more easily. In the FactorialButton program, we declare the two text boxes as in- stance variables because we need to use them in createContents and also in the actionPerformed event handler.
Note this line from the createContents method:
xfBox.setEditable(false);
This causes the factorial text box, xfBox, to be non-editable (i.e., the user won’t be able to update the text box). That should make sense since xfBox holds the factorial, and it’s up to the program (not the user) to generate the factorial. Note in Figure 16.7 that the factorial text box is grayed out. You get that visual cue free of charge whenever you call setEditable(false) from a text box component. Cool!
3 The factorial of a number is the product of all positive integers less than or equal to the number. The factorial of n is written as n! Example: The factorial of 4 is written as 4!, and 4! is equal to 24 because 1 times 2 times 3 times 4 equals 24.
16.12 JButton Component 663