Java Reference
In-Depth Information
downButton = new JRadioButton( "Decrement" , true );
p. add(upButton) ;
p . add(downButton) ;
ButtonGroup group = new ButtonGroup () ;
group .add(upButton) ;
group .add(downButton) ;
CenterPanel centerPanel = new CenterPanel () ;
add(centerPanel , BorderLayout .CENTER) ;
}
class CenterPanel extends JPanel {
JTextField textField = new JTextField( "0" , 20) ;
int x=0;
public CenterPanel ()
{
add(textField);
Timer t = new Timer(1000, new ActionListener ()
{
public void actionPerformed(ActionEvent e)
{
if (upButton . isSelected () ) x++;
if (downButton. isSelected()) x −− ;
textField .setText( "" +x);
}
} );
t. start() ;
textField . getDocument() . addDocumentListener( new DocumentListener
() {
public void insertUpdate(DocumentEvent e)
{
try {
x = Integer . parseInt(textField .getText() . trim()) ;
}
catch (Exception es) {
}
} public void removeUpdate(DocumentEvent e )
{
try {
x = Integer . parseInt(textField .getText() . trim()) ;
}
catch (Exception es) {
}
} public void changedUpdate(DocumentEvent e)
{
}
}
);
}
}
}
The program stores a variable x , which is displayed in the text field. A timer that changes
the value of x every second is created. The isSlected method checks which radio button
is selected. Depending on the outcome, the value of x is incremented or decremented by
one. The user can also manually change the value of x . Every time something is inserted in
or deleted from the text field, a method is called. In both cases, the variable x is updated
to the new value of the text field. Note that the parseInt method is used to convert a
string to an integer. If the user does not type in an integer, then an exception is raised.
The try-catch blocks guarantee that in this situation the program simply continues to
increment or decrement the value x and disregards the user input.
 
Search WWH ::




Custom Search