1

I'm trying to make an app with a panel where it asks a question (whether an image contains humans, cars, or other objects... and more). Each question is answered with yes/no. I didn't want to make JRadioButton for each of the 'yes's and 'no's. So I tried to add the same Radio Button multiple times but it doesn't work (See below).

contentsPanel = new JPanel();
contentsHumans = new JLabel("Humans? ");
contentsCars = new JLabel("Cars? ");
contentsOtherObjects = new JLabel("Other Objects? ");

yes = new JRadioButton("Yes"); 
no = new JRadioButton("No");
binaryAnswer = new ButtonGroup();
binaryAnswer.add(yes);
binaryAnswer.add(no);

contentsPanel.setBorder(BorderFactory.createTitledBorder(
                 BorderFactory.createEtchedBorder(), "Image contains... "));
contentsPanel.add(contentsHumans);
contentsPanel.add(yes); contentsPanel.add(no);
contentsPanel.add(contentsCars);
contentsPanel.add(yes); contentsPanel.add(no);
contentsPanel.add(contentsOtherObjects);
contentsPanel.add(yes); contentsPanel.add(no);

Do I have to separately create y1 = new JRadioButton("Yes");, y2 = new JRadioButton("Yes");, etc., for all my 'yes's and 'no's?? I can definitely copy and paste to do that but I was wondering if there is any other way.

Here's the image of current output:

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
ju09
  • 19
  • 3
  • Can you show an image of what you would expect the UI to look like (and the current result?). Strictly speaking there are multiple ways to achieve this (a yes/no button that would take the current context of the UI, or a yes/no button that's generated within a method that makes new panes, etc) – Rogue May 27 '22 at 16:41
  • 2
    Use a method that adds two radiobuttons in a buttongroup. Copying and pasting code is sign of repetitive code, which is almost always improvable. – tucuxi May 27 '22 at 16:45
  • 1
    You need to create new instances of the buttons. Otherwise, pressing one is the same as pressing all. But you can do this in a loop. And if you update required listeners during creation you don't even need to keep the button fields around. Using a method to create buttons is a common practice. – WJS May 27 '22 at 17:15

0 Answers0