How Do I Make Sure Only One JRadioButton Is Selected In Java? - java

I have three JRadioButtons added to a JPanel. However, when I select one, I can select another one and the previous one selected stays selected. How can I make sure that only one is selected at a time?
My JPanel class, which is added by my main JFrame:
public class MainPanel extends JPanel {
private static JRadioButton addHouse, addRoad, calculateDist;
static {
addHouse = new JRadioButton("Add House");
addRoad = new JRadioButton("Add Road");
calculateDist = new JRadioButton("Calculate Distance");
}
MainPanel() {
setBackground(Color.WHITE);
addHouse.setBounds(50, 50, 100, 50);
addRoad.setBounds(50, 150, 100, 50);
addHouse.setBounds(50, 250, 100, 50);
addHouse.setBackground(Color.WHITE);
addRoad.setBackground(Color.WHITE);
calculateDist.setBackground(Color.WHITE);
add(addHouse);
add(addRoad);
add(calculateDist);
}
}

As you didn't share the complete code i can't tell how to do it in your case but in general
It can be done like that
ButtonGroup buttonGroup = new ButtonGroup() // create a button group , buttons in a button group knows how to behave together
JRadioButton radioButton1 = new JRadioButton("R1"); // create your buttons
JRadioButton radioButton2 = new JRadioButton("R2"); // as many you want
buttonGroup.add(radioButton1); // make them part of group
buttonGroup.add(radioButton2);
myJFrame.setLayout(new FlowLayout()); // or any layout you want
myJFrame.add(radioButton1); // add buttons to jframe
myJFrame.add(radioButton1);
when buttons were added to JFrame (or any other container) they were part of a group , so group handles the communications between them, now you can check only one at a time,
try commenting buttonGroup.add(); you will loose that behaveiour .
Same thing can be achieved manually , it that case you will track all other radio buttons
at every selection to check if others are already check and then uncheck them which is tedious so better use ButtonGroup class of swing

You can add the JRadioButtons in a ButtonGroup instance first. Here is a simple example:
// configure buttons bounds, background etc.
ButtonGroup buttonGroup= new ButtonGroup();
buttonGroup.add(addHouse);
buttonGroup.add(addRoad);
buttonGroup.add(calculateDist);
// add the buttons to the panel too.

Related

More efficient way to add multiple button groups

I am trying to make a personality quiz in java using the swing library. There are 5 questions that each have 3 possible answers. Right now I'm building the interface but I'm struggling to add multiple groups of buttons to my createComponents method.
So for the sake of clarity and making it easier to read, I made a separate method for my first question text. That has been added no problem. But I run into issues with the button groups. I didn't want to load up my createComponents method with multiple lines and lines and lines of repetitive add Buttongroups stuff because I read that excluding comments, methods should be 15 lines long max. or at least for a beginner.
So I made a separate method for my button groups which I then tried to add to the createComponents method. this gave me an error saying there is no suitable method to add a button group to my container.
Right now I am writing multiple lines of code in my createComponent method so that I can 'correctly' add my radio buttons. I'm only on the first question and already have 16 lines in my method. there's a better, more efficient way right?
private void createComponents(Container container){
BoxLayout layout = new BoxLayout(container, BoxLayout.Y_AXIS);
container.setLayout(layout);
JLabel text = new JLabel("this is the intro text");
container.add((text), BorderLayout.NORTH);
container.add(QuizIntro());
container.add(QuestionOne());
container.add(QuestionOneGroup());
// this throws an error
JRadioButton int1 = new JRadioButton("This is answer choice 1");
JRadioButton ent1 = new JRadioButton("This is answer choice 2");
JRadioButton jb1 = new JRadioButton("This is answer choice 3");
ButtonGroup group = new ButtonGroup();
group.add(int1);
group.add(ent1);
group.add(jb1);
container.add(int1);
container.add(ent1);
container.add(jb1);
// this is the 'correct' way I've been doing it.
}
public ButtonGroup QuestionOneGroup(){
JRadioButton int1 = new JRadioButton("This is answer choice 1");
JRadioButton ent1 = new JRadioButton("This is answer choice 2");
JRadioButton jb1 = new JRadioButton("This is answer choice 3");
ButtonGroup group = new ButtonGroup();
group.add(int1);
group.add(ent1);
group.add(jb1);
return group;
// this is the method I made to add a buttongroup and make my createComponent easier to read.
}
So my expected output is just a barebones window with the question and the 3 possible answer choices but I get an error telling me no suitable method. it says "argument mismatch buttongroup cannot be converted to popup menu or component".
You can only add Components to a Container.
A ButtonGroup is NOT a Component.
A ButtonGroup is used to indicate which component of a group of components has been selected. You still need to add each individual radio button to a panel.
Your code should be something like:
//public ButtonGroup QuestionOneGroup()
public JPanel questionOneGroup()
{
JRadioButton int1 = new JRadioButton("This is answer choice 1");
JRadioButton ent1 = new JRadioButton("This is answer choice 2");
JRadioButton jb1 = new JRadioButton("This is answer choice 3");
ButtonGroup group = new ButtonGroup();
group.add(int1);
group.add(ent1);
group.add(jb1);
//return group;
JPanel panel = new JPanel();
panel.add( int1 );
panel.add( ent1 );
panel.add( jb1 );
return panel;
}
Read the section from the Swing tutorial on How to Use Radio Buttons for more information and working examples.

populating JTabbed Pane with JScroll panes according to user selection

We have a project for university which is a program to hold handouts and feedback for courseworks done.
What we've thought of is breaking the whole thing down into smaller pieces, for example:
You have a coursework which requires to write a program and a report on results etc.
So the user will create a new coursework by selecting the "code" and "report" options, since that's what is required. And then we need to create the respective tabs in the program so the user can input what is needed.
I have created all necessary forms and windows, It's just I'm not sure how to move on forward.
a) where should I put my code? should I have it on the "create" event?
b) how do I do this whole custom population thing?
Obviously, I'm not asking for the entire thing in code. I'm not even sure what to read and what to search for.
Following are some screenshots of the ui to help explain what I mean.
New project window
How the main window should be after creating a new projet. Notice the various tabs.
A form for report feedback
On your "Create" button click check for the checkbox.isSelected() and use the method below as:
if(reportCheckbox.isSelected()){
addonScreen(new reportFrame(),"Report Submission");
addonScreen(new reportFeedbackFrame(),"Report Feedback");
}
Use a desktop pane as a container...add your tabbed pane to it
public static JTabbedPane tabbedPane = new JTabbedPane();
jDesktopPane1.add(tabbedPane);
Use this method to add tabs to the layout at runtime
public static void addOnScreen(JInternalFrame inFrame, String title) {
//border for the internal frame
javax.swing.plaf.InternalFrameUI ifu = inFrame.getUI();
((javax.swing.plaf.basic.BasicInternalFrameUI) ifu).setNorthPane(null);
Border b1 = new LineBorder(new Color(114, 139, 173), 3, true) {
};
tabbedPane.setBounds(0, 0, jDesktopPane1.getWidth(), jDesktopPane1.getHeight());
inFrame.setLocation(0, 0);
inFrame.setSize(jDesktopPane1.getWidth(), jDesktopPane1.getHeight());
inFrame.setBorder(b1);
JPanel jp = new JPanel();
jp.setLayout(new GridLayout());
jp.setOpaque(true);
jp.add(inFrame);
tabbedPane.addTab(title, jp);
tabbedPane.setSelectedComponent(jp);
inFrame.requestFocusInWindow();
inFrame.setVisible(true);
tabbedPane.setVisible(true);
}

Adding components via code

I'm trying to have painted into a JPanel (which is inside a ScrollPane), a bunch of labels and RadioButtons, dynamically. I receive an ArrayList with "Advice" objects, and I want to iterate over them to represent them in a way I have a label that describes them, and then, two radio buttons (to choose "Yes" or "No").
But at the moment, with this code at the JFrame's constructor, it's not properly working:
// My constructor
public CoachingFrame(AdvicesManager am) {
initComponents();
this.am = am;
// I set the layout for the inner panel (since ScrollPane doesn't allow BoxLayout)
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
// Iterate over the arraylist
for(int i=0;i<am.advices.size();i++){
//Add elements to the panel
panel.add(new JLabel( am.advices.get(i).getQuestion()));
ButtonGroup group = new ButtonGroup();
// Group the RadioButtons inside another panel, so I can use FlowLayout
JPanel buttonsPanel = new JPanel();
buttonsPanel.setLayout(new FlowLayout());
JRadioButton rad1 = new JRadioButton();
JRadioButton rad2 = new JRadioButton();
group.add(rad1);
group.add(rad2);
buttonsPanel.add(rad1);
buttonsPanel.add(rad2);
// Add the radiobuttons' panel to the main one, and revalidate
panel.add(buttonsPanel);
panel.revalidate();
}
// Finally, add the panel to the ScrollPane.
questions.add(panel);
}
I receive the arraylist correctly; I already checked that. The problem seems to be when painting the components.
Since I always use the NetBeans GUI creator, I'm not very used to add components via code. Can someone help me? I guess I'm missing something here.
edit: Note that "questions" is the ScrollPane object!
edit 2: This "questions" panel should have all those components painted: http://i.imgur.com/tXxROfn.png
As Kiheru said, ScrollPane doesn't allow views (like my JPanel) to be added with .add(), instead, I had to use .setViewportView(Component). Now it's working perfectly, thank you!

Buttons overwriting each other

So my buttons are overwriting each other, instead of all going up North like a tool bar..
I'm trying to get the buttons to go up North if that makes sense. I know my GUI is awful, and I'll rewire it once I get this prototype done.
// panels
mainPuzzlerPanel = new Panel();
mainPuzzlerPanel.setLayout(new BorderLayout());
puzzlePanel = new Panel();
//mainPuzzlerPanel.setLayout(null);
puzzlePanel.setLocation(100, 120);
// text fields
debugTxt = new TextArea(null,6,40,1);
debugTxt.setEditable(false);
mainPuzzlerPanel.add(debugTxt,BorderLayout.NORTH);
// buttons
Button newPuzzle = new Button("New Puzzle");
Button loadImage = new Button("Load Image");
Button assignLocation = new Button("Assign Location");
Button assignTimestamp = new Button("Assign Timestamp");
Button savePuzzle = new Button("Save Puzzle");
Button clearPuzzleCreator = new Button("Clear");
newPuzzle.addActionListener(this);
loadImage.addActionListener(this);
assignLocation.addActionListener(this);
assignTimestamp.addActionListener(this);
savePuzzle.addActionListener(this);
clearPuzzleCreator.addActionListener(this);
mainPuzzlerPanel.add(assignLocation,BorderLayout.NORTH);
mainPuzzlerPanel.add(assignTimestamp,BorderLayout.NORTH);
mainPuzzlerPanel.add(loadImage,BorderLayout.NORTH);
mainPuzzlerPanel.add(savePuzzle,BorderLayout.NORTH);
mainPuzzlerPanel.add(clearPuzzleCreator,BorderLayout.NORTH);
mainPuzzlerPanel.add(newPuzzle,BorderLayout.NORTH);
mainPuzzlerPanel.add(puzzlePanel,BorderLayout.CENTER);
add(mainPuzzlerPanel, "Controls");
setSize(1200, 700);
setVisible(true);
You can't add all the components BorderLayout.NORTH, makes no sense. Instead, add the JButtons to a JPanel that uses a different layout, say GridLayout, and then add that JPanel BorderLayout.NORTH. But most important -- read a tutorial on how to use the layout managers. It looks like you're guessing at this and that's not an efficient way to learn how to use these complex tools.
Regading,
I know my GUI is awful, and I'll rewire it once I get this prototype done.
Also not a good plan. It's much easier to write it well the first time through.
e.g.,
// after creating all of your JButtons, put them in an array...
JButton[] btnArray = {newPuzzle, loadImage, assignLocation, assignTimestamp,
savePuzzle, clearPuzzleCreator};
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 5, 0));
for (JButton btn : btnArray) {
buttonPanel.add(btn);
}
mainPuzzlerPanel.add(buttonPanel, BorderLayout.NORTH);
Edit: Oops, I notice now you're using Buttons and Panels, not JButtons and JPanels. I urge you to change your app to be a Swing app not an AWT app.
Layout manager tutorial: Laying Out Components Within a Container

Add ButtonGroup to JPanel

JPanel.add(ButtonGroup);
Is not working. I MUST add it to a JPanel because I am using tabs.
This is getting really frustrating.I hace not found a way yet
As ButtonGroup is not a component, you cannot add your ButtonGroup to a JPanel. Instead add your buttons to your JPanel, e.g:
JPanel jPanel = new JPanel();
ButtonGroup group = new ButtonGroup();
btn1 = new JRadioButton("btn1 ");btn1.setSelected(true);
btn2 = new JRadioButton("btn2 ");
group.add(btn1 );
group.add(btn2 );
jPanel.add(btn1);
jPanel.add(btn2).
Hope it will be useful.
Thanks
The ButtonGroup class creates only a logical radio button selection group, not a physical one, and is responsible for ensuring that only one button is selected (by deselecting others in the group).

Categories

Resources