Pass arguments into JButton ActionListener
24,270
Solution 1
- Create a class that implements the
ActionListener
interface. - Provide a constructor that has a
JTextField
argument.
Example -
class Foo implements ActionListener{
private final JTextField textField;
Foo(final JTextField textField){
super();
this.textField = textField;
}
.
.
.
}
Problem?
Solution 2
2 ways
make
entry
final
so it can be accessed in the anonymous classpublic static void addDialog() { JButton addButton = new JButton( "Add" ); final JTextField entry = new JTextField( "Entry Text", 20 ); ... addButton.addActionListener( new ActionListener( ) { public void actionPerformed( ActionEvent e ) { System.out.println( entry.getText() ); } }); ... }
make
entry
a fieldJTextField entry; public static void addDialog() { JButton addButton = new JButton( "Add" ); entry = new JTextField( "Entry Text", 20 ); ... addButton.addActionListener( new ActionListener( ) { public void actionPerformed( ActionEvent e ) { System.out.println( entry.getText() ); } }); ... }
Solution 3
Maybe better in this case to use Action and AbstractAction, where you could do that kind of thing.
Solution 4
From the code I see here, entry is NOT a global variable. It's a local variable in the addDialog() method.. Did I misunderstand you?
If you declare the variable locally as final, then the listener will be able to access it.
final JTextField entry = new JTextField( "Entry Text", 20 );
...
addButton.addActionListener( new ActionListener( ) {
public void actionPerformed( ActionEvent e )
{
System.out.println( entry.getText() );
}
});
...
Author by
Sam
Updated on March 30, 2020Comments
-
Sam about 4 years
I'm looking for a way to pass a variable or string or anything into an anonymous actionlistener ( or explicit actionlistener ) for a JButton. Here is what I have:
public class Tool { ... public static void addDialog() { JButton addButton = new JButton( "Add" ); JTextField entry = new JTextField( "Entry Text", 20 ); ... addButton.addActionListener( new ActionListener( ) { public void actionPerformed( ActionEvent e ) { System.out.println( entry.getText() ); } }); ... } }
Right now I just declare
entry
to be a global variable, but I hate that way of making this work. Is there a better alternative?