Java Radio button clear/deselect - java

I am trying to deselect JRadio button while clear button is pressed. I have tried googling and gone thru lots of forum the only fix i could find is create an invisible button and while clear button is pressed select invisible one. Is there any other method i can use? My code is as follows
public class deselectRadioBtn extends JFrame {
private JRadioButton[] buttons; // array for JRadio buttons
public deselectRadioBtn() {
super("Deselect Radio");
for (int nbrOfButtons = 0; nbrOfButtons < options.length; nbrOfButtons++) {
//create new JRadioButtons and labels and add ( ) around label
buttons[nbrOfButtons] = new JRadioButton(( nbrOfButtons + radioLabel[nbrOfButtons] ));
//add buttons to eastPanel
rightPanel.add(options[nbrOfButtons]);
}//end for (JRadio)
//Create a ButtonGroup object, add buttons to the group
ButtonGroup optionSelect = new ButtonGroup();
optionSelect.add(buttons[0]);
optionSelect.add(buttons[1]);
optionSelect.add(buttons[2]);
optionSelect.add(buttons[3]);
}
This is just a piece of code and i havent include full code.

Use ButtonGroup.clearSelection().

Related

How can I get an Object's name in java

I have a group of radio buttons that doesn't includes any text on frame 1.
Every button has a j label l, which means that when I choose one radio button, I want to change the icon of a specific j label.
I want to know which button is selected to send it to frame 2 by a constructor.
So I want send the variable of the current radio button that's clicked.
How can i do that?
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;
}
JRadioButton radioA = new JRadioButton(0);
JRadioButton radioB = new JRadioButton(0);
ButtonGroup buttonGroup = new ButtonGroup();
buttonGroup.add(radioA);
buttonGroup.add(radioB);
JLabel label = new JLabel("The label");
When you click the button to go to the next frame....
if(radioA.isSelected()) {
label.setText("Radio A is Selected");
gotoNextFrame();
}
else if(radioB.isSelected()) {
label.setText("Radio B is Selected");
gotoNextFrame();
}
More - How do I get which JRadioButton is selected from a ButtonGroup

Adding a button component to a java tabbed pane in java

i am trying to create GUI using java swings.I am just a beginner in java swings.
My primary idea was to create two tabs and add a button in one of the tabs.
I wanted to write a separate class for each tab so i created 3 classes out of which one has the main method.and the other two represent the tabs.
In one of the tabs i wanted to add a button in middle and add an action listener to that button.
below is the class which has the main method.
public class abc {
JFrame frame;
JTabbedPane tabPane;
ImageIcon close;
Dimension size;
int tabCounter = 0;
abc_export exp;
abc_import imp;
public static void main(String[] args) {
abc jtab = new abc();
jtab.start();
}
public void start(){
exp=new abc_export();
imp=new abc_import();
tabPane.addTab(null, exp.panel);
tabPane.addTab(null, imp.panel);
tabPane.setTabComponentAt(tabPane.getTabCount()-1, exp.tab);
tabPane.setTabComponentAt(tabPane.getTabCount()-1, imp.tab);
}
public abc() {
// Create a frame
frame = new JFrame();
// Create the tabbed pane.
tabPane = new JTabbedPane();
// Create a button to add a tab
// Create an image icon to use as a close button
close = new ImageIcon("C:/JAVAJAZZUP/tabClose.gif");
size = new Dimension(close.getIconWidth()+1, close.getIconHeight()+1);
//Adding into frame
frame.add(tabPane, BorderLayout.CENTER);
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
};
below is code for one of the tabs.although the other tab is also having the same code which represent other tab with different class name.
public class abc_import {
ImageIcon close;
Dimension size;
int tabCounter = 0;
JPanel tab;
final JPanel panel;
public abc_import() {
close = new ImageIcon("C:/JAVAJAZZUP/tabClose.gif");
size = new Dimension(close.getIconWidth()+1, close.getIconHeight()+1);
//Adding into frame
JLabel label = null;
panel = new JPanel();
// Create a panel to represent the tab
tab = new JPanel();
tab.setOpaque(false);
String str = "abc_import";
label = new JLabel(str);
tab.add(label, BorderLayout.WEST);
}
};
as expected both the tabs are created.But i am out of ideas about adding a button inside one of the tabs.
Now my question here is if i wanted to add a button in one of the tabs as i already said.what do i need to do?can anyone help me?
I'm not sure I understand your intent, but you might try the approach shown in the TabComponentsDemo, discussed in How to Use Tabbed Panes: Tabs With Custom Components.
A related example is shown here.
You can try by using setTabComponentAt method.
This methd has the parameter setTabComponentAt(int index, Component component), in which you just mention the component you want.
You can refer a link here.

Trouble with Java GUI design

I am having trouble designing GUI's in an object oriented manner. The following code will help me express my question more clearly:
import javax.swing;
import java.awt.*;
import java.awt.event.*;
public class QuoteOptionsPanel extends JPanel
{
private JLabel quote;
private JRadioButton comedy, philosophy, carpentry;
private String comedyQuote, philosophyQuote, carpentryQuote;
//-----------------------------------------------------------------
// Sets up a panel with a label and a set of radio buttons
// that control its text.
//-----------------------------------------------------------------
public QuoteOptionsPanel()
{
comedyQuote = "Take my wife, please.";
philosophyQuote = "I think, therefore I am.";
carpentryQuote = "Measure twice. Cut once.";
quote = new JLabel (comedyQuote);
quote.setFont (new Font ("Helvetica", Font.BOLD, 24));
comedy = new JRadioButton ("Comedy", true);
comedy.setBackground (Color.green);
philosophy = new JRadioButton ("Philosophy");
philosophy.setBackground (Color.green);
carpentry = new JRadioButton ("Carpentry");
carpentry.setBackground (Color.green);
ButtonGroup group = new ButtonGroup();
group.add (comedy);
group.add (philosophy);
group.add (carpentry);
QuoteListener listener = new QuoteListener();
comedy.addActionListener (listener);
philosophy.addActionListener (listener);
carpentry.addActionListener (listener);
add (quote);
add (comedy);
add (philosophy);
add (carpentry);
setBackground (Color.green);
setPreferredSize (new Dimension(300, 100));
}
//*****************************************************************
// Represents the listener for all radio buttons.
//*****************************************************************
private class QuoteListener implements ActionListener
{
//--------------------------------------------------------------
// Sets the text of the label depending on which radio
// button was pressed.
//--------------------------------------------------------------
public void actionPerformed (ActionEvent event)
{
Object source = event.getSource();
if (source == comedy)
quote.setText (comedyQuote);
else
if (source == philosophy)
quote.setText (philosophyQuote);
else
quote.setText (carpentryQuote);
}
}
}
The above code simply creates a panel with three radio buttons, each corresponding to a quote. It also creates a label which displays a quote. Whenever a button is selected, the text in the label is set to the corresponding quote. I understand this code just fine. I run into trouble trying to modify it. Let's say I want to create the same program, but with the radio buttons stacked vertically on top of one another. Let's also say that I decide to go about this by adding the radio buttons to a panel with a BoxLayout, which I define in its own BoxPanel class. (I would then add the BoxPanel to my QuoteOptionsPanel, which would still contain my quote JLabel.)
So my BoxPanel code might look something like this:
import java.awt.*;
import javax.swing.*;
public class BoxPanel extends JPanel
{
private JRadioButton comedy, philosophy, carpentry;
public BoxPanel()
{
setLayout (new BoxLayout (this, BoxLayout.Y_AXIS));
setBackground (Color.green);
comedy = new JRadioButton ("Comedy", true);
comedy.setBackground (Color.green);
philosophy = new JRadioButton ("Philosophy");
philosophy.setBackground (Color.green);
carpentry = new JRadioButton ("Carpentry");
carpentry.setBackground (Color.green);
ButtonGroup group = new ButtonGroup();
group.add (comedy);
group.add (philosophy);
group.add (carpentry);
QuoteListener listener = new QuoteListener();
comedy.addActionListener (listener);
philosophy.addActionListener (listener);
carpentry.addActionListener (listener);
}
//*****************************************************************
// Represents the listener for all radio buttons.
//*****************************************************************
private class QuoteListener implements ActionListener
{
//--------------------------------------------------------------
// Sets the text of the label depending on which radio
// button was pressed.
//--------------------------------------------------------------
public void actionPerformed (ActionEvent event)
{
Object source = event.getSource();
I do not know what to do here.
}
}
}
So as you can see, I did not know how to define my QuoteListener class. I want it to perform the same function as in the original program I posted, but am unsure of how to make it do so. The label which displays the quote is located in QuoteOptionsPanel, so I do not have access to it. In essence I am asking for the optimal way to change a label on one panel with an event listener belonging to a component on a different panel. I would be immensely grateful for any help you may be able to provide. Please let me know if I have not expressed my question clearly enough.
There are several ways to solve this, but for most all the key is to get and use references. Say the class that holds the JLabel as a private field has a public method,
public void setQuoteLabelText(String text) {
quoteLabel.setText(text);
}
Then you have to pass the reference to the visualized object of this class to your BoxPanel class, either through a constructor parameter or a setXXX(...) setter method. Then your ActionListener can call methods on the object of this class.
1. You can create an instance of the class whose private instance variable you need to
access.
2. Follow the one of the many use of Encapsulation, that is to have private Instance variable
and public getter-setter for that instance variable.
3. Now you can access the private member, by calling the public method on the instance of
the class.
4. One more thing, try using the Group Layout created by NetBeans team in 2005. Use the Window Builder Pro, now free from google.

Java KeyEvents for a KeyPad component

I'm writing a Java application that will have an on-screen number pad available for touch-input. Normal key input will also be available, but I'd like the keypad there for tablets and such. I've made a class that extends JPanel. It has 10 buttons laid out in the normal keypad configuration. Now I'm trying to figure out how to make it act like a regular keypad.
I just don't know how to issue KeyEvents. Here's what I've tried so far:
I tried adding a new KeyListener. In the JPanel, when a button was pressed, the action listener called a method that created a new KeyEvent and sent it to all the KeyListeners that were added to the JPanel. However, no matter how many times I added KeyListeners, the didn't seem to be any associated with the panel.
Another thing I tried was passing the target JTextField to the JPanel and setting a member object to the JTextField. But every time I try to append text to it, the member object is null. It's really perplexing to me.
I'm hoping someone could point me in the correct direction with how to implement this keypad to make it as modular is possible so it can be used inside several different screens.
Thanks in advance!
Brent
You dont need the KeyListener you can associate yourself the outcome effect of pressing a button (its not a key) on the JTextField.
Maybe something like:
New JButton button = new JButton(new KeyPressedAction(mTextField,"0"));
Where
public class KeyPressedAction extends Action{
JTextField tf;
String num;
public KeyPressedAction(JTextField textField,String num){
this.tf = textField;
this.num = num;
}
public void actionPerformed(ActionEvent e){
textField.setText(textField.getText+num);
}
}
I'm writing a Java application that
will have an on-screen number pad
available for touch-input.
So I assume that when the button is "touched" an ActionEvent will be generated. Then I assume you will want to add the character related to the button to a text field. If so, then the following examples should get you started. You don't need to generated KeyEvents, you just respond to the ActionEvents:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ButtonCalculator extends JFrame implements ActionListener
{
private JButton[] buttons;
private JTextField display;
public ButtonCalculator()
{
display = new JTextField();
display.setEditable( false );
display.setHorizontalAlignment(JTextField.RIGHT);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout( new GridLayout(0, 5) );
buttons = new JButton[10];
for (int i = 0; i < buttons.length; i++)
{
String text = String.valueOf(i);
JButton button = new JButton( text );
button.addActionListener( this );
button.setMnemonic( text.charAt(0) );
buttons[i] = button;
buttonPanel.add( button );
}
getContentPane().add(display, BorderLayout.NORTH);
getContentPane().add(buttonPanel, BorderLayout.SOUTH);
setResizable( false );
}
public void actionPerformed(ActionEvent e)
{
JButton source = (JButton)e.getSource();
display.replaceSelection( source.getActionCommand() );
}
public static void main(String[] args)
{
ButtonCalculator frame = new ButtonCalculator();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
}
If that doesn't solve your problem, then you should be looking into Key Bindings instead of using KeyEvents.

Unselecting RadioButtons in Java Swing

When displaying a group of JRadioButtons, initially none of them is selected (unless you programmatically enforce that). I would like to be able to put buttons back into that state even after the user already selected one, i.e., none of the buttons should be selected.
However, using the usual suspects doesn't deliver the required effect: calling 'setSelected(false)' on each button doesn't work. Interestingly, it does work when the buttons are not put into a ButtonGroup - unfortunately, the latter is required for JRadioButtons to be mutually exclusive.
Also, using the setSelected(ButtonModel, boolean) - method of javax.swing.ButtonGroup doesn't do what I want.
I've put together a small program to demonstrate the effect: two radio buttons and a JButton. Clicking the JButton should unselect the radio buttons so that the window looks exactly as it does when it first pops up.
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.*;
import javax.swing.*;
/**
* This class creates two radio buttons and a JButton. Initially, none
* of the radio buttons is selected. Clicking on the JButton should
* always return the radio buttons into that initial state, i.e.,
* should disable both radio buttons.
*/
public class RadioTest implements ActionListener {
/* create two radio buttons and a group */
private JRadioButton button1 = new JRadioButton("button1");
private JRadioButton button2 = new JRadioButton("button2");
private ButtonGroup group = new ButtonGroup();
/* clicking this button should unselect both button1 and button2 */
private JButton unselectRadio = new JButton("Unselect radio buttons.");
/* In the constructor, set up the group and event listening */
public RadioTest() {
/* put the radio buttons in a group so they become mutually
* exclusive -- without this, unselecting actually works! */
group.add(button1);
group.add(button2);
/* listen to clicks on 'unselectRadio' button */
unselectRadio.addActionListener(this);
}
/* called when 'unselectRadio' is clicked */
public void actionPerformed(ActionEvent e) {
/* variant1: disable both buttons directly.
* ...doesn't work */
button1.setSelected(false);
button2.setSelected(false);
/* variant2: disable the selection via the button group.
* ...doesn't work either */
group.setSelected(group.getSelection(), false);
}
/* Test: create a JFrame which displays the two radio buttons and
* the unselect-button */
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
RadioTest test = new RadioTest();
Container contentPane = frame.getContentPane();
contentPane.setLayout(new GridLayout(3,1));
contentPane.add(test.button1);
contentPane.add(test.button2);
contentPane.add(test.unselectRadio);
frame.setSize(400, 400);
frame.setVisible(true);
}
}
Any ideas anyone? Thanks!
You can do buttonGroup.clearSelection().
But this method is available only since Java 6.
The Javadoc of the class ButtonGroup itself gives some hint about how this can be achieved:
From the API doc of class ButtonGroup:
Initially, all buttons in the group are unselected. Once any button is selected, one button is always selected in the group.There is no way to turn a button programmatically to "off", in order to clear the button group. To give the appearance of "none selected", add an invisible radio button to the group and then programmatically select that button to turn off all the displayed radio buttons.
Try adding a third invisible button to the button group. When you want to "deselect", select the invisible one.
Or you can use Darryl's Select Button Group which doesn't require you to use an "invisible button".
You can use a click counter:
private ButtonGroup radioGroup = new javax.swing.ButtonGroup();
private JRadioButton jRadioBtn1 = new javax.swing.JRadioButton();
private int clickCount = 0;
private void jRadioBtn1Clicked(java.awt.event.MouseEvent evt) {
// Remove selection on a second click
if (jRadioBtn1.isSelected()) {
if (++clickCount % 2 == 0) {
radioGroup.clearSelection();
}
}
}
You can use setselected(false) method to unselect the previous selected button.
I don't know if this will help but have you tried to use doClick() method?
jRadioButtonYourObject.doClick();
Input - NONE
Return- void
I had a similar problem and tried everything in this thread to no avail. So I took a look at all the methods of JRadioButton and found that method from JRadioButton's parent class.
In my program, I had two radio button independent of each other and it was programed so that only one was selected.
After the user enters data and hits a button the program clears all text fields and areas and deselects the radio button. The doClick() did the job of deselecting the radio button for me; the method "performs a "click"."
I know yours is different and you probably would have to program the doClick() method for every radio button that is selected.
http://docs.oracle.com/javase/7/docs/api/javax/swing/AbstractButton.html
search for doClick()
When you want to deselect, select invisible. For that you add a third invisible button to the button group.
In my case I use Jgoodies project to bind GUI components to Java model.
The RadioButton component is bound to a field
class Model {
private SomeJavaEnum field; // + getter, setter
}
In such case ButtonGroup.clearSelection doesn't work since the old value still retains in the model. Straightforward solution was to simply setField(null).
Use this helper class SelectButtonGroup.java
direct link to the class source
import java.awt.*;
import java.awt.event.ActionListener;
import javax.swing.*;
public class SelectUnselected extends JPanel {
private static String birdString = "Bird";
private static String catString = "Cat";
private static Integer selectedIndex = -1;
private static AbstractButton hiddenButton = new JRadioButton(catString);
private final static AbstractButton birdButton = new JRadioButton(birdString);
private final static AbstractButton catButton = new JRadioButton(catString);
//Group the radio buttons.
private SelectButtonGroup group = new SelectButtonGroup();
public SelectUnselected() {
super(new BorderLayout());
//Create the radio buttons.
hiddenButton.setVisible(false);
hiddenButton.setSelected(true);
group.add(birdButton);
group.add(catButton);
group.add(hiddenButton);
ActionListener sendListener = e -> {
checkSelectedRadioButten();
};
birdButton.addActionListener(sendListener);
catButton.addActionListener(sendListener);
hiddenButton.addActionListener(sendListener);
//Put the radio buttons in a column in a panel.
JPanel radioPanel = new JPanel(new GridLayout(0, 1));
radioPanel.add(birdButton);
radioPanel.add(catButton);
add(radioPanel, BorderLayout.LINE_START);
setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
}
public void checkSelectedRadioButten(){
System.out.println("selectedIndex = " + selectedIndex + "\ngroup.getSelectedButton() = " + group.getSelectedIndex());
if(group.getSelectedIndex() == selectedIndex){
hiddenButton.setSelected(true);
selectedIndex = -1;
System.out.println("getText = " + group.getSelectedButton().getText());
}else{
selectedIndex = group.getSelectedIndex();
System.out.println("getText = " + group.getSelectedButton().getText());
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("RadioButtonDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent newContentPane = new SelectUnselected();
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
}
You can use your own ButtonGroup (1), or use modified instance (2), like this:
ONLY SINCE JAVA 6:
(1) public class NoneSelectedButtonGroup extends ButtonGroup {
#Override
public void setSelected(ButtonModel model, boolean selected) {
if (selected) {
super.setSelected(model, selected);
} else {
clearSelection();
}
}
}
(2) ButtonGroup chGroup = new ButtonGroup() {
#Override
public void setSelected(ButtonModel m, boolean b) {
if (!b) clearSelection();
else
super.setSelected(m, b);
}
};
take from https://blog.frankel.ch/unselect-all-toggle-buttons-of-a-group/

Categories

Resources