How to randomly select a button in a ButtonGroup of JRadioButtons? - java

I want to have a random radio button to be selected whenever this panel gets initialized, but I'm not sure how/if I can do that.
Is there a way to get a random button from the group and select it?
import javax.swing.*;
public class RandomPanel extends JPanel
{
private ButtonGroup buttonGroup;
private String[] buttonText =
{
"Red",
"Mashed Potatoes",
"Metal",
"Running",
"Butts",
"Turquoise"
};
public RandomPanel()
{
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
setBorder(BorderFactory.createTitledBorder("Random Selections"));
buttonGroup = new ButtonGroup();
for (String text : buttonText)
{
JRadioButton option = new JRadioButton(text);
add(option);
button.add(option);
}
}
}

What you can do is keep a list/array of all the radio buttons you create, and then set the selected by using the button group's setSelected() method, something like this
buttonGroup.setSelected(buttonsArray[randomButtonNum].getModel(), true);

Try using the Randomclass .
// Library location
import java.util.Random;
//Inside some method
Random r = new Random();
randomIndex = r.nextInt(buttonText.length());
text = buttonText[randomIndex];
This will need arranging to suit your implementation, whats shown is a 'how-to' usage.
Note: the argument to nextInt(args) is exclusive. i.e. will return
0 <= x < args

I believe you are looking for something like the solution below.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.*;
public class RandomPanel extends JPanel
{
private ButtonGroup buttonGroup;
private String[] buttonText =
{
"Red",
"Mashed Potatoes",
"Metal",
"Running",
"Butts",
"Turquoise"
};
private JRadioButton[] radioButton;
Random r = new Random();
public RandomPanel()
{
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
setBorder(BorderFactory.createTitledBorder("Random Selections"));
buttonGroup = new ButtonGroup();
radioButton = new JRadioButton[buttonText.length];
for(int rb=0; rb<buttonText.length; rb++)
{
radioButton[rb] = new JRadioButton(buttonText[rb]);
add(radioButton[rb]);
buttonGroup.add(radioButton[rb]);
}
JButton b = new JButton("Random");
b.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
selectRandomButton();
}
});
add(b);
}
public void selectRandomButton()
{
radioButton[r.nextInt(radioButton.length)].setSelected(true);
}
public static void main(String[] args)
{
JFrame f = new JFrame("Test Random Button");
f.setSize(300, 300);
f.setLocationRelativeTo(null);;
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new RandomPanel());
f.setVisible(true);;
}
}

I created a small method that allow me to set any radio group button. Very convenient if you don't want to use if for any radio button.
public void setButtonGroup(int rdValue, Enumeration elements ){
while (elements.hasMoreElements()){
AbstractButton button = (AbstractButton)elements.nextElement();
if(Integer.parseInt(button.getActionCommand())==rdValue){
button.setSelected(true);
}
}
}
then
setButtonGroup(randomIndex, yourButtonGroup.getElements());

Related

Java - get JRadioButton cmd with Jbutton listener

I am new to java and creating a Simple gui App. In this simple app, I am trying to write a e-commerce letter for Firms. So, I planned my app something like this..
First i ask to user if he want to write an letter to British Firm or American. For this i use two radio buttons(one for american firm and second for british) and JButton. When user Trigger jbutton then i want to get radiobutton command(which type of letter user want to write).
The problem is I don't have any idea to get Radiobutton command when i trigger jButton. Please give me an Simple Idea(if possible with exapmle not complicated for begginers) to get RadioButtons value..
Here is my java Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class englet{
static public JFrame f;
static public JPanel p;
static class getTypeOfLetter implements ActionListener{
public void actionPerformed( ActionEvent e){
String btnInput = e.getActionCommand();
System.out.println(btnInput);
}
}
public static void askletter(){
JRadioButton btnRadio1;
JRadioButton btnRadio2;
ButtonGroup btngrp;
JButton btnGo = new JButton("Write");
btnRadio1 = new JRadioButton("Write Letter For American Firm");
btnRadio1.setActionCommand("Amer");
btnRadio2 = new JRadioButton("Write Letter For British Firm");
btnRadio2.setActionCommand("Brit");
btngrp = new ButtonGroup();
btnGo.setActionCommand("WriteTest");
btnGo.addActionListener(new getTypeOfLetter());
btngrp.add(btnRadio1);
btngrp.add(btnRadio2);
p.add(btnRadio1);
p.add(btnRadio2);
p.add(btnGo);
}
englet(){
f = new JFrame("English Letter");
p = new JPanel();
askletter();
f.add(p);
f.setSize(400,200);
f.setVisible(true);
}
public static void main (String[] argv ){
englet i = new englet();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
I am using Notepad++ and CMD.. Not any another tools like netbeans initllli ecplisse.
**RE-EDIT ** I want a possible solution and can satisfy me.. this app works but i am not able to get radiobuttons commmand with jubtton..
You've got several issues:
Over-use of static. Most of the fields and methods of your code should be non-static
You're missing key fields that will be necessary to transmit the information needed. To get the selected JRadioButton, you need to make JRadioButton fields and check which is selected, or (and my preference), you need to make the ButtonGroup variable a field and check which JRadioButton has been selected based on the ButtonModel returned by the ButtonGroup.
You're currently using local variables and these won't be visible throughout the class, which is why either the JRadioButtons or the ButtonModel most be fields (declared in the class).
If you go with ButtonModel above, you must give each JRadioButton an appropriate actionCommand String.
For example:
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class GetRadio extends JPanel {
private static final String[] FIRMS = {"American Firm", "British Firm"};
// You need this field to access it in your listener
private ButtonGroup buttonGroup = new ButtonGroup();
public GetRadio() {
// create JButton and add ActionListener
JButton button = new JButton("Select");
button.addActionListener(new ButtonListener());
// JPanel with a grid layout with one column and variable number of rows
JPanel radioButtonPanel = new JPanel(new GridLayout(0, 1));
radioButtonPanel.setBorder(BorderFactory.createTitledBorder("Select Firm")); // give it a title
for (String firm : FIRMS) {
// create radiobutton and set actionCommand
JRadioButton radioButton = new JRadioButton(firm);
radioButton.setActionCommand(firm);
// add to button group and JPanel
buttonGroup.add(radioButton);;
radioButtonPanel.add(radioButton);
}
// add stuff to main JPanel
add(radioButtonPanel);
add(button);
}
private class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
// get button model of selected radio button from ButtonGroup
ButtonModel model = buttonGroup.getSelection();
// if null, no country selected
if (model == null) {
Component component = GetRadio.this;
String message = "You must first select a country!";
String title = "Error: No Country Selected";
int type = JOptionPane.ERROR_MESSAGE;
JOptionPane.showMessageDialog(component, message, title, type);
} else {
// valid country selected
String country = model.getActionCommand();
System.out.println("Letter to " + country);
}
}
}
private static void createAndShowGui() {
GetRadio mainPanel = new GetRadio();
JFrame frame = new JFrame("Get Radio Btn");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

JApplet will not initialize when Listener is added to jcheckBox

Alright, since it didn't work out last time. I'm going to post my full code here and i hope i can get some replies as to why it's not working. I'm not getting any compiling errors, the applet runs and then nothing shows up and at the bottom it says "applet not initialized." I'm using blueJ. I apologize for the length of this post, I could not figure out how to make this same error with a shorter code.
I have a JApplet program with multiple classes. RegPanel,WorkshopPanel, ConferenceGUI, ConferenceHandler and ConferenceClient. Basically RegPanel and WorkShop panel are added to the ConferenceGUI, which also creates and adds a couple small panels. The ConferenceClient class is just used to initaite the class to run the applet. The ConferenceHandler is used to handle the action events for the JButtons, JTextArea, JCheckBox, etc... Normally this whole program works fine. Except when i add a listener for the JCheckBox, it stops working. The problem area is in the ConferenceGUI class, it is commented with stars to be clear what's causing the problem.
I've been stuck on this error for about a day now and the frustration i'm feeling is overwhelming. So, to get to the point, here's the complete code:
(please, i don't need tips on any other part of the code, I just need help with that error). You may want to skip over the code and just read the ConferenceGUI class where the error is located. If you could also explain to me why this isn't working, it would be very helpful to me. Thank you in advance!
RegPanel Class:
import java.awt.*; import java.awt.event.*; import javax.swing.*;
public class RegPanel extends JPanel
{
protected JTextField regNameTextBox;
protected JCheckBox keynoteCheckBox;
protected final String[] REGTYPES = {"Please select a type","Business","Student","Complimentary"};
protected JPanel registrationPanel, keynotePanel;
protected final double BUSINESSFEE = 895,STUDENTFEE = 495,COMPLIMENTARYFEE = 0;
protected JComboBox regTypeComboBox;
public RegPanel()
{
//Set the layout for the RegPanel to be 2 rows and 1 column.
setLayout(new GridLayout(2, 1));
//initiate the registration panel and add a border
registrationPanel = new JPanel();
registrationPanel.setLayout(new FlowLayout());
registrationPanel.setBorder(BorderFactory.createTitledBorder("Registrant's Name & Type"));
//initiate the comboBox and add the registration types
regTypeComboBox = new JComboBox(REGTYPES);
//Initiate the textfield with a size of 20
regNameTextBox = new JTextField(20);
//Add the registration name textbox and type combobox to the registration panel
registrationPanel.add(regNameTextBox);
registrationPanel.add(regTypeComboBox);
//initiate the second panel for the checkbox
keynotePanel = new JPanel();
keynotePanel.setLayout(new FlowLayout());
//initiate the checkbox and add it to the keynote panel
JCheckBox keynoteCheckBox = new JCheckBox("Dinner and Keynote Speach");
keynotePanel.add(keynoteCheckBox);
//Add the two panels to the main panel
add(registrationPanel);
add(keynotePanel);
}
public double getRegistrationCost()
{
double regFee = 0;
String comboBoxAnswer = (String)regTypeComboBox.getSelectedItem();
switch (comboBoxAnswer)
{
case "Business": regFee = BUSINESSFEE;
break;
case "Student": regFee = STUDENTFEE;
break;
}
return regFee;
}
public double getKeynoteCost()
{
double keynoteCost = 0;
if(keynoteCheckBox.isSelected())
{
keynoteCost = 30;
}
return keynoteCost;
}
public String getRegType()
{
String regType = (String)regTypeComboBox.getSelectedItem();
return regType;
}
}
WorkshopPanel Class:
import java.awt.*; import java.awt.event.*; import javax.swing.*;
public class WorkshopPanel extends JPanel
{
protected final double ITFEE = 295, DREAMFEE = 295, JAVAFEE = 395, ETHICSFEE = 395;
protected final String[] WORKSHOPS = {"IT Trends in Manitoba","Creating a Dream Career","Advanced Java Programming","Ethics: The Challenge Continues"};
protected JList workshopList;
public WorkshopPanel()
{
setLayout(new FlowLayout());
workshopList = new JList(WORKSHOPS);
workshopList.setSelectionMode(2);
BorderFactory.createTitledBorder("Workshops");
add(workshopList);
}
public double getWorkshopCost()
{
Object[] workshops = workshopList.getSelectedValues();
double cost = 0;
String workshopString;
for (int i = 0; i < workshops.length; i++)
{
workshopString = (String)workshops[i];
switch(workshopString)
{
case "IT Trends in Manitoba":
cost += ITFEE;
break;
case "Creating a Dream Career":
cost += DREAMFEE;
break;
case "Advanced Java Programming":
cost += JAVAFEE;
break;
case "Ethics: The Challenge Continues":
cost += ETHICSFEE;
break;
}
}
return cost;
}
public Object[] getWorkshopList()
{
Object[] workshopListArray = workshopList.getSelectedValues();
return workshopListArray;
}
}
ConferenceGUI class (THIS CONTAINS THE ERROR):
import java.awt.*; import java.awt.event.*; import javax.swing.*;
public class ConferenceGUI extends JPanel
{
protected JPanel titlePanel, buttonPanel;
protected RegPanel regPanel;
protected WorkshopPanel workshopPanel;
protected JLabel titleLabel;
protected JButton calculateButton, clearButton;
protected JTextArea resultArea;
protected JScrollPane textScroll;
public ConferenceGUI()
{
setLayout(new BorderLayout());
titlePanel = new JPanel();
titleLabel = new JLabel("Select Registration Options",JLabel.CENTER);
Font titleFont = new Font("SansSerif", Font.BOLD, 18);
titleLabel.setFont(titleFont);
titlePanel.add(titleLabel);
add(titlePanel, BorderLayout.NORTH);
regPanel = new RegPanel();
add(regPanel, BorderLayout.WEST);
workshopPanel = new WorkshopPanel();
add(workshopPanel, BorderLayout.EAST);
buildButtonPanel();
add(buttonPanel, BorderLayout.SOUTH);
ConferenceHandler handler = new ConferenceHandler(this);
regPanel.regTypeComboBox.addItemListener(handler);
regPanel.regNameTextBox.addFocusListener(handler);
//****************************************************************
//The line below is what causes the error. Without it the code
//Works, with it it doesn't and i get the aforementioned error.
//regPanel.keynoteCheckBox.addItemListener(handler);
}
private void buildButtonPanel()
{
buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
calculateButton = new JButton("Calculate Charges");
buttonPanel.add(calculateButton);
clearButton = new JButton("Clear");
buttonPanel.add(clearButton);
resultArea = new JTextArea(5,30);
textScroll = new JScrollPane(resultArea);
buttonPanel.add(textScroll);
ConferenceHandler handler = new ConferenceHandler(this);
calculateButton.addActionListener(handler);
clearButton.addActionListener(handler);
}
}
ConferenceHandler class( this class is unfinished until i get that error straightened out) :
import java.awt.*; import java.awt.event.*; import javax.swing.*;
public class ConferenceHandler implements ActionListener, ItemListener, FocusListener
{
protected ConferenceGUI gui;
public ConferenceHandler(ConferenceGUI gui)
{
this.gui = gui;
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == gui.calculateButton)
{
String regType = gui.regPanel.getRegType();
Object[] workshopList = gui.workshopPanel.getWorkshopList();
String workshopString;
if (regType == "Please select a type")
{
JOptionPane.showMessageDialog(null,"Please select a registration type","Type Error",JOptionPane.ERROR_MESSAGE );
}
else
{
if(gui.regPanel.keynoteCheckBox.isSelected())
{
gui.resultArea.append("Keynote address will be attended/n");
}
else
{
gui.resultArea.append("Keynot address will not be attended/n");
}
}
}
if (e.getSource() == gui.clearButton)
{
gui.resultArea.append("CLEAR");
}
}
private double getTotalCharges()
{
double charges = 0;
return charges;
}
public void itemStateChanged(ItemEvent e)
{
}
public void focusLost(FocusEvent e)
{
}
public void focusGained(FocusEvent e)
{
}
}
ConferenceClient Class:
import java.awt.*; import java.awt.event.*; import javax.swing.*;
public class ConferenceClient extends JApplet
{
private final int WINDOW_HEIGHT = 700, WINDOW_WIDTH = 250;
private ConferenceGUI gui;
private Container c;
public ConferenceClient()
{
gui = new ConferenceGUI();
c = getContentPane();
c.setLayout(new BorderLayout());
c.add(gui, BorderLayout.CENTER);
setSize(WINDOW_HEIGHT, WINDOW_WIDTH);
}
}
You're shadowing your keynoteCheckBox variable. First you create a instance field in RegPanel, but in the constructor, you redeclare it...
public class RegPanel extends JPanel {
protected JCheckBox keynoteCheckBox;
//...
public RegPanel() {
//...
//initiate the checkbox and add it to the keynote panel
JCheckBox keynoteCheckBox = new JCheckBox("Dinner and Keynote Speach");
keynotePanel.add(keynoteCheckBox);
This leaves the instance field as null which will cause a NullPointerException
Also, this: regType == "Please select a type" is not how to compare Strings in Java, you want to use something more like "Please select a type".equals(regType)

Java Radio Buttons within Radio Buttons

I have learnt to create a menu with radio buttons using java, but I want to know how to make radio buttons WITHIN radio buttons. The real problem is that I have finally created the radio buttons 'within' a radio button by displaying a new menu with a new group of buttons, but whenever I click on these new radio buttons, nothing happens. It is as if the buttons are not being listened to. Here is my code (example, but still the same idea):
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TestRadioButtons extends JPanel implements ActionListener
{
private String test = "Test Button 1";
private String random = "RANDOM";
private String test2 = "Button to Click";
private String random2 = "RANDOM MK. 2";
private static boolean menu = false;
public TestRadioButtons()
{
super(new BorderLayout());
//creates first set of radio buttons
JRadioButton testButton = new JRadioButton(test);
testButton.setMnemonic(KeyEvent.VK_T);
testButton.setActionCommand(test);
JRadioButton randomButton = new JRadioButton(random);
randomButton.setMnemonic(KeyEvent.VK_R);
randomButton.setActionCommand(random);
//groups the first set of buttons
ButtonGroup group1 = new ButtonGroup();
group1.add(testButton);
group1.add(randomButton);
//register listener for first radio buttons
testButton.addActionListener(this);
randomButton.addActionListener(this);
//put first radio buttons into a column in a panel
JPanel radioPanel1 = new JPanel(new GridLayout(0, 1));
radioPanel1.add(testButton);
radioPanel1.add(randomButton);
//set first menu border
add(radioPanel1, BorderLayout.LINE_START);
setBorder(BorderFactory.createEmptyBorder(20,20,20,250));
//I also have it so that if the a boolean value equals true, the following menu appears:
if (menu == true)
{
JRadioButton test2Button = new JRadioButton(test2);
test2Button.setMnemonic(KeyEvent.VK_A);
test2Button.setActionCommand(test2);
JRadioButton random2Button = new JRadioButton(random2);
random2Button.setMnemonic(KeyEvent.VK_B);
random2Button.setActionCommand(random2);
ButtonGroup group2 = new ButtonGroup();
group2.add(test2Button);
group2.add(random2Button);
test2Button.addActionListener(this);
random2Button.addActionListener(this);
JPanel radioPanel2 = new JPanel(new GridLayout(0, 1));
radioPanel2.add(test2Button);
radioPanel2.add(random2Button);
add(radioPanel2, BorderLayout.LINE_START);
setBorder(BorderFactory.createEmptyBorder(20,20,20,250));
}
}
public static void menu2()
{
JFrame innerMenu = new JFrame();
innerMenu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent innerComponent = new TestRadioButtons();
innerComponent.setOpaque(true);
innerMenu.setContentPane(innerComponent);
innerMenu.pack();
innerMenu.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if (test.equals(e.getActionCommand()))
{
menu = true;
menu2();
if (test2.equals(e.getActionCommand()))
{
JOptionPane.showMessageDialog(null, "This is just a TEST!");
}
}
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("Radio Button Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent component = new TestRadioButtons();
component.setOpaque(true);
frame.setContentPane(component);
frame.pack();
frame.setVisible(true);
}
public static void main (String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}
If anyone is able to help me (as well as fix up my code in the part where I create the new menu), I would be grateful.
Just a } problem
Change your public void actionPerformed(ActionEvent e) like this
public void actionPerformed(ActionEvent e)
{
if (test.equals(e.getActionCommand()))
{
menu = true;
menu2();
}
if (test2.equals(e.getActionCommand()))
{
JOptionPane.showMessageDialog(null, "This is just a TEST!");
}
}

How to enable a button only after a radio button was pressed in java JFrame

After a lot of googling i still haven't found what im looking for, mostly because i don't know what i'm looking for.
Basically i want the lock in button to be disabled until one of the radio buttons is selected, and i only want one of the radio buttons to be selected at a a time.
I haven't done any formatting yet so its still ugly.
My JFrame
My Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.*;
public class Game extends JFrame
{
JLabel lblQuestion;
JRadioButton btA;
JRadioButton btB;
JRadioButton btC;
JRadioButton btD;
JButton btLock;
JTextField txtQuestion;
int question = 0;
public Game()
{
getContentPane().setLayout(null);
setupGUI();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
void setupGUI()
{
txtQuestion = new JTextField();
txtQuestion.setLocation(10,10);
txtQuestion.setSize(100,25);
txtQuestion.setText(Integer.toString(question));
getContentPane().add(txtQuestion);
lblQuestion = new JLabel();
lblQuestion.setLocation(50,82);
lblQuestion.setSize(300,50);
lblQuestion.setText("No_Label");
getContentPane().add(lblQuestion);
btA = new JRadioButton();
btA.setLocation(50,160);
btA.setSize(100,50);
btA.setText("No_Label");
btA.setSelected(false);
getContentPane().add(btA);
btB = new JRadioButton();
btB.setLocation(250,160);
btB.setSize(100,50);
btB.setText("No_Label");
btB.setSelected(false);
getContentPane().add(btB);
btC = new JRadioButton();
btC.setLocation(50,240);
btC.setSize(100,50);
btC.setText("No_Label");
btC.setSelected(false);
getContentPane().add(btC);
btD = new JRadioButton();
btD.setLocation(250,240);
btD.setSize(100,50);
btD.setText("No_Label");
btD.setSelected(false);
getContentPane().add(btD);
btLock = new JButton();
btLock.setLocation(150,303);
btLock.setSize(100,50);
btLock.setText("Lock in");
getContentPane().add(btLock);
btLock.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
question = question + 1;
txtQuestion.setText(Integer.toString(question));
try{
ArrayList<String> list = questions(question);
}catch(Exception ex){}
}
});
setTitle("Who wants to be a millionare");
setSize(570,400);
setVisible(true);
setResizable(true);
setLocationRelativeTo(null);
}
public ArrayList<String> questions(int quesion) throws IOException{
File file = new File("questions.txt");
if (!file.exists()){
throw new FileNotFoundException("Could not find \"users\" file");
}
FileReader fr = new FileReader(file.getAbsoluteFile());
BufferedReader br = new BufferedReader(fr);
ArrayList<String> list = new ArrayList<String>();
String s;
for(int i = 0; i*4 <= quesion; i++){
br.readLine();
}
while((s=br.readLine()) !=null){
list.add(s);
}
br.close();
return list;
}
public static void main( String args[] )
{
new Game();
}
}
First you need to add an action listener to whichever RadioButton needs to be pressed before the button is active.
Like this:
someRadioButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
someButton.enabled(true);
}
});
And secondly for the only one RadioButton used at a time you need a ButtonGroup such as:
ButtonGroup myButtonGroup = new ButtonGroup();
myButtonGroup.add(someRadioButton);
Add all the RadioButtons you want into a group.
Hope this helps :)
Start by taking a look at How to Use Buttons, Check Boxes, and Radio Buttons.
You can use a ButtonGroup to ensure that only one button within the group is selected
You can use an ActionListener to detect changes to the JRadioButton state

Limit the number of selected JToggleButton

I'm new on swing java, I maked an array of jtoggle buttons and my problem is that I want to limit the number of selected(toggled) buttons for 4 toggled buttons. Is there any property that allows me to do that ?
Here is my code example.
package adad;
import java.awt.*; import java.awt.event.*;
import javax.swing.*;
public class essayer extends JFrame
{
private JToggleButton jb_essai[] = new JToggleButton[6];
JButton pressme = new JButton("Press Me");
essayer() // the frame constructor
{
super("Toggle boutons");
setBounds(100,100,300,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container con = this.getContentPane();
JPanel pane = getContainer();
con.add(pane);
setVisible(true);
}
class ToggleAction implements ActionListener
{
private JToggleButton jb_essai[];
public ToggleAction(JToggleButton a_jb_essai[])
{
jb_essai = a_jb_essai;
}
public void actionPerformed(ActionEvent e)
{
String etatBoutons = "";
int size = jb_essai.length;
for(int i=0;i<size;i++)
{
String tmp = "Bouton "+(i+1)+" : ";
if(jb_essai[i].isSelected()==true )
{
tmp+="enfonce";
}
else
{
tmp+="relache";
}
tmp+="\n";
etatBoutons +=tmp;
}
System.out.println(etatBoutons+"\n---------");
}
}
private JPanel getContainer()
{
GridLayout thisLayout = new GridLayout(6,2);
JPanel container = new JPanel();
ToggleAction tga = new ToggleAction(jb_essai);
container.setLayout(thisLayout);
int j=6;
for (int i=0;i<j;i++)
{
String s = String.valueOf(i+1);
container.add(jb_essai[i]= new JToggleButton(s)); // actuellement tt s'affiche sur un même colone.
jb_essai[i].addActionListener(tga);
}
return container;
}
public static void main(String[] args) {new essayer();}
}
Is there any property that allows me to do that ?
No. There is a ButtonGroup that allows 'one of many'. But that is 1, not N of many. Anything beyond that you'll need to code yourself.
Is there any property that allows me to do that ?
No, you need to write your own code.
Add a common ItemListener to every toggle button. Then when a button is selected you loop though your toggle button array to count the number of selected toggle buttons.
If the count is greater than 4 then you display a JOptionPane with an error message and your reset the last selected button to be unselected. You can use the getSource() method of the ItemListener to get the toggle button.
Or maybe you can extend the ButtonGroup class to implement similar behaviour.

Categories

Resources