Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

JFormattedTextField: clearing text

Status
Not open for further replies.

godcomplex

Programmer
Apr 24, 2002
94
US
Hello All,

I am sorry ahead of time if this question has already been answered somewhere in the forum, but I couldn't find it. I am simply trying to find a method to clear the tex field of all its text (ie set it back to its original state). When I try to use the method setText( String value ), and set value = "", I get some wierd results. Here's the code, pretty simple stuff:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.text.*;

public class GUITest
{
public static void main( String args[] )
{
JFrame frame = new TestFrame();
frame.show();
}
}

class TestFrame extends JFrame implements ActionListener
{
private JFormattedTextField ssnText;
private JFormattedTextField dateText;
private JButton button;

public TestFrame()
{
setTitle( "GUI Test" );
setSize( 300, 200 );
addWindowListener( new WindowAdapter()
{
public void WindowClosingEvent( WindowEvent e )
{
System.exit( 0 );
}
} );

button = new JButton( "Clear" );
button.addActionListener( this );

try
{
ssnText = new JFormattedTextField( new MaskFormatter( "###-##-####" ) );
dateText = new JFormattedTextField( new MaskFormatter( "##/##/## ##:##" ) );
} catch( Exception e ){}

getContentPane().setLayout( new FlowLayout() );
getContentPane().add( ssnText );
getContentPane().add( dateText );
getContentPane().add( button );
}

public void actionPerformed( ActionEvent event )
{
System.out.println( "SSN = \"" + ssnText.getText() + "\"" );
System.out.println( "DATE = \"" + dateText.getText() + "\"" );

ssnText.setText( "" );
dateText.setText( "" );
}
}

If anyone could give me a hand with this I would appreciate it.

-gc
 
This text field, although implementing JTextfield, has a lot to do with the focus it receives when running. Try using the its own setValue instead of setText.

setValue(new String(""));

I havent tried this so it may not be valid. Just an idea.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top