Reputation: 2862
I am a studying programming we just started Swing I have to make a simple boat management I need about 20 buttons. I am using the setVisible()
method for every button I just wonder if is there another way of doing that.
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e) {
button.setVisible(false);
button1.setVisible(false);
button2.setVisible(true);
button3.setVisible(true);
}
});
Upvotes: 0
Views: 1779
Reputation: 201447
If I understand your question, you could define two utility methods like
static void setVisible(JButton... btns) {
for (JButton btn : btns) {
btn.setVisible(true);
}
}
static void setInvisible(JButton... btns) {
for (JButton btn : btns) {
btn.setVisible(false);
}
}
Then you could call those with any number of buttons; like
setInvisible(button, button1);
setVisible(button2, button3);
As for making different buttons do different things, define an ActionListener
per button (or per unique action).
Upvotes: 2
Reputation: 6077
You can just implement the action listener in your class like:
public class XYZ implements ActionListener
Then add it to your buttons like:
b1.addActionListener(this);
b2.addActionListener(this);
...
Then override the actionPerformed method:
public void actionPerformed(ActionEvent e) {
//Here do your tasks.
// To identify the button, use : e.getSource();
}
Upvotes: 0
Reputation: 2560
Just add another new ActionListener(){....} to each button and modify the actionPerformed(ActionEvent e) method accordingly
Upvotes: 0