I need to pass the control variable from a for
, as a parameter to a method. The problem, is that I'm trying to do this according to the JRadioButton
that was selected, I'm creating them according to my for, and defined events for them then.
The issue is that within ActionEvent
I can not use the for control variable, unless it is final, however, this is not possible, since it can change "size" according to the columns of a table.
(Note: in if
, in e.getActionCommand().equals(tituloColuna[i])
is an attempt to make the action only apply to radioButton
that has the same name that gives it condition.)
Does anyone have any suggestions?
I made a very simple example, just to illustrate the situation.
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class TesteFor extends JFrame {
public static void main(String[] args) {
EventQueue.invokeLater(()
-> {
TesteFor ts = new TesteFor();
ts.setVisible(true);
});
}
public TesteFor() {
setTitle("Teste");
add(componentesTela());
setPreferredSize(new Dimension(375, 300));
pack();
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private JComponent componentesTela() {
JPanel jp = new JPanel();
String tituloColuna[] = {"Coluna 01", "Coluna 02"};
//Tabela apenas para indicar de onde veio os valores, não estou adicionando ela no exemplo.
JTable tabela = new JTable();
tabela.setModel(new DefaultTableModel(
new Object[][]{
{null, null, null},
{null, null, null},
{null, null, null}
},
new String[]{
"", ""
}
));
int numeroColunas = tabela.getColumnModel().getColumnCount();
for (int i = 0; i < numeroColunas; i++) {
JRadioButton radio = new JRadioButton("Ocultar " + tituloColuna[i]);
jp.add(radio);
radio.setActionCommand(tituloColuna[i]); //e.getActionCommand() vai retornar o nome do radio clicado
radio.addActionListener((ActionEvent e)
-> {
//ERRO
/*if (e.getActionCommand().equals(tituloColuna[i])) {
alterarTabela(i);
System.out.println("Peguei a " + e.getActionCommand());
}*/
});
}
return jp;
}
private void alterarTabela(int indiceColuna) {
//alterar colunas de acordo com o indice.
}
}