为什么不能在actionListener中调用此方法?

时间:2016-10-28 06:10:06

标签: java

我刚学习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){ 

            }
        }
    });

1 个答案:

答案 0 :(得分:0)

如果要从侦听器实现中调用方法,请将其实现。例如,

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;
}