【问题标题】:Pass arguments into JButton ActionListener将参数传递给 JButton ActionListener
【发布时间】:2012-04-13 09:54:31
【问题描述】:

我正在寻找一种将变量或字符串或任何内容传递给 JButton 的匿名 actionlistener(或显式 actionlistener)的方法。这是我所拥有的:

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() );
      }
    });
  ...
  }
}

现在我只是将entry 声明为一个全局变量,但我讨厌这种工作方式。有更好的选择吗?

【问题讨论】:

    标签: java swing jbutton actionlistener


    【解决方案1】:
    1. 创建一个实现ActionListener 接口的类。
    2. 提供具有JTextField 参数的构造函数。

    示例 -

    class Foo implements ActionListener{
        private final JTextField textField;
    
        Foo(final JTextField textField){
            super();
            this.textField = textField;
        }
        .
        .
        .
    }
    

    问题?

    【讨论】:

    • 问题:Java 新手。感谢您提供的信息,效果很好,并且更好地理解了它们是如何联系在一起的。
    • 不过,我遇到了同样的问题,并把它作为一个有用的答案。
    【解决方案2】:

    在这种情况下使用 Action 和 AbstractAction 可能会更好,你可以在其中做那种事情。

    【讨论】:

      【解决方案3】:

      从我在这里看到的代码来看,entry 不是全局变量。它是 addDialog() 方法中的局部变量。我误会了吗?

      如果您在本地将变量声明为 final,那么监听器将能够访问它。

          final JTextField entry = new JTextField( "Entry Text", 20 );
          ...
          addButton.addActionListener( new ActionListener( ) {
            public void actionPerformed( ActionEvent e )
            {
              System.out.println( entry.getText() );
            }
          });
        ...
      

      【讨论】:

      • 我将这个 sn-p 作为本地人编写,所以它可以工作,我的意思是这就是我希望它的工作方式。我使用它的方式是全球性的。
      【解决方案4】:

      两种方式

      1. 使entryfinal可以在匿名类中访问

        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. 使entry成为一个字段

        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() );
              }
            });
          ...
          }
        

      【讨论】:

      • 2) 基本上是我让它工作的方式。我还没有尝试过 1),但我确实让它与 mre 的建议一起工作。还没有使用final 还不足以真正掌握我猜的用法,谢谢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-23
      • 2013-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多