Reset radio buttons in Java - java

I have three radio buttons in one button group. I want, on JButton click, for the radio buttons to be reset so they're unfilled. I've tried the logical suggestions that come up with you type .set and all of the booleans didn't do what I wanted it to do. So if you have suggestions that would be greatly appreciated. Thanks!

Simply use ButtonGroup#clearSelection
For example...
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Action;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JRadioButton[] buttons;
private ButtonGroup buttonGroup;
public TestPane() {
buttons = new JRadioButton[] {
new JRadioButton("Nuclear"),
new JRadioButton("Gas"),
new JRadioButton("Stream"),
new JRadioButton("Peddle"),
new JRadioButton("Electric")
};
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1;
gbc.anchor = GridBagConstraints.WEST;
gbc.gridwidth = GridBagConstraints.REMAINDER;
buttonGroup = new ButtonGroup();
for (JRadioButton btn : buttons) {
add(btn, gbc);
buttonGroup.add(btn);
}
JButton clear = new JButton("Clear");
add(clear, gbc);
clear.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
buttonGroup.clearSelection();
}
});
}
}
}

Related

How do I set the size of my program's window? It seems to automatically be small. I'm using a lot of different 'containers' I guess

With all the different 'containers' I'm using, it's hard to set my window size in the code. I guess I need them but at the same time need to find a way to change settings around it.
I've tried doing frame.setSize(int x, int y), did not work.
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TweetProgram1{
public static void main(String[] args) {
new TweetProgram1();
}
public TweetProgram1() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Tweet Program");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TweetProgram1Pane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TweetProgram1Pane extends JPanel {
public TweetProgram1Pane() {
setLayout(new GridBagLayout());
JLabel lbl = new JLabel("Random tweet");
JButton btn = new JButton("Send it");
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = 300;
gbc.gridheight = 300;
add(lbl, gbc);
add(btn, gbc);
}
}
}
I expect to be able to re-scale the window size (in the code) to whatever I need it to be.
Thanks

How to set caret position at the end of JFormattedTextField when it is clicked/focused?

I have frame with JFormattedTextField(s). My simplified code can look like:
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(100,100);
frame.setLayout(new GridLayout(2,2));
JFormattedTextField field1 = new JFormattedTextField(NumberFormat.getInstance());
field1.setValue(0.4);
frame.add(new JLabel("value A"));
frame.add(field1);
JFormattedTextField field2 = new JFormattedTextField(NumberFormat.getInstance());
field2.setValue(0.8);
frame.add(new JLabel("value B"));
frame.add(field2);
frame.setVisible(true);
which generates:
Goal
When I click/focus on any of JFormattedTextField I would like it to automatically place caret at the end
Problem
I tried using following solutions before calling frame.setVisible(true); but none of them seems to work
from How to set AUTO-SCROLLING of JTextArea in Java GUI?
field1.setCaretPosition(field1.getDocument().getLength());
from https://tips4java.wordpress.com/2008/10/22/text-area-scrolling/ ((DefaultCaret)field2.getCaret()).setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
Works without issue for me....
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
JTextField textField = new JTextField("This is a test");
add(textField, gbc);
JButton button = new JButton("This is a button");
add(button, gbc);
button.setFocusable(false);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (textField.getCaretPosition() != 0) {
textField.setCaretPosition(0);
} else {
textField.setCaretPosition(textField.getText().length());
}
textField.requestFocusInWindow();
}
});
}
}
}
Provide a runnable example which doesn't work if you still have issues
Update with JFormattedTextField....
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
JFormattedTextField textField = new JFormattedTextField("This is a test");
textField.setValue(0.8d);
add(textField, gbc);
JButton button = new JButton("This is a button");
add(button, gbc);
button.setFocusable(false);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (textField.getCaretPosition() != 0) {
textField.setCaretPosition(0);
} else {
textField.setCaretPosition(textField.getText().length());
}
textField.requestFocusInWindow();
}
});
}
}
}
Updated with "set at beginning"
Okay, I just want to point out that I have personally dislike of JFormattedTextField, it does a lot of "things" at times which don't always make sense.
An "old" trick I've used, when implementing a "auto select all on focus gain", is to offload the request to the end of the Event Dispatching Thread, this places the request AFTER all the "funky stuff" that the JFormattedTextField does when the field becomes focused...
JFormattedTextField textField = new JFormattedTextField("This is a test");
textField.setValue(0.8d);
add(textField, gbc);
textField.addFocusListener(new FocusAdapter() {
#Override
public void focusGained(FocusEvent arg0) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
textField.setCaretPosition(textField.getText().length());
}
});
}
});
Yes, I'm serious ...

How to change the (displayed) selected item on a disabled JComboBox?

I'd like to change the displayed selected item on a disabled JComboBox programmatically. I tried
enabling it before invoking setSelectedItem and disabling it right after
the former and invoking updateUI before disabling
It might be that this isn't intended, but would save me the work to replace the combobox with a JLabel, so a dirty hack answer would be appreciated as well.
Well, it seems to work okay for me...
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
JComboBox cb = new JComboBox(new String[]{
"One", "Two", "Three", "Four", "Five"
});
cb.setEnabled(false);
add(cb, gbc);
cb.setEnabled(false);
JButton btn = new JButton("Update");
add(btn, gbc);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cb.setSelectedItem("Five");
}
});
}
}
}
Make sure the object you using is equal to the value in the JComboBox

Is there a listener that listens to the enable/disable event in Swing?

Is there a listener I can add to a Swing combobox that will trigger when the combobox is enabled or disabled?
I have tried different listeners like componentlistener, itemlistener, propertychangelistener but in vain. I'm using JDK 1.6.
PropertyChangeListener seems to work just fine for me...
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class EnabledTest {
public static void main(String[] args) {
new EnabledTest();
}
public EnabledTest() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
final JComboBox cb = new JComboBox(new Object[]{"One", "Two", "Three"});
add(cb, gbc);
cb.addPropertyChangeListener("enabled", new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
System.out.println("State changed for " + evt.getPropertyName() + " to " + evt.getNewValue());
}
});
JButton btn = new JButton("Switch");
add(btn, gbc);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cb.setEnabled(!cb.isEnabled());
}
});
}
}
}

How to update JComboBox instances in Swing?

I've 3 comboboxes, upon selecting first combobox, the rest should be updated but my code doesn't seems to be working. Please help in this guys. Here is my code(since my code very long so I'll write error part only).
// example code
public class GuiComponents {
JComboBox<String> comboBox1, comboBox2, comboBox3;
public GuiComponents() {
.........
.........
String[] element1 = {"item1", "item2", "item3"};
String[] element2 = {"item1", "item2", item3};
String[] element3 = {"item1", "item2", "item3"};
comboBox1.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent event) {
if(event.getStateChange() == ItemEvent.SELECTED) {
// how do I update 2 comboboxes, upon selecting combobox1.
// combox2 should update as(element2) and
// combox3 should update as element3.
}
}
});
}
}
Thanks in advance....
If you intention is to change the combo box values when the user makes a selection, then you are better off using a ActionListener.
If you want to the combo boxes to update each time the user selects a different item in the drop down list (and, yes, this is a different event), then you should use an ItemListener
But in either case, the process is the same...
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class ComboBoxUpdates {
public static void main(String[] args) {
new ComboBoxUpdates();
}
public ComboBoxUpdates() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JComboBox<String> cb1, cb2, cb3;
public TestPane() {
cb1 = new JComboBox<>(new String[]{"Click me", "Click me", "Click them"});
cb2 = new JComboBox<>();
cb3 = new JComboBox<>();
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(cb1, gbc);
add(cb2, gbc);
add(cb3, gbc);
cb1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cb2.setModel(new DefaultComboBoxModel<String>(new String[]{"item1", "item2", "item3"}));
cb3.setModel(new DefaultComboBoxModel<String>(new String[]{"item4", "item5", "item6"}));
}
});
}
}
}

Categories

Resources