12

这是一个带有两个按钮的 java 程序,用于更改整数值并显示它。但是在 IntelliJIDEA 中,这两行带有

increase.addActionListener(incListener());
decrease.addActionListener(decListener());

继续显示错误“预期方法调用”。

我不知道该怎么做才能解决这个问题。

任何帮助将不胜感激

谢谢

注意:下面附上完整的代码。

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

public class Main extends JDialog {
public JPanel contentPane;
public JButton decrease;
public JButton increase;
public JLabel label;

public int number;

public Main() {
    setContentPane(contentPane);
    setModal(true);

    increase = new JButton();
    decrease = new JButton();
    increase.addActionListener(incListener());
    decrease.addActionListener(decListener());

    number = 50;
    label = new JLabel();
}

public class incListener implements ActionListener {
    public void actionPerformed (ActionEvent event) {
        number++;
        label.setText("" + number);
    }
}

public class decListener implements ActionListener {
    public void actionPerformed (ActionEvent event) {
        number--;
        label.setText("" + number);
    }
}

public static void main(String[] args) {
    Main dialog = new Main();
    dialog.pack();
    dialog.setVisible(true);
    System.exit(0);

}
}
4

7 回答 7

21

incListener 和 declListener 是类,而不是方法。

尝试

increase.addActionListener(new incListener());

顺便说一句,重命名你的类名,使它们以大写开头

于 2013-05-07T11:47:55.153 回答
5

很简单:使用new incListener()而不是incListener(). 后者试图调用一个名为的方法incListener,前者从类中创建一个对象incListener,这正是我们想要的。

于 2013-05-07T11:48:22.200 回答
1

incListener 和 decListener 是一个类而不是一个方法,所以你必须调用 new 来使用它们,试试这个:

增加.addActionListener(new incListener()); 减少.addActionListener(new decListener());

对不起,我的英语不好

于 2013-05-07T11:53:11.090 回答
0

进行以下更改:

 public Main() {
    contentPane = new JPanel();
    setContentPane(contentPane);
    setModal(true);

    increase = new JButton("inc");
    decrease = new JButton("dec");
    contentPane.add(increase);
    contentPane.add(decrease);
    increase.addActionListener(new incListener());
    decrease.addActionListener(new decListener());

    number = 50;
    label = new JLabel(number+"");
    contentPane.add(label);
}
于 2013-05-07T11:55:13.333 回答
0

increase.addActionListener( new incListener());
decrease.addActionListener( new decListener());
于 2013-05-07T11:47:58.407 回答
0

很遗憾,但我不得不用谷歌搜索同样的错误……我盯着一个返回类的方法。我离开了new运营商。

return <class>(<parameters>) 对比 return new <class>(<parameters>)

于 2019-05-20T17:56:43.533 回答
-1

每当使用new运算符创建字符串对象时,都会创建一个新对象,这就是您的程序正在寻找的对象。以下链接有助于了解字符串和新字符串之间的区别。 “文本”和新字符串(“文本”)有什么区别?

于 2018-07-09T20:03:57.337 回答