How to enable a disabled JRadioButton - java

I have two JRadioButton with ImageIcon for each one. Because of the ImageIcons I'm using, I need to give the appearance that one button is selected and the other one is not selected. To do this I'm trying to disable the other button, which automatically changes the ImageIcon to disabled appearance.
Problem is that when I click on the disabled JRadioButton, nothing happens, not even the ActionListener on the JRadioButton is getting called.
Is there a way to enable a disabled JRadioButton by clicking directly on it? Once it's disabled, it's ActionListener no longer gets called, so I can't enable it by clicking on it.
Basically I'm trying to give the appearance that when one is selected, the other is not selected, using ImageIcons.
//Below part of my code how I initialize the buttons
ButtonGroup codeSearchGroup = new ButtonGroup();
searchAllDocs = new JRadioButton(new ImageIcon(img1));
searchCurrDoc = new JRadioButton(new ImageIcon(img2));
RadioListener myListener = new RadioListener();
searchAllDocs.addActionListener(myListener);
searchCurrDoc.addActionListener(myListener);
codeSearchGroup.add(searchAllDocs);
codeSearchGroup.add(searchCurrDoc);
//Below listener class for buttons
class RadioListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(e.getSource() == searchAllDocs){
searchAllDocs.setEnabled(true);
System.out.println("Search All documents pressed. Disabling current button...");
searchCurrDoc.setEnabled(false);
}
else{
searchCurrDoc.setEnabled(true);
System.out.println("Search Current document pressed. Disabling all button...");
searchAllDocs.setEnabled(false);
}
}
}
Thanks in advance.

The ActionListener wont fire in disabled mode, but mouse events will.
Thus simply add a MouseAdapter to JRadioButton and override mouseClicked(..) and call setEnable(true) within overridden method like so:
JRadioButton jrb = new JRadioButton("hello");
jrb.setEnabled(false);
jrb.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent me) {
super.mouseClicked(me);
JRadioButton jrb = (JRadioButton) me.getSource();
if (!jrb.isEnabled()) {//the JRadioButton is disabled so we should enable it
//System.out.println("here");
jrb.setEnabled(true);
}
}
});
though I must say there is a bit of skewed logic at play. If something is disabled its done so for a reason, thus we shouldnt allow users to be able to enable. and if we do there should be a control system where we can choose to have the button enabled/disable it wouldnt become the control system itself.

Related

Returning result from the first clicked Jbutton from multiple JButtons java swing

Basically I have n JButtons. If any of them is clicked, they return a certain number.
I have a menu with each of the buttons and when the user clicks one, my menu method returns the number returned by the Button handler. Is it possible?
Something like:
frame.add(button1..)
frame.add(button2..)
frame.add(button3..)
if (button1.isClicked()) {
return button1ActionHandler();
} else if (button2.isClicked()) {
return button2ActionHandler();
} else if (button3.isClicked()) {
return button3ActionHandler();
}
The problem is, the code is not waiting for me to click a button so it won't enter in any of those if's. What can I do for the program to wait for click and how can I check if a button is clicked?
Start by having a look at How to Use Buttons, Check Boxes, and Radio Buttons and How to Write an Action Listeners.
Remember, a GUI is an event driven environment, that is, something and then you respond to it.
You need to register an ActionListener against each button, when the button is triggered, you need to take appropriate action.
There are a number of ways you could achieve this, you could set the actionCommand of the buttons with appropriate information that you can use to ascertain what should be done when the button is clicked. You could use the source property of the ActionEvent to determine the source of the event and take appropriate action, as exampels
It sounds like you want to present the user with several options, let him choose one of the options, and then have him press a "submit" button to submit that option to the program. If so, then I think that your best bet is to use JRadioButtons, all added to a ButtonGroup -- this allows only one of the radio buttons to be selected at any time, or use a JComboBox. Either way, it would be easy to extract the information regarding which selection the user made. If you use the first option, use of JRadioButtons, ButtonGroup and a "submit" button, you simply get the selected ButtonModel from the ButtonGroup by calling its getSelection() method, and then extract the actionCommand String from this model by calling getActionCommand(). If you decide on the second option, use of a JComboBox together with a "submit" button, then simply call getSelectedItem() on the JComboBox within your submit button's ActionListener.
Below I show you both options. Note that my submit button doesn't use an ActionListener but rather an AbstractAction, which is kind of like an ActionListener on steroids.
import java.awt.event.ActionEvent;
import javax.swing.*;
public class SelectionEg extends JPanel {
private static final String[] SELECTIONS = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
private ButtonGroup buttonGroup = new ButtonGroup();
private JComboBox<String> selectionComboBox = new JComboBox<>(SELECTIONS);
public SelectionEg() {
for (String selection : SELECTIONS) {
JRadioButton radioButton = new JRadioButton(selection);
radioButton.setActionCommand(selection);
add(radioButton);
buttonGroup.add(radioButton);
}
add(selectionComboBox);
add(new JButton(new SubmitAction("Submit")));
}
private class SubmitAction extends AbstractAction {
public SubmitAction(String name) {
super(name);
putValue(MNEMONIC_KEY, (int) name.charAt(0));
}
#Override
public void actionPerformed(ActionEvent e) {
ButtonModel model = buttonGroup.getSelection();
if (model == null) {
// nothing selected yet, ignore this
return;
}
String message = "The selected radio button is: " + model.getActionCommand();
System.out.println(message);
message = "The selection from the combo box is: " + selectionComboBox.getSelectedItem();
System.out.println(message);
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("Selelection Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new SelectionEg());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

Java: Creating multiple (duplicate) buttons that perform the same action but to themselves

BACKGROUND INFO: I want to make a 9x9 grid of buttons that act as empty beds. All buttons say "Add bed" and when clicked open up a window to write data about the occupant. Once saved the button will change to an occupied bed image.
QUESTION: Is it possible to create an event listener that does the same thing for each button, but applies it to the button being pressed? Im new to java but I understand that good code should be able to do this in a few lines rather than 100+
CODE:
//button1 (inside the gui function)
addBed1 = new JButton("Add bed"); //button 1 of 9
addBed1.addActionListener(new room1Listener());
class room1Listener implements ActionListener{
public void actionPerformed(ActionEvent event){
addBed1.setText("Adding bed..);
addBedGui(); //Generic window for adding bed info.
}
}
Is it possible to create an event listener that does the same thing for each button, but applies it to the button being pressed? Im new to java but I understand that good code should be able to do this in a few lines rather than 100+
Absolutely. In fact you can create one ActionListener object and add this same listener to each and every button in a for loop. The ActionListener will be able to get a reference to the button that pressed it via the ActionEvent#getSource() method, or you can get the JButton's actionCommand String (usually its text) via the ActionEvent#getActionCommand() method.
e.g.,
// RoomListener, not roomListener
class RoomListener implements ActionListener{
public void actionPerformed(ActionEvent event){
AbstractButton btn = (AbstractButton) event.getSource();
btn.setText("Adding bed..);
addBedGui(); //Generic window for adding bed info.
}
}
and
RoomListener roomListener = new RoomListener();
JButton[] addButtons = new JButton[ADD_BUTTON_COUNT];
for (int i = 0; i < addButtons.length; i++) {
addButtons[i] = new JButton(" Add Bed "); // make text big
addButtons[i].addActionListener(roomListener);
addBedPanel.add(addButtons[i]);
}

How to make Java Swing Radio Buttons unselectable but not greyed out?

I am developing a Java Swing App, and I want to use JRadioButton objects to show state. I don't want the user to have the ability to select them. If I use the button's .setEnabled(false) method, the radio button is greyed out.
I don't want the Radio Button to grey out. Is there a way to override this?
Well You Could Do Something Like:
boolean rButtonEnabled = false;
JRadioButton rButton = new JRadioButton();
rButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
rdbtnNewRadioButton.setSelected(rButtonEnabled);
}
});
It's not the prettyist solution, but I hope it helps.
To store the new value perhaps you can create a new class extending JRadioButton.
While this does not use the .setEnabled(), it is effectively the same

Fast double key pressed on Jbutton leads results in same operation twice

1> I have a JButton in Jframe.
2> The click of JButton opens new instance of another JFrame.
The problem is when a Key is pressed very fast on the above Jbutton .Two instances of the same JFrame opens up.
I have to open these frames. I knows there are other options also not using the Jframes as I read.
I managed to solve this problem for Doulbl click of Mouce by setMultiClickThreshHold('time in miliseconds'). But it worked only for mouse.
Tried some other stuffs which I got in google, But none worked.
Is there any other way to solve this issue?
For full control of how often/quickly again an Action is triggered, implement it to disable itself in its actionPerformed. Something like:
singlePerform = new AbstractAction("DoSomthing") {
#Override
public void actionPerformed(ActionEvent e) {
setEnabled(false);
doSomething();
}
};
JButton button = new JButton(singlePerform);
When it's safe for doSomething to be triggered again, simply re-enable the Action:
singlePerform.setEnabled(true);

How to get the source of all JButton components from an ActionEvent?

I'm trying to implement a simple window that contain two buttons Yes and No.
When clicking on Yes I want to disable the No button and when pressing on No I want to disable the Yes button.
I've implemented:
JButton btnYes = new JButton("Yes");
contentPane.add(btnYes);
btnYes.setActionCommand("Yes");
btnYes.addActionListener(this);
...the same for the No button...
Now I'm catching the event in this method:
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("Yes"))
{
//I know how to get the button that caused the event
//but I don't know how to disable the OTHER button.
JButton source = (JButton)e.getSource();
//Handle the source button...
}
}
In the above method I have an access to the button that caused the event, but not to the other button.
What is the best way of getting the buttons?
You should just implement ActionListener as a nested class of your Dialog's class, in this case you will have full access to all fields of outer class (in which you should store reference to buttons when your create them).
The bad dirty solution (that should NOT be used) still exists: to navigate to battens through getParent() of JButton and then through getChildren() of parents childrens. Just to show that it is possible anyway.
You could use a JButton array as class member variable and to check which instance didnt cause the event:
for (JButton button: buttonArray) {
if (button != source) {
button.setEnabled(false); // disable the other button
}
}

Categories