【问题标题】:Why can't this method be called inside actionListener?为什么在actionListener里面不能调用这个方法?
【发布时间】:2016-10-28 06:10:06
【问题描述】:

我刚开始学习 java 中的方法。在 python 中,使用“函数”很容易,但我最近了解到 java 没有类似的东西。我有一个方法应该返回 n1 和 n2 中的最小值。我在 public static int minFunction 行中遇到错误...

Multiple markers at this line
- Syntax error on token "(", ; 
 expected
- Syntax error on token ",", ; 
 expected
- Syntax error on token ")", ; 
 expected

但语法似乎没有任何问题。

JButton btnCompute = new JButton("Compute");
    btnCompute.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try { 


                int n1=5;
                int n2=4;
                int minValue= minFunction(n1,n2);


                public static int minFunction(int n1 , int n2) {
                       int min;
                       if (n1 > n2)
                          min = n2;
                       else
                          min = n1;

                       return min; 
                    }                       
                }

            catch(NumberFormatException ex){ 

            }
        }
    });

【问题讨论】:

标签: java


【解决方案1】:

如果您想从侦听器实现中调用方法,请将其放在实现之外。例如,

JButton btnCompute = new JButton("Compute");
public void handleAction() {
    btnCompute.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {

                int n1 = 5;
                int n2 = 4;
                int minValue = minFunction(n1, n2);

            }

            catch (NumberFormatException ex) {

            }
        }
    });
}
public int minFunction(int n1, int n2) {
    int min;
    if (n1 > n2)
        min = n2;
    else min = n1;

    return min;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-09
    • 1970-01-01
    • 2021-06-29
    • 1970-01-01
    • 2011-02-25
    • 1970-01-01
    • 1970-01-01
    • 2019-11-18
    相关资源
    最近更新 更多