Skip to content

Instantly share code, notes, and snippets.

@tonetheman
Created August 11, 2013 04:04
Show Gist options
  • Select an option

  • Save tonetheman/6203337 to your computer and use it in GitHub Desktop.

Select an option

Save tonetheman/6203337 to your computer and use it in GitHub Desktop.
How to clear a text field when a button is pressed
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;
public class Clearer {
public static void main(String[] args) {
JFrame mainframe = new JFrame("test");
mainframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainframe.setSize(300,200);
final JTextField tf = new JTextField(20);
JButton button = new JButton("clear");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
// here it is, get the document and call remove on it
// pass 0 (the starting point)
// and the length of the document
tf.getDocument().remove(0,tf.getDocument().getLength());
} catch(BadLocationException err1) {
err1.printStackTrace();
}
}
});
mainframe.getContentPane().setLayout(new FlowLayout());
mainframe.getContentPane().add(tf);
mainframe.getContentPane().add(button);
mainframe.setVisible(true);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment