There are two JTextField and a button in this example. The actionPerformed() method which will be called when user complete text entry in textField1 by pressing Enter, or by clicking on buttonAccept. Then the text in textField1 will be copied to textField2.
|
Example of using JTextField |
package javamyframe;
import java.awt.BorderLayout;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
/**
* @web http://java-buddy.blogspot.com/
*/
public class JavaMyFrame extends JFrame
implements ActionListener{
JTextField textField1, textField2;
Label labelInfo;
JButton buttonAccept;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
JavaMyFrame myFrame = new JavaMyFrame();
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.prepareUI();
myFrame.pack();
myFrame.setVisible(true);
}
private void prepareUI(){
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
textField1 = new JTextField(20);
textField1.addActionListener(this);
textField2 = new JTextField(20);
labelInfo = new Label();
panel.add(textField1);
panel.add(textField2);
panel.add(labelInfo);
buttonAccept = new JButton("Accept");
buttonAccept.addActionListener(this);
getContentPane().add(panel, BorderLayout.CENTER);
getContentPane().add(buttonAccept, BorderLayout.PAGE_END);
}
@Override
public void actionPerformed(ActionEvent e) {
textField2.setText(textField1.getText());
if(e.getSource() == textField1){
labelInfo.setText("by textField1");
}else if(e.getSource() == buttonAccept){
labelInfo.setText("by buttonAccept");
}else{
labelInfo.setText("unknow source");
}
}
}
No comments:
Post a Comment