Java Reference
In-Depth Information
JButton
To create a button, Java provides the class JButton . Thus, to create objects
belonging to the class JButton , we use a technique similar to the one we used to
create instances of JLabel and JTextField . Table 6-5 shows some methods of the
class JButton .
TABLE 6-5 Commonly Used Methods of the class JButton
Method / Description
public JButton(Icon ic)
//Constructor to initialize the button object with the icon
//specified by ic.
public JButton(String str)
//Constructor to initialize the button object to the text specified
//by str.
6
public JButton(String str, Icon ic)
//Constructor to initialize the button object to the text specified
//by str and the icon specified by ic.
public void setText(String str)
//Method to set the text of the button to the string specified by str.
public String getText()
//Method to return the text contained in the button.
public void addActionListener(ActionListener obj)
//Method to register a listener object to the button object.
The following three lines will create two buttons, Calculate and Exit , shown earlier in
Figure 6-2:
JButton calculateB, exitB;
//Line 1
calculateB = new JButton("Calculate"); //Line 2
exitB = new JButton("Exit"); //Line 3
The statement in Line 1 declares calculateB and exitB to be reference variables of
type JButton . The statement in Line 2 instantiates the button object calculateB
and sets the text for the button to the string Calculate . Similarly, the statement in
Line 3 instantiates the button object exitB and sets the text for exitB to the string
Exit .
 
 
 
Search WWH ::




Custom Search