0

So I'm trying to learn java and I'm trying to condense code down to be more simple by attempting to manipulate a group of JButtons together, is there any way to do this?

I've tried putting them all under a ButtonGroup group = new ButtonGroup(); but I can't do things like group.setFont(new Font("Times New Roman", Font.PLAIN, 50); or group.addActionListener(new Response()); or panel.add(group);.

Does Java allow this or am I just woefully ignorant?

By the way I'm only including 3 buttons as an example but I'm actually working with 20 so please don't say "since you only have 3 buttons it doesn't really matter".

Currently:

button1.setFont(new Font("Times New Roman", Font.PLAIN, 50));
button2.setFont(new Font("Times New Roman", Font.PLAIN, 50));
button3.setFont(new Font("Times New Roman", Font.PLAIN, 50));
button1.addActionListener(new Response());
button2.addActionListener(new Response());
button3.addActionListener(new Response());
panel.add(button1);
panel.add(button2);
panel.add(button3);

What I would like to happen:

ButtonGroup group = new ButtonGroup();
group.add(Button1);
group.add(Button2);
group.add(Button3);
group.setFont(new Font("Times New Roman", Font.PLAIN, 50));
group.addActionListener(new Response());
panel.add(group);
Evan M
  • 2,573
  • 1
  • 31
  • 36
Archie
  • 13
  • 6
  • 2
    Use an array/List to store the buttons and loop over to set the values for each element – copeg Aug 13 '16 at 19:56
  • Any time I see variable names with incrementing numbers I think, why doesn't this fellow use an array or ArrayList? You're making things way too hard on yourself by not doing this. – Hovercraft Full Of Eels Aug 13 '16 at 19:57
  • @copeg Oh thank you so much! I didn't know you could put JButtons under an array, I appreciate it man :D – Archie Aug 13 '16 at 19:57
  • @HovercraftFullOfEels Oh thank you for the constructive criticism man! XD I had no idea java could group JButtons under an array or array list XD. I appreciate it so much man :D – Archie Aug 13 '16 at 19:58

0 Answers0