The use case in my UI is to populate two JTextField components based on double clicking items in a JList. The easy was is to use a JCheckBox populate jTextField1 if the checkbox is selected, and populate the other if it is not selected or vice versa which is working perfectly.
But I would like to explore if this can be done without the checkbox.
As in, if I type something in jtextfield1 and double click the item in list to complete the text, the item clicked should be appended to jtextfield1 based on fetching the latest KeyStroke I used.
Is there are any way to do this?
The use case in my UI is to populate two jTextField's based on double clicking items in a jlist.
Well, normally a UI should be designed so that you can use the mouse or the keyboard to invoke an Action. That is you should be able to double click or use the Enter key on the selected item.
Check out List Action for a simple class that allows you to implement this functionality by using an Action.
Now when you create your Action you can extend TextAction. Then you can use the getFocustComponent() method from the TextAction to determine the text component that last had focus and add the text from the selected item to that text field.
The basic code for the custom Action would be:
JList list = (JList)e.getSource();
JTextComponent textField = getFocusedComponent();
textField.setText( list.getSelectedValue().toString() );
Note: you will need to verify if focus is on one of the two fields if your window contains more than two text components.
To use the FocusListener approach you would need to define an instance variable in your class:
private JTextField lastFocusedTextField = null;
Then in the constructor of your class where you create the text fields you would create the listener:
FocusListener fl = new FocusAdapter()
{
#Override
public void focusGained(FocusEvent e)
{
lastFocusedTextField = (JTextField)e.getSource();
}
};
JTextField textField1 = new JTextField(...);
textField1.addFocusListener( fl );
// same for the other text field
Now you need to add a MouseListener to the JList. In the mouseClicked(...) method you do something like:
JList list = (JList)e.getSource();
lastFocusedTextField.setText( list.getSelectedValue().toString() );
So you need:
an instance variable
a FocusListener
a MouseListener
As everyone has suggested initialize a FocusListener to both the text fields and and point it to a string variable when either of the loses focus.
Code:
String LastFocusLost = null;
jTextField1.addFocusListener(new java.awt.event.FocusAdapter()
{
public void focusLost(java.awt.event.FocusEvent evt)
{
LastFocusLost = "jTextField1";
}
});
jTextField2.addFocusListener(new java.awt.event.FocusAdapter()
{
public void focusLost(java.awt.event.FocusEvent evt)
{
LastFocusLost = "jTextField2";
}
});
In the mouseListener add a if-else then:
if ("jTextField1".equals(LastFocusLost))
{
//;
}
else if ("jTextField2".equals(LastFocusLost))
{
//;
}
The use case in my UI is to populate two JTextField components based on double clicking items in a JList. The easy was is to use a JCheckBox populate jTextField1 if the checkbox is selected, and populate the other if it is not selected or vice versa which is working perfectly.
But I would like to explore if this can be done without the checkbox.
As in, if I type something in jtextfield1 and double click the item in list to complete the text, the item clicked should be appended to jtextfield1 based on fetching the latest KeyStroke I used.
Is there are any way to do this?
The use case in my UI is to populate two jTextField's based on double clicking items in a jlist.
Well, normally a UI should be designed so that you can use the mouse or the keyboard to invoke an Action. That is you should be able to double click or use the Enter key on the selected item.
Check out List Action for a simple class that allows you to implement this functionality by using an Action.
Now when you create your Action you can extend TextAction. Then you can use the getFocustComponent() method from the TextAction to determine the text component that last had focus and add the text from the selected item to that text field.
The basic code for the custom Action would be:
JList list = (JList)e.getSource();
JTextComponent textField = getFocusedComponent();
textField.setText( list.getSelectedValue().toString() );
Note: you will need to verify if focus is on one of the two fields if your window contains more than two text components.
To use the FocusListener approach you would need to define an instance variable in your class:
private JTextField lastFocusedTextField = null;
Then in the constructor of your class where you create the text fields you would create the listener:
FocusListener fl = new FocusAdapter()
{
#Override
public void focusGained(FocusEvent e)
{
lastFocusedTextField = (JTextField)e.getSource();
}
};
JTextField textField1 = new JTextField(...);
textField1.addFocusListener( fl );
// same for the other text field
Now you need to add a MouseListener to the JList. In the mouseClicked(...) method you do something like:
JList list = (JList)e.getSource();
lastFocusedTextField.setText( list.getSelectedValue().toString() );
So you need:
an instance variable
a FocusListener
a MouseListener
As everyone has suggested initialize a FocusListener to both the text fields and and point it to a string variable when either of the loses focus.
Code:
String LastFocusLost = null;
jTextField1.addFocusListener(new java.awt.event.FocusAdapter()
{
public void focusLost(java.awt.event.FocusEvent evt)
{
LastFocusLost = "jTextField1";
}
});
jTextField2.addFocusListener(new java.awt.event.FocusAdapter()
{
public void focusLost(java.awt.event.FocusEvent evt)
{
LastFocusLost = "jTextField2";
}
});
In the mouseListener add a if-else then:
if ("jTextField1".equals(LastFocusLost))
{
//;
}
else if ("jTextField2".equals(LastFocusLost))
{
//;
}
I am working with jsliders, I have made a jslider, and couple of text boxes, what I want to do is when lets say the user slides the slider to 3 it makes visible text boxes. I have a code which is working at the moment and also does not interpret making visible text boxes but enabling or disabling them.
do {
textField.setEnabled(true);
}
while (slider.setValue(3));
I want to hide text boxes and when the user slides the slider to 3 it enables text boxes. Thanks,
You need to add a change listener like
jSlider1.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
jSlider1StateChanged(evt);
}
});
and then change the visibility of the text field on that function:
private void jSlider1StateChanged(javax.swing.event.ChangeEvent evt) {
if(jSlider1.getValue()<50)
jLabel1.setVisible(false);
else
jLabel1.setVisible(true);
}
I'm trying to change content dynamically based on a JRadioButton selection... My simplified code looks something like this.
//import
public class Thing {
//
JPanel pnlMain, pnl1, pnl2, pnlRt, pnlLt;
JRadioBtn btn1, btn2;
//
Thing () {
//
//initialize panels, add to them, etc.
pnlMain.add(pnlLt);
pnlMain.add(pnl1);
pnlMain.add(pnlRt);
//
//Get it showing and stuff.
//
}
//
//One instance of this class connected to all radio buttons.
class Evt implements ActionListener {
public void actionImplemented (ActionEvent evt) {
//
pnlMain.remove(1);
//
if (evt.getActionCommand().equals("Radio 1"))
pnlMain.add(pnl1);
else pnlMain.add(pnl2);
//
pnlMain.validate();
//
}
}
//
public static void main (String[] args) {
new Thing();
}
//
}
This lets me change panels, but i cannot change back to a panel i had previously selected... I don't understand why. Please help!!!
You should be using CardLayout instead, as this is exactly what that is for. Check out the tutorial here.
Use a proper layout manager. In this scenario, I recommend using CardLayout. This enables the developer to delegate the "complexity" of panel exchanging to the layout manager, which is how it should be.
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/