ActionListener actionPerformed被调用两次

时间:2014-11-24 09:23:47

标签: java action onclicklistener

我有这个ActionListener:

logOutButton.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println(getTextFieldContent());

        }
    });

在这里我将按钮添加到面板:

c.fill = GridBagConstraints.RELATIVE;
c.anchor = GridBagConstraints.LAST_LINE_END;
c.gridwidth = 1;
this.add(logOutButton, c);

如果JTextField的内容是test, 控制台输出是:

test
test

所以我认为actionPerformed()方法被调用两次,但为什么呢?

修改

洞穴代码:

public GuiPanel(){
    super();
    this.setBorder(new EmptyBorder(10, 10, 10, 10) );
    //Layout:
    GridBagLayout gridbag = new GridBagLayout();
    GridBagConstraints c = new GridBagConstraints();
    this.setLayout(gridbag);
    setUpJButton();

    //label for textfield
    c.fill = GridBagConstraints.HORIZONTAL;
    c.gridwidth = GridBagConstraints.REMAINDER;
    gridbag.setConstraints(labelForName, c);
    this.add(labelForName);

    c.insets = new Insets(5, 0, 0, 0);//padding to top

    //textField
    c.fill = GridBagConstraints.HORIZONTAL;
    setUpTextField();
    c.gridwidth = GridBagConstraints.REMAINDER;
    gridbag.setConstraints(textField, c);
    c.gridwidth = 1;//reset gridwidth
    this.add(textField);

    c.insets = new Insets(10, 0, 0, 0);//padding to top

    //anmelden Button
    c.fill = GridBagConstraints.RELATIVE;
    setUpJButton();
    c.gridwidth = 1;
    c.anchor = GridBagConstraints.LAST_LINE_START;
    this.add(logInButton, c);

    c.insets = new Insets(10, 5, 0, 0);//padding to left

    //abmelden Button
    c.fill = GridBagConstraints.RELATIVE;
    c.anchor = GridBagConstraints.LAST_LINE_END;
    c.gridwidth = 1;
    this.add(logOutButton, c);
}

private void setUpJButton() {
    logInButton.setSize(50, 50);
    logInButton.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println(getTextFieldContent());
        }
    });
    logOutButton.setSize(50, 50);
    logOutButton.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println(getTextFieldContent());

        }
    });
}

3 个答案:

答案 0 :(得分:6)

您在代码中调用setUpJButton()两次,在相同的按钮上添加两次侦听器。

答案 1 :(得分:0)

尝试打印e.getActionCommand()。我猜测按钮上有两个截然不同的动作。

答案 2 :(得分:0)

由于您在addActionListener中使用class AmazonsController < ApplicationController def index @joe = ProductService.screen_print end end instantiate ActionListener()实例,它会传递new operator(因为您调用setUpJButton两次)并且它(addActionListener)不知道他们是同一个要求。

如果你确定不想扩展ActionListener并像这样使用,那么two different instance就是addActionListener。 像这样:

reference it to an member object and pass

然后

ActionListener acLs=new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
           System.out.println(getTextFieldContent());  //getTextFieldContent??
        }
    };