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
Related
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 ...
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();
}
});
}
}
}
package swingtraining;
import static java.awt.Color.BLACK;
import static java.awt.Color.RED;
import java.awt.EventQueue;
import static java.awt.Font.BOLD;
import java.awt.Point;
import java.awt.Rectangle;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
public class JFrameWithAButton extends JFrame {
public JFrameWithAButton(){
setSize(400,400);
setTitle("Swing is hard");
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String args[]){
JPanel Jp1 = new JPanel();
Jp1.setOpaque(true);
Jp1.setBackground(RED);
JButton Jbt = new JButton();
Jbt.setLayout(null);
Jbt.setSize(200,200);
Jbt.setBounds(new Rectangle(new Point(200, 200)));
Jbt.setText("Hello!");
EventQueue.invokeLater(new Runnable(){
public void run(){
JFrameWithAButton ex = new JFrameWithAButton();
ex.setVisible(true);
ex.add(Jp1);
Jp1.add(Jbt);
}
});
}
}
Sorry if the code's a bit mom's spaghetti-esque, but I just can't crack this cookie >.> Even with layout set to null it doesn't move. Any suggestions of how I get this JButton to not only move to the middle of the window but also grow 200 by 200 pixels?
Any suggestions of how I get this JButton to not only move to the middle of the window but also grow 200 by 200 pixels?
I can think of a few, none of which use null layouts
GridBagConstraints
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 javax.swing.JButton;
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.ipadx = 200;
gbc.ipady = 200;
add(new JButton("Hello"), gbc);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
}
}
JButton#setMargin
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.Insets;
import javax.swing.JButton;
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();
JButton btn = new JButton("Hello");
btn.setMargin(new Insets(100, 100, 100, 100));
add(btn);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
}
}
EmptyBorder
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
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 BorderLayout());
setBorder(new EmptyBorder(50, 50, 50, 50));
JButton btn = new JButton("Hello");
add(btn);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
}
}
You could use combination of them, maybe using an EmptyBorder and GridBagConstraints to further constrain the layout.
The great benefit of these examples, is, for the most part, if the font size changes or the rendering requirements for the fonts change, the layout is capable of compensating
Avoid using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify
And because it's always a fun read, Why is it frowned upon to use a null layout in SWING?
if you wanna define any component size manually you have to set the mother component's layout: null
so you have to set Jframe layout null to define Jpanel size and location
then you have to set JPanel layout null to define Jbutton size and location in it
final JPanel Jp1 = new JPanel();
Jp1.setOpaque(true);
Jp1.setBackground(RED);
Jp1.setLayout(null);
final JButton Jbt = new JButton();
// Jbt.setLayout(null); not needed!
Jbt.setBounds(10, 10, 100, 40);
// Jbt.setBounds(new Rectangle(new Point(200, 200))); not in this style
Jbt.setText("Hello!");
Jp1.add(Jbt);
EventQueue.invokeLater(new Runnable() {
public void run() {
JFrameWithAButton ex = new JFrameWithAButton();
ex.setVisible(true);
ex.add(Jp1);
}
});
don't forget to define size and location both when you are adding a component in a null layout Jpanel or Jframe and ...
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());
}
});
}
}
}
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"}));
}
});
}
}
}