Pass arguments into JButton ActionListener

24,270

Solution 1

  1. Create a class that implements the ActionListener interface.
  2. 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

  1. make entry final so it can be accessed in the anonymous class

    public 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() );
          }
        });
      ...
      }
    
  2. make entry a field

    JTextField 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() );
      }
    });
  ...
Share:
24,270
Sam
Author by

Sam

Updated on March 30, 2020

Comments

  • Sam
    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?