I have 20 loop-generated JToggleButtons
and I need to count how many of them are active.
private void generarBotones(){
JToggleButton b;
this.panelCuerpo.setLayout(new GridLayout(4,5));
for(int i = 1; i<=20; i++){
b = new JToggleButton();
b.setText(String.valueOf(i));
this.panelCuerpo.add(b);
b.addActionListener(new ActionListener() {
int clicks = 0;
@Override
public void actionPerformed(ActionEvent ae2){
clicks = clicks + 1;
System.out.println(clicks);
}
public void setCantidadBoletas(int clicks){
cantidadBoletas = clicks;
}
});
}
}
The problem here is that it counts how many times is EACH ONE of them clicked instead of count how many of them are selected.
PS. I tried to use (b.isSelected())
but b
needs to be final
to access it so it wasn't the solution.
If you declare the JToggleButton
inside the loop, you can make it final
:
for (int i = 1; i<=20; i++) {
JToggleButton b = new JToggleButton();
Then you can use b.isSelected
:
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (b.isSelected())
clicks++;
else
clicks--;
}
});
}
clicks
would have to be a class variable.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다