javaprogrammer javaprogrammer - 1 month ago 7
Java Question

Why can't this method be called inside actionListener?

I'm new to learning about methods in java. In python, it was easy to use "Functions" but I recently learnt that java doesn't have something similar to that. I have a method which should return the lowest value out of n1 and n2. I'm getting an error in the line public static int minFunction...

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


But there doesn't seem to be anything wrong with the syntax.

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){

}
}
});

Answer

If you want to call method from listener implementation, put it out side implementation. For example,

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