【发布时间】:2014-11-24 09:23:46
【问题描述】:
我有这个 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
所以我认为 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());
}
});
}
【问题讨论】:
-
向我们展示整个代码。你可能有另一个听众附加到
logOutButton -
logOutButton.addActionListener(){...}大概执行了两次,在上面打个断点检查一下。 -
@PredragMaric 谢谢这是问题:-)
-
@YvesHendseth 请点击 Predrag 答案上的复选标记,因为它与解决您的问题的评论相同。
标签: java action onclicklistener