Как увеличить счетчик (локальную переменную) при нажатии JButton? ⇐ JAVA
-
Anonymous
Как увеличить счетчик (локальную переменную) при нажатии JButton?
I want to count the number of times the button plus is pressed. I do it with an object. I want to know if I can do it just with a simple int and how, as it says it needs to be final or effectively final (like in the lambda function)
Here's a snippet:
public class Counters { public int x; Counters(){ this.x = 0; } public void incrementX(){ x++; } } public class Main { public static void main(String[] args) { JButton plus = new JButton(); Counters hrs = new Counters(); plus.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { hrs.incrementX(); System.out.println(String.valueOf(hrs.x)); } }); //Down here i also take care of the jframe but it's out of the scope of the question } } This works and I can increase hrs.x. But is there a way to use a primitive value as a counter in this listener? This seems a bit overcomplicated for just a counter.
Источник: https://stackoverflow.com/questions/780 ... of-jbutton
I want to count the number of times the button plus is pressed. I do it with an object. I want to know if I can do it just with a simple int and how, as it says it needs to be final or effectively final (like in the lambda function)
Here's a snippet:
public class Counters { public int x; Counters(){ this.x = 0; } public void incrementX(){ x++; } } public class Main { public static void main(String[] args) { JButton plus = new JButton(); Counters hrs = new Counters(); plus.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { hrs.incrementX(); System.out.println(String.valueOf(hrs.x)); } }); //Down here i also take care of the jframe but it's out of the scope of the question } } This works and I can increase hrs.x. But is there a way to use a primitive value as a counter in this listener? This seems a bit overcomplicated for just a counter.
Источник: https://stackoverflow.com/questions/780 ... of-jbutton