Reputation: 2652
Hello I have this set up
private JButton btnFoo, btnBar;
And I need to get for each button the following
btnFoo = new JButton("Foo");
btnFoo.addActionListener(this);
add(btnFoo);
Is it possible in Java to create this dynamically for each button I declare? because when I have like 5 buttons I don't want 3x5 = 15 lines of code but only a few lines with dynamically created buttons.
Upvotes: 1
Views: 9860
Reputation: 21
boton1= new JButton();
boton1.setText(" Calcular ");
add(boton1);
boton1.setActionCommand("Calcular");
boton1.addActionListener(this);
boton1.setEnabled(true);
String nB2="boton";
for(int j=2; j<4; j++){
JButton botonGenerico = new JButton(nB2+j);
botonGenerico.setText("Calcular"+j);
add(botonGenerico);
botonGenerico.setActionCommand("Calcular"+j);
botonGenerico.addActionListener(this);
botonGenerico.setEnabled(true);
}
public void actionPerformed(ActionEvent e){
String a = e.getActionCommand();
if(a.equals("Calcular")){
JOptionPane.showMessageDialog(null, "¡boton 1");
}
if(a.equals("Calcular2")){
JOptionPane.showMessageDialog(null, "¡boton 2");
}
if(a.equals("Calcular3")){
JOptionPane.showMessageDialog(null, "¡boton 3");
}
}
Upvotes: 2
Reputation: 68847
Write a little loop and store your buttons in an array:
private JButton buttons[] = new JButton[5];
String names[] = {"Foo", "Bar", "Baz", "Fob", "Bao"};
for (int i = 0; i < buttons.length; ++i)
{
JButton btn = new JButton(names[i]);
btn.addActionListener(this);
add(btn);
buttons[i] = btn;
}
Upvotes: 6
Reputation: 25950
That's where arrays and loops come to help. Use a button array and iterate over it.
But if you worry about identifiers, then using HashMap<String, JButton>
might be a good way.
Map<String, JButton> buttons = new HashMap<String, JButton>();
map.put("fooButton", new JButton());
...
By iterating over the entry set (just a few lines of code), set the ActionListener
for the buttons.
Upvotes: 2