Created
August 11, 2013 04:04
-
-
Save tonetheman/6203337 to your computer and use it in GitHub Desktop.
How to clear a text field when a button is pressed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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