如何将ActionListener添加到JButton

时间:2016-02-24 14:20:00

标签: java actionlistener

我知道如果我用名称声明JButton,我可以将ActionListener添加到JButton。

JButton showDialogButton = new JButton("Click Me");

    showDialogButton.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent e)
      {
        // display/center the jdialog when the button is pressed
        JDialog d = new JDialog(frame, "Hello", true);
        d.setLocationRelativeTo(frame);
        d.setVisible(true);
      }
    });

但如果我有以下代码该怎么办:

MyJFrame frame = new MyJFrame();
frame.setSize(500,300);
JPanel base = new JPanel();

base.setLayout(new BorderLayout());

JPanel north = new JPanel();

north.add(new JLabel("Name"));
north.add(new JTextField());
north.add(new JButton("Enter"));
north.add(new JButton("Exit"));

我很感激任何答案。

3 个答案:

答案 0 :(得分:0)

为了向ActionListener添加JButton,您必须保留对它的引用,以便您不能仅仅为什么将其作为new传递给JPanel的构造函数 该解决方案基本上是您之前执行的操作,它是单独声明+初始化它们:JButton myButton = new JButton("My Button");然后只需将之前的ActionListener添加到JPanel

myButton.addActionListener(new ActionListener() ...);

然后只是north.add(myButton);

答案 1 :(得分:0)

在添加

之外声明它们
JButton exit = new JButton("exit");
exit.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent e)
      {
        //do stuff
      }
    });
north.add(exit);

然后对您希望将侦听器添加到

的所有其他组件执行相同操作

答案 2 :(得分:0)

在搜索Java API之后,我发现add方法返回正在添加的组件。不幸的是,它只是一个通用的Component对象,如果没有强制转换就无法链接。但是你可以得到这样的附加对象:

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

public class GuiTest
{
    public static void main(String[] args)
    {
        JFrame frame = new JFrame();
        frame.setSize(500, 300);
        JPanel base = new JPanel();

        base.setLayout(new BorderLayout());

        JPanel north = new JPanel();

        Component comp1 = north.add(new JLabel("Name"));
        System.out.println("comp1 class type: " + comp1.getClass().getName());
        Component comp2 = north.add(new JTextField());
        System.out.println("comp2 class type: " + comp2.getClass().getName());
        Component comp3 = north.add(new JButton("Enter"));
        System.out.println("comp3 class type: " + comp3.getClass().getName());
        ((JButton)north.add(new JButton("Exit")))
                 .addActionListener(new ActionListener()
                  {
                      public void actionPerformed(ActionEvent e)
                      {
                          System.out.println("EXIT");
                      }
                  });
        base.add(north);

        frame.getContentPane().add(base);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

此代码完整且可验证(我在Arch Linux x64机器上测试过)。这有点难看,但有效。