Java Reference
In-Depth Information
FIGURE 12.6: Example of radio buttons.
12.10 Document Listeners
The following interface is part of the library javax.swing.event.* .
interface DocumentListener {
public void insertUpdate(DocumentEvent e) ;
public void removeUpdate(DocumentEvent e ) ;
public void changedUpdate(DocumentEvent e) ;
}
This interface can be used to create a listener that can be added to a document.
The insertUpdate method is called when a new character is inserted in the text. The
removeUpdate method is called when text is deleted. The changeUpdate method is called
every time the text is modified. Given a text field or a text area, the getDocument method
returns the document that is associated with the field (i.e., an object of type Document ). The
addDocumentListener method can be used to register an event listener with the document.
Next, let us extend the application from the last section by adding a text field. The
text field will contain a number that increases by one every second. If the radio button
Decrement is selected, then the value in the text field will start decrementing by one every
second. Conversely, if the radio button Increment is selected, then the value in the text
field will increment by one every second. At the same time, we will add a listener to the
text field that allows the user to enter a new value for the text field. Here is the complete
code.
import java .awt . ;
import java .awt. event . ;
import javax . swing . ;
import javax . swing . event . ;
{
public static void main(String [] args)
public class Test
{
NumbersFrame f = new NumbersFrame () ;
f . setVisible( true );
}
}
class NumbersFrame extends JFrame
{
JRadioButton upButton ;
JRadioButton downButton ;
public NumbersFrame ()
{
setSize (400,100) ;
JPanel p = new JPanel () ;
a d d ( p , B o r d e r L a y o u t . NORTH) ;
upButton = new JRadioButton( "Increment" , true );
 
Search WWH ::




Custom Search