How to update JComboBox instances in Swing? - java

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"}));
}
});
}
}
}

Related

Jlabel change color on mouse click Java

I am adding multiple Jlabel using for loop. What I want is on mouse click, the color of the selected JLabel should change and set to the default color on click of anotherJLabel.
Since you changed the state of the label, you need someway to change it back. The simplest solution is to maintain a reference to the last label that was changed and when the new label is clicked, reset it's state
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
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;
HighlightMouseListener hml = new HighlightMouseListener();
for (int index = 0; index < 10; index++) {
JLabel label = new JLabel("Hello " + index);
label.addMouseListener(hml);
add(label, gbc);
}
}
}
public class HighlightMouseListener extends MouseAdapter {
private JLabel previous;
#Override
public void mouseClicked(MouseEvent e) {
Component source = e.getComponent();
if (!(source instanceof JLabel)) {
return;
}
JLabel label = (JLabel) source;
if (previous != null) {
previous.setBackground(null);
previous.setForeground(null);
previous.setOpaque(false);
}
previous = label;
label.setForeground(Color.WHITE);
label.setBackground(Color.BLUE);
label.setOpaque(true);
}
}
}
I still wonder if a JList would be a better and simpler solution, but since I don't know what you're doing, it's all I can do

Reset radio buttons in 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();
}
});
}
}
}

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());
}
});
}
}
}

Is it possible to use a JSlider controlling multiple JTextfield?

I tried to use a JSlider to set text in three JTextFields.
My condition is the slider should work for textfield_1, only when a textfield_1 get its focus, similarly for the other two textfields.
When I tried to use the same slider with other textfield, only the first text field values getting changed.
Expecting valuable suggestions Thanks in Advance.
JSlider slider;
JTextField tf;
tf.addFocusListener(new FoucusListener(){
public void foucusGained(FocusEvent fe){
slider.addChangeListener(new ChangeListener()){
public void stateChanged(ChangeEvent ce){
JSlider slider =(JSlider)ce.getSource();
if(slider.getValueisAdjusting())
tf.setText(String.valueOf(slider.getValue()))
}
});
});
The basic idea is you need to know what field was last selected. The problem is, when you select the slider, it will fire a focus gained event...
The simplest idea would be to use a FocusListener registered only to the text fields and maintain a reference to the last field selected.
When the slider changes, you would simply interact with the last selected field (if it's not null)
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class SliderControl {
public static void main(String[] args) {
new SliderControl();
}
public SliderControl() {
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 JSlider slider;
private JTextField[] fields;
private JTextField selectedField;
public TestPane() {
setLayout(new GridBagLayout());
fields = new JTextField[3];
FocusHandler focusHandler = new FocusHandler();
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
for (int index = 0; index < 3; index++) {
fields[index] = new JTextField(3);
fields[index].addFocusListener(focusHandler);
add(fields[index], gbc);
gbc.gridy++;
}
gbc.fill = GridBagConstraints.HORIZONTAL;
slider = new JSlider();
slider.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
if (selectedField != null) {
selectedField.setText(String.valueOf(slider.getValue()));
}
}
});
add(slider, gbc);
}
protected class FocusHandler extends FocusAdapter {
#Override
public void focusGained(FocusEvent e) {
if (e.getComponent() instanceof JTextField) {
selectedField = (JTextField) e.getComponent();
}
}
}
}
}

Categories

Resources