Re: Action Listeners for JTextFields
Some other variants to consider..
<sscce>
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Test2 extends JFrame implements ActionListener {
// scope class..
JTextField jtf = new JTextField(20);
Test2() {
JPanel p1 = new JPanel();
p1.add(jtf);
// layout constraint
this.add(p1, BorderLayout.NORTH);
JButton jb = new JButton("Click Me!");
// layout constraint
this.add(jb, BorderLayout.CENTER);
jb.addActionListener(this);
}
/** The action listener is implemented as follows */
public void actionPerformed(ActionEvent e){
System.out.println(jtf.getText());
}
/** Add a simple main to throw it on-screen */
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
Test2 test = new Test2();
test.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
test.pack();
test.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
</sscce>
..and..
<sscce>
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Test3 extends JFrame {
Test3() {
JPanel p1 = new JPanel();
// scope local, must be final..
final JTextField jtf = new JTextField(20);
p1.add(jtf);
// layout constraint
this.add(p1, BorderLayout.NORTH);
JButton jb = new JButton("Click Me!");
// layout constraint
this.add(jb, BorderLayout.CENTER);
//jb.addActionListener(this);
// implement actionlistener as inner class
jb.addActionListener(
new ActionListener(){
/** The action listener is implemented as follows */
public void actionPerformed(ActionEvent e){
System.out.println(jtf.getText());
}
});
}
/** Add a simple main to throw it on-screen */
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
Test3 test = new Test3();
test.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
test.pack();
test.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
</sscce>
HTH
--
Andrew Thompson
http://www.athompson.info/andrew/
Message posted via JavaKB.com
http://www.javakb.com/Uwe/Forums.aspx/java-general/200710/1