how to assign value to a checked JChechbox? - java

I am making a simple currency convertor which takes the initial value in a JTextField then the user clicks the JCheckBox corresponding to their desired currency, the converted value will then be displayed in another JTextField. Basically i would like to know is there any way of assigning a value to a checked JCheckBoxi have looked around and cannot find a clear answer to this, any help would be appreciated.
For example if the current conversion rate from Sterling to euro is 1.12244 this value would be assigned when the JCheckBox is checked, so the the original value would be multiplied by the conversion rate.

Think it'd be easier if you assign an action-listener to your JCheckBox and make the conversion on trigger of this event. To check is a JCheckBox is checked or not you can use the isSelected() method
EDIT
Actually i think you need to use JRadioButton's in a ButtonGroup for this, as if you are using a checkbox then there is a chance that more than one is selected. Here is an example of how to do use ButtonGroup and trigger action on the radio button

This would give you the value of the check box.
JCheckBox cb = ...;
// Determine status
boolean isSel = cb.isSelected();
if (isSel) {
// The checkbox is now selected
} else {
// The checkbox is now deselected
}
You can change the value on the action-listener of the JCheckBox
// Create an action
Action action = new AbstractAction("CheckBox Label") {
// This method is called when the button is pressed
public void actionPerformed(ActionEvent evt) {
// Perform action
JCheckBox cb = (JCheckBox)evt.getSource();
// Determine status
boolean isSel = cb.isSelected();
if (isSel) {
// The checkbox is now selected
} else {
// The checkbox is now deselected
}
}
};
// Create the checkbox
JCheckBox checkBox = new JCheckBox(action);

// this is whole working code i hope this this will help
public class CConvertor extends JFrame {
private JLabel result;
private JCheckBox pk;
private JCheckBox ch;
public CConvertor(){
result = new JLabel();
ch = new JCheckBox();
pk = new JCheckBox();
init();
}
public void init(){
setTitle("JCheckBox Test");
getContentPane().setLayout(new FlowLayout());
add(result);
add(new JLabel(" "));
add(new JLabel(" China "));
add(ch);
add(new JLabel(" Pakistan "));
add(pk);
setSize(400,80);
pk.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ch.setSelected(false);
result.setText("Pakistan selected");
}
});
ch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
pk.setSelected(false);
result.setText("China is Selected");
}
});
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
new CConvertor();
}
}

This could not be the best solution but you can try this.
Take an array of JCheckBox.
Make sure only one checkbox gets selected at a time.
Take an array of currency conversion value.
Now based on the index of the selected checkbox get the currency conversion value from array.
Instead of using JCheckBox you can use JRadioButton as suggested by #Balanivash. More simpler and proper solution will be using JComboBox.[I'm with #Riduidel in this.]

I also think that JCheckBox isn't the best option to do what you want, however...
Why don't you extend the JCheckBox class to a CurrencyConverterCheckBox where you can
pass as arguments the currencies and the current value of the conversion.
e.g.:
public class CurrencyConverterCheckBox extends JCheckBox {
private String from;
private String to;
private double value;
public CurrencyConverterCheckBox(String from, String to, double value) {
super();
this.from = from;
this.to = to;
this.value = value;
}
}
Then you will be able to do the conversion when the user clicks the checkbox. You can also provide labels next to the checkboxes (USD to EUR). And you can also provide a method in your new checkbox to flip the currencies and calculate the multiplication factor in the other direction.
kind regards

What it's easiest to do is something like this:
String[] ccys = {"USD", "EUR", "CHF", "JPY"};
public void initUI(){
...
ButtonGroup grp = new ButtonGroup();
for(String ccy : ccys){
JCheckBox cb = new JCheckBox(ccy);
cb.setActionCommand(ccy);
cb.addActionListener(this);
grp.add(cb);
...(add CheckBox to ui)
}
}
private double getRate(String ccy){
...(retrieve the current conversion rate, f.ex from a map)
}
public void actionPerformed(ActionEvent evt){
Double rate = getRate(evt.getActionCommand());
...(calculation, display)
}

Related

How to change a Jbutton's function on clicking another Jbutton?

I am writing a program which will convert weight in pounds to kilograms and also weight in Kilograms to pounds. The output window is as follows:
When I want to convert Kilograms to Pounds I click switch button and the output changes as follows:
But the problem is when I click "Convert" it still converts weight to Kilogram instead of Pounds.
I want the "Convert" button's function to change when I click the "Switch" button so it will convert the weight in Kilograms to pounds. Please help.
My source code is as follows:
public class convertApp extends JFrame implements ActionListener {
private JLabel poundlbl = new JLabel("Weight in Pounds");
private JLabel kglbl = new JLabel("Weight in Kilograms");
private JTextField poundbx= new JTextField(12);
private JTextField kgbx= new JTextField(12);
private JButton conbtn=new JButton("Convert");
private JButton switchbtn=new JButton("Switch");
private JButton newconbtn=new JButton("Convert");
private JPanel bxPanel = new JPanel();
public convertApp(){
super("Weight Converter");
bxPanel.setLayout(new GridLayout(5,29,5,5));
bxPanel.add(poundlbl);
bxPanel.add(poundbx);
bxPanel.add(kglbl);
bxPanel.add(kgbx);
bxPanel.add(conbtn);
bxPanel.add(switchbtn);
//bxPanel.setBackground(Color.gray);
this.setLayout(new GridLayout(1,1,0,0));
this.add(bxPanel);
this.setVisible(true);
//what to do if i close
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//put window in the center
this.setLocationRelativeTo(null);
//disable resize
this.setResizable(false);
//pack all the components within the window
this.pack();
conbtn.addActionListener(this);
switchbtn.addActionListener(this);
}
public void actionPerformed(ActionEvent evnt){
if(evnt.getSource()==conbtn){
String poundtext = poundbx.getText();
int pound = Integer.parseInt(poundtext);
double kilo = pound * 0.453592;
kgbx.setText(""+kilo);
}
else if(evnt.getSource()==switchbtn)
{
poundlbl.setText("Weight in Kilograms:");
kglbl.setText("Weight in Pounds:");
if(evnt.getSource()==conbtn){
String kilotext = poundbx.getText();
int kilo = Integer.parseInt(kilotext);
double pound = kilo * 2.20462;
kgbx.setText(""+pound);
}
}
}
}
Create boolean Variable
boolean switch=true;
void kiloGramToPound{
//Convert Codes Here
}
void PoundToKiloGram{
//Convert Codes Here
}
Convert Button actionPerformed
if(switch==true){
kiloGramToPound();
}else{
PoundToKiloGram();
}
Switch Button actionPerformed
if(switch==true){
switch=false;
}else{
switch=true;
}
You cannot change the function itself. You can create a flag that sets true or false (your choice) when you click the 'switch' button. Then check the value of that flag when you click 'convert' and perform the appropriate conversion according to your flag convention.
i.e.
Boolean isPtoK = true;
// [...]
if(isPtoK){
// convert pounds to kilos
} else{
// kilos to pounds
}
I would create a separate function that switches the value of your flag when 'switch' is clicked.
Apologies for not answering your question, but may I suggest you to try KeyListener/KeyAdapter instead of the combination of ActionListeners and buttons.
Example:
textField1.addKeyListener(new ConverterListener(textField2, "2.20462"));
textField2.addKeyListener(new ConverterListener(textField1, "0.453592"));
class ConverterListener extends KeyAdapter {
JTextField destination;
String multiplier;
public ConverterListener(JTextField destination, String multiplier) {
this.destination = destination;
this.multiplier = multiplier;
}
#Override
public void keyReleased(KeyEvent e) {
JTextField source = (JTextField) e.getSource();
String result = convert(source.getText(), multiplier);
destination.setText(result);
}
private String convert(String value, String multiplier) {
String result = "0";
try {
double dblValue = value.isEmpty() ? 0d : Double.parseDouble(value);
double dblMultiplier = value.isEmpty() ? 0d : Double.parseDouble(multiplier);
result = Double.toString(dblValue * dblMultiplier);
} catch (Exception e) {
System.out.println(e);
}
return result;
}
}

I need to add listeners to the checkboxes and changes in selection is shown in the textArea

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class JDorm implements ItemListener{
public static void main(String[] args){
JCheckBox privateroom = new JCheckBox("Private Room",false);
JCheckBox interweb = new JCheckBox("Internet Connection",false);
JCheckBox cable = new JCheckBox("Cable TV connection",false);
JCheckBox fridg = new JCheckBox("Refridgerator",false);
JCheckBox microwave = new JCheckBox("Microwave",false);
JCheckBox soon = new JCheckBox(",and so on",false);
JLabel greet = new JLabel("Please choose ammenities");
String sel = "Your selected options";
JTextArea textBox = new JTextArea(sel,0,1);
cable.addItemListener();
JFrame dormFrame = new JFrame("Dorm Options");// creates frame with title
final int WIDTH = 250;
final int HEIGHT = 500;
dormFrame.setSize(WIDTH, HEIGHT);// sets the size of frame in pixels
dormFrame.setVisible(true);// note: default visibility is false
dormFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
dormFrame.setLayout(new FlowLayout());
dormFrame.add(greet);
dormFrame.add(microwave);
dormFrame.add(fridg);
dormFrame.add(cable);
dormFrame.add(interweb);
dormFrame.add(privateroom);
dormFrame.add(soon);
dormFrame.add(textBox);
}
public void itemStateChanged(ItemEvent event){
Object source = event.getSource();
int select = event.getStateChange();
}
}
This is what I have so far, I know I need listeners, and a message to appear in the box when selection is checked and unchecked.
Do I need if statements for the changes?
Create a generic listener that can be added to all the check boxes. Something like:
ItemListener listener = new ItemListener()
{
public void itemStateChanged(ItemEvent event)
{
JCheckBox checkBox = (JCheckBox)event.getSource();
textBox.setText( checkBox.getText() );
}
};
Then you add the listener to each check box:
privateRoom.addItemListener( listener );
interweb.addItemListener( listener );
I have tried for one Checkbox and you can do others similarly
final JCheckBox privateroom = new JCheckBox("Private Room",false);
Now add item listener to checkbox privateroom and also the actions which you would like to happen i.e.
privateroom.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent event)
{
if (event.getItemSelectable() == privateroom)
textBox.setText("Private Room");
}
});
The reason i have declared Checkbox privaterroom as final is because privaterroom is local and is being accessed from an inner class.
One more thing I don't know the way you have written your program is good or bad because I am also learning swing and am a newbie. But the way i write my program has the following structure
class MyClass extends JFrame implements LISTENER_NAME
{
// Components declared here
// constructor starts
public MyClass()
{
//Componenets instantiated
// add listeners to appropriate components
// setVisible(), setDefaultCloseOperation(),setSize() etc called
}
// listener interface methods here like
public void itemStateChanged(ItemEvent ie)
{
................
}
// main method
public static void main(String[] args)
{
new MyClass();
}
} // class over
This way I have never encountered the final keyword etc problems. I hope some expert will guide us.

case sensitive jcombobox

My problem is a bit tricky. I am using an Editable JComboBox. It may contain case sensitive items. For example, it may have Item1 and item1. So, these two items should be treated as different in my case.
But the problem is, these two items is treated as same. No matter which Items I have selected, it always select the first one (Item1). I've searched in Google, but didn't find any solution. That's why, I am here.
Code:
//loading of Items
jdcbmItemType = new javax.swing.DefaultComboBoxModel(ItemTypeHandler.getItemTypeComboData(MainFrame.companyId));
private void jcbItemTypeMouseReleased(MouseEvent evt)
{
if (jcbItemType.getSelectedIndex() != -1)
{
loadItemTypeDetails(((ItemObject) jcbItemType.getSelectedItem()).getId());
}
else
{
resetFields();
}
}
public static Vector<ItemObject> getItemTypeComboDataV(BigInteger companyId, BigInteger categoryId, boolean addFirstElement, TriState deleted) throws ExceptionWrapper, EJBException
{
try
{
return (Vector<ItemObject>)lookupItemTypeFacade().getItemTypeComboData(companyId, categoryId, addFirstElement, deleted);
} catch (ExceptionWrapper exceptionWrapper)
{
throw exceptionWrapper;
} catch (EJBException ejbEx)
{
throw ejbEx;
} catch (Exception ex)
{
throw new ExceptionWrapper(ex.getMessage());
}
}
ItemObject is a customClass where one field is BigInteger and another is String.
getItemTypeComboData is functioning properly. So, you can assume to get a list of ItemObject from here and it will nicely convert it to Vector<ItemObject>
jcbItemType.getSelectedIndex() always return the same index for Item1 and item1. But it returns different index for item2.
I know, it would be better if I can use itemStateChanged event. But in my case, I can't use it. But my question is, MouseReleased and FocusLost works fine for different name string but not same string with different case. I am really stumbled.
Another way to ask the question:
Does MouseReleased or FocusLost event check for case-sensitive items?
How to resolve this problem?
Thanks.
Here is my SSCCE and this works fine , If this is not what youre looking for, then post your SSCCE for better sooner help!
import javax.swing.*;
import java.awt.event.*;
public class ComboBoxTest {
JComboBox combo;
JTextField txt;
public static void main(String[] args) {
new ComboBoxTest();
}
public ComboBoxTest() {
String items[] = {"Item1", "item1"};
JFrame frame = new JFrame("JComboBox Case-sensitivity Test");
JPanel panel = new JPanel();
combo = new JComboBox(items);
combo.setEditable(true);
txt = new JTextField(10);
panel.add(combo);
panel.add(txt);
frame.add(panel);
combo.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent ie) {
String str = (String) combo.getSelectedItem();
txt.setText(str);
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 100);
frame.setVisible(true);
}
}
I think you are doing like this :-
String[] items = {"item1", "item2"};
JComboBox cb = new JComboBox(items);
cb.setEditable(true);
Now you have to access the JCombobox elements which you have insert into this as in array form like this:-
MyItemListener actionListener = new MyItemListener();
cb.addItemListener(actionListener);
class MyItemListener implements ItemListener {
// This method is called only if a new item has been selected.
public void itemStateChanged(ItemEvent evt) {
JComboBox cb = (JComboBox)evt.getSource();
// Get the affected item
Object item = evt.getItem();
if (evt.getStateChange() == ItemEvent.SELECTED) {
// Item was just selected
} else if (evt.getStateChange() == ItemEvent.DESELECTED) {
// Item is no longer selected
}
}
}
After adding the itemListener you can do your different tasks with individual JCombobox Item
Try this, it works fine...
use ActionListener() to capture the click... then use getSelectedItem() to capture the item clicked on the JComboBox
try this,
check in your console for the output
myComboBox.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent ie) {
String str = (String) myComboBox.getSelectedItem();
System.out.println(str);
}

Stopping JPopupMenu stealing the focus

I have a JTextField for which I'm hoping to suggest results to match the user's input. I'm displaying these suggestions in a JList contained within a JPopupMenu.
However, when opening the popup menu programmatically via show(Component invoker, int x, int y), the focus is getting taken from the JTextField.
Strangely enough, if I call setVisible(true) instead, the focus is not stolen; but then the JPopupMenu is not attached to any panel, and when minimizing the application whilst the box is open, it stays painted on the window.
I've also tried to reset the focus to the JTextField using requestFocus(), but then I have to restore the caret position using SwingUtilities.invokeLater(), and the invoke later side of things is giving the user a slight margin to mess around with the existing contents / overwrite it / or do other unpredictable things.
The code I've got is effectively:
JTextField field = new JTextField();
JPopupMenu menu = new JPopupMenu();
field.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
JList list = getAListOfResults();
menu.add(list);
menu.show(field, 0, field.getHeight());
}
});
Can anyone suggest the best avenue to go down to show the JPopupMenu programmatically whilst preserving the focus on the JTextField?
The technical answer is to set the popup's focusable property to false:
popup.setFocusable(false);
The implication is that the textField has to take over all keyboard and mouse-triggered actions that are normally handled by the list itself, sosmething like:
final JList list = new JList(Locale.getAvailableLocales());
final JPopupMenu popup = new JPopupMenu();
popup.add(new JScrollPane(list));
popup.setFocusable(false);
final JTextField field = new JTextField(20);
Action down = new AbstractAction("nextElement") {
#Override
public void actionPerformed(ActionEvent e) {
int next = Math.min(list.getSelectedIndex() + 1,
list.getModel().getSize() - 1);
list.setSelectedIndex(next);
list.ensureIndexIsVisible(next);
}
};
field.getActionMap().put("nextElement", down);
field.getInputMap().put(
KeyStroke.getKeyStroke("DOWN"), "nextElement");
As your context is very similar to a JComboBox, you might consider having a look into the sources of BasicComboBoxUI and BasicComboPopup.
Edit
Just for fun, the following is not answering the focus question :-) Instead, it demonstrates how to use a sortable/filterable JXList to show only the options in the dropdown which correspond to the typed text (here with a starts-with rule)
// instantiate a sortable JXList
final JXList list = new JXList(Locale.getAvailableLocales(), true);
list.setSortOrder(SortOrder.ASCENDING);
final JPopupMenu popup = new JPopupMenu();
popup.add(new JScrollPane(list));
popup.setFocusable(false);
final JTextField field = new JTextField(20);
// instantiate a PatternModel to map text --> pattern
final PatternModel model = new PatternModel();
model.setMatchRule(PatternModel.MATCH_RULE_STARTSWITH);
// listener which to update the list's RowFilter on changes to the model's pattern property
PropertyChangeListener modelListener = new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if ("pattern".equals(evt.getPropertyName())) {
updateFilter((Pattern) evt.getNewValue());
}
}
private void updateFilter(Pattern newValue) {
RowFilter<Object, Integer> filter = null;
if (newValue != null) {
filter = RowFilters.regexFilter(newValue);
}
list.setRowFilter(filter);
}
};
model.addPropertyChangeListener(modelListener);
// DocumentListener to update the model's rawtext property on changes to the field
DocumentListener documentListener = new DocumentListener() {
#Override
public void removeUpdate(DocumentEvent e) {
updateAfterDocumentChange();
}
#Override
public void insertUpdate(DocumentEvent e) {
updateAfterDocumentChange();
}
private void updateAfterDocumentChange() {
if (!popup.isVisible()) {
popup.show(field, 0, field.getHeight());
}
model.setRawText(field.getText());
}
#Override
public void changedUpdate(DocumentEvent e) {
}
};
field.getDocument().addDocumentListener(documentListener);
It looks straight forward to me. Add the following
field.requestFocus();
after
menu.add(list);
menu.show(field, 0, field.getHeight());
Of course, you will have to code for when to hide the popup etc based on what is going on with the JTextField.
i.e;
menu.show(field, field.getX(), field.getY()+field.getHeight());
menu.setVisible(true);
field.requestFocus();
You may take a look to JXSearchField, which is part of xswingx

How do I get which JRadioButton is selected from a ButtonGroup

I have a swing application that includes radio buttons on a form. I have the ButtonGroup, however, looking at the available methods, I can't seem to get the name of the selected JRadioButton. Here's what I can tell so far:
From ButtonGroup, I can perform a getSelection() to return the ButtonModel. From there, I can perform a getActionCommand, but that doesn't seem to always work. I tried different tests and got unpredictable results.
Also from ButtonGroup, I can get an Enumeration from getElements(). However, then I would have to loop through each button just to check and see if it is the one selected.
Is there an easier way to find out which button has been selected? I'm programing this in Java 1.3.1 and Swing.
I got similar problem and solved with this:
import java.util.Enumeration;
import javax.swing.AbstractButton;
import javax.swing.ButtonGroup;
public class GroupButtonUtils {
public String getSelectedButtonText(ButtonGroup buttonGroup) {
for (Enumeration<AbstractButton> buttons = buttonGroup.getElements(); buttons.hasMoreElements();) {
AbstractButton button = buttons.nextElement();
if (button.isSelected()) {
return button.getText();
}
}
return null;
}
}
It returns the text of the selected button.
I would just loop through your JRadioButtons and call isSelected(). If you really want to go from the ButtonGroup you can only get to the models. You could match the models to the buttons, but then if you have access to the buttons, why not use them directly?
You must add setActionCommand to the JRadioButton then just do:
String entree = entreeGroup.getSelection().getActionCommand();
Example:
java = new JRadioButton("Java");
java.setActionCommand("Java");
c = new JRadioButton("C/C++");
c.setActionCommand("c");
System.out.println("Selected Radio Button: " +
buttonGroup.getSelection().getActionCommand());
I suggest going straight for the model approach in Swing. After you've put the component in the panel and layout manager, don't even bother keeping a specific reference to it.
If you really want the widget, then you can test each with isSelected, or maintain a Map<ButtonModel,JRadioButton>.
You can put and actionCommand to each radio button (string).
this.jButton1.setActionCommand("dog");
this.jButton2.setActionCommand("cat");
this.jButton3.setActionCommand("bird");
Assuming they're already in a ButtonGroup (state_group in this case) you can get the selected radio button like this:
String selection = this.state_group.getSelection().getActionCommand();
Hope this helps
The following code displays which JRadiobutton is selected from Buttongroup on click of a button.
It is done by looping through all JRadioButtons in a particular buttonGroup.
JRadioButton firstRadioButton=new JRadioButton("Female",true);
JRadioButton secondRadioButton=new JRadioButton("Male");
//Create a radio button group using ButtonGroup
ButtonGroup btngroup=new ButtonGroup();
btngroup.add(firstRadioButton);
btngroup.add(secondRadioButton);
//Create a button with text ( What i select )
JButton button=new JButton("What i select");
//Add action listener to created button
button.addActionListener(this);
//Get selected JRadioButton from ButtonGroup
public void actionPerformed(ActionEvent event)
{
if(event.getSource()==button)
{
Enumeration<AbstractButton> allRadioButton=btngroup.getElements();
while(allRadioButton.hasMoreElements())
{
JRadioButton temp=(JRadioButton)allRadioButton.nextElement();
if(temp.isSelected())
{
JOptionPane.showMessageDialog(null,"You select : "+temp.getText());
}
}
}
}
import javax.swing.Action;
import javax.swing.ButtonGroup;
import javax.swing.Icon;
import javax.swing.JRadioButton;
import javax.swing.JToggleButton;
public class RadioButton extends JRadioButton {
public class RadioButtonModel extends JToggleButton.ToggleButtonModel {
public Object[] getSelectedObjects() {
if ( isSelected() ) {
return new Object[] { RadioButton.this };
} else {
return new Object[0];
}
}
public RadioButton getButton() { return RadioButton.this; }
}
public RadioButton() { super(); setModel(new RadioButtonModel()); }
public RadioButton(Action action) { super(action); setModel(new RadioButtonModel()); }
public RadioButton(Icon icon) { super(icon); setModel(new RadioButtonModel()); }
public RadioButton(String text) { super(text); setModel(new RadioButtonModel()); }
public RadioButton(Icon icon, boolean selected) { super(icon, selected); setModel(new RadioButtonModel()); }
public RadioButton(String text, boolean selected) { super(text, selected); setModel(new RadioButtonModel()); }
public RadioButton(String text, Icon icon) { super(text, icon); setModel(new RadioButtonModel()); }
public RadioButton(String text, Icon icon, boolean selected) { super(text, icon, selected); setModel(new RadioButtonModel()); }
public static void main(String[] args) {
RadioButton b1 = new RadioButton("A");
RadioButton b2 = new RadioButton("B");
ButtonGroup group = new ButtonGroup();
group.add(b1);
group.add(b2);
b2.setSelected(true);
RadioButtonModel model = (RadioButtonModel)group.getSelection();
System.out.println(model.getButton().getText());
}
}
Typically, some object associated with the selected radio button is required. It is not necessarily a String representing the button's label. It could be an Integer containing the button's index or an object of more complicated type T. You could fill and use a Map<ButtonModel, T> as Tom Hawtin suggested, but I propose to extend the model and place the objects there. Here's an improved ButtonGroup that uses this approach.
import javax.swing.*;
#SuppressWarnings("serial")
public class SmartButtonGroup<T> extends ButtonGroup {
#Override
public void add(AbstractButton b) {
throw new UnsupportedOperationException("No object supplied");
}
public void add(JRadioButton button, T attachedObject) {
ExtendedModel<T> model = new ExtendedModel<>(attachedObject);
model.setSelected(button.isSelected());
button.setModel(model);
super.add(button);
}
#SuppressWarnings("unchecked")
public T getSelectedObject() {
ButtonModel selModel = getSelection();
return selModel != null ? ((ExtendedModel<T>)selModel).obj : null;
}
public static class ExtendedModel<T> extends javax.swing.JToggleButton.ToggleButtonModel {
public T obj;
private ExtendedModel(T object) {
obj = object;
}
}
}
You can use this utility class instead of ButtonGroup. Create an object of this class and add buttons along with associated objects to it. For example,
SmartButtonGroup<Integer> group = new SmartButtonGroup<>();
JPanel panel = new JPanel();
for (int i = 1; i <= 5; i++) {
JRadioButton button = new JRadioButton("Button #" + i, i == 3); // select the 3rd button
group.add(button, i);
panel.add(button);
}
After this, you can get the object associated with the currently selected button anytime you need by simply calling getSelectedObject(), like this:
int selectedButtonIndex = group.getSelectedObject();
In case you need just the buttons themselves, you can use the next non-generic class instead.
import javax.swing.JRadioButton;
#SuppressWarnings("serial")
public class RadioButtonGroup extends SmartButtonGroup<JRadioButton> {
public void add(JRadioButton button) {
super.add(button, button);
}
#Override
public void add(JRadioButton button, JRadioButton attachedObject) {
throw new UnsupportedOperationException("Use the short form of addition instead");
}
public JRadioButton getSelectedButton() {
return getSelectedObject();
}
}
You could use getSelectedObjects() of ItemSelectable (superinterface of ButtonModel) which returns the list of selected items. In case of a radio button group it can only be one or none at all.
Add the radiobuttons to a button group then:
buttonGroup.getSelection().getActionCommand
Use the isSelected() method. It will tell you the state of your radioButton. Using it in combination with a loop(say for loop) you can find which one has been selected.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyJRadioButton extends JFrame implements ActionListener
{
JRadioButton rb1,rb2; //components
ButtonGroup bg;
MyJRadioButton()
{
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
rb1=new JRadioButton("male");
rb2=new JRadioButton("female");
//add radio button to button group
bg=new ButtonGroup();
bg.add(rb1);
bg.add(rb2);
//add radio buttons to frame,not button group
add(rb1);
add(rb2);
//add action listener to JRadioButton, not ButtonGroup
rb1.addActionListener(this);
rb2.addActionListener(this);
pack();
setVisible(true);
}
public static void main(String[] args)
{
new MyJRadioButton(); //calling constructor
}
#Override
public void actionPerformed(ActionEvent e)
{
System.out.println(((JRadioButton) e.getSource()).getActionCommand());
}
}
Ale Rojas's answer works fine:
As alternative you can also use the My_JRadiobutton11.addActionListener(this); on your JButton and then make your actions in the actionPerformed function like this (It just uses an extra variable which you have to instantiate (e.g Private String selection;) but it's not a big deal):
public void actionPerformed(ActionEvent arg0) {
if(arg0.getSource() == My_JRadiobutton11){
//my selection
selection = "Become a dolphin";
}else if(arg0.getSource() == My_JRadiobutton12){
//my selection
selection = "Become a Unicorn";
} ..etc
}
jRadioOne = new javax.swing.JRadioButton();
jRadioTwo = new javax.swing.JRadioButton();
jRadioThree = new javax.swing.JRadioButton();
... then for every button:
buttonGroup1.add(jRadioOne);
jRadioOne.setText("One");
jRadioOne.setActionCommand(ONE);
jRadioOne.addActionListener(radioButtonActionListener);
...listener
ActionListener radioButtonActionListener = new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
radioButtonActionPerformed(evt);
}
};
...do whatever you need as response to event
protected void radioButtonActionPerformed(ActionEvent evt) {
System.out.println(evt.getActionCommand());
}

Categories