Created
March 11, 2013 22:50
-
-
Save figengungor/5138640 to your computer and use it in GitHub Desktop.
Java GUI >> Adding ActionListener to TextField and Button
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 java.awt.event.ActionEvent; | |
| import java.awt.event.ActionListener; | |
| import javax.swing.JButton; | |
| import javax.swing.JFrame; | |
| import javax.swing.JLabel; | |
| import javax.swing.JPanel; | |
| import javax.swing.JTextField; | |
| public class MyGUI extends JFrame { | |
| JPanel jp; | |
| JTextField jt; | |
| JLabel jl; | |
| JButton jb; | |
| public MyGUI(){ | |
| setTitle("JTextField Example"); | |
| setSize(400,200); | |
| setVisible(true); | |
| setDefaultCloseOperation(EXIT_ON_CLOSE); | |
| jp = new JPanel(); | |
| jt = new JTextField(30); //text to appear in the text field, horizontal length | |
| jl = new JLabel(); | |
| jb = new JButton("Enter"); | |
| jt.addActionListener(new ActionListener() { | |
| //after adding text to text field, enter will be listened by action listener of text field | |
| public void actionPerformed(ActionEvent e) { | |
| String input = jt.getText(); | |
| jl.setText(input); | |
| } | |
| }); | |
| jb.addActionListener(new ActionListener() { | |
| public void actionPerformed(ActionEvent e) { | |
| String input = jt.getText(); | |
| jl.setText(input); | |
| } | |
| }); | |
| jp.add(jt); | |
| jp.add(jb); | |
| jp.add(jl); | |
| add(jp); | |
| validate(); | |
| } | |
| public static void main(String [] args) { | |
| new MyGUI(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment