Java JTextField setText
JTextField Object has several methods.Some of these methods are JTextField getText, JTextField setToolTipText etc
JTextField setText Example
[
import javax.swing.JFrame; import javax.swing.JTextField; import javax.swing.JButton; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JOptionPane; public class JavaJTextField { public static JTextField field; public static JButton add; public static void main(String args[]) { JFrame frame=new JFrame("JTextField Example"); field=new JTextField(); field.setEnabled(false); field.setBounds(50,50, 150,20); frame.add(field); add=new JButton("Save"); add.setBounds(50,100,100,20); frame.add(add); add.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { String name=JOptionPane.showInputDialog(null, "Enter your name", "Name",JOptionPane.INFORMATION_MESSAGE); field.setText(name); } }); frame.setSize(400,400); frame.setLocationRelativeTo(null); frame.setLayout(null); frame.setVisible(true); } }
]
JTextField setText Code Explanation
When Save button is clicked,a JOptionPane.showInputDialog shows up requesting user to enter his/her name.
The name is saved as String name and using [field.setText(name);] we are able to set Text in the JTextField.
Other methods used in this program:
- [field.setEnabled(false);]-Prevents user from directly entering text.
- [add.setBounds(50,100,100,20);]-sets JButton position on JFrame.
- [add.addActionListener(new ActionListener())]-Adds ActionListener to the JButton