The code below demonstrate how to set the selected item of JComboBox
and then on how to get the value of the selected item. In this example we set the JComboBox
component so that user can enter their own value.
package org.kodejava.swing;
import javax.swing.*;
import java.awt.*;
public class ComboBoxSelectedItem extends JFrame {
public ComboBoxSelectedItem() {
initialize();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(
() -> new ComboBoxSelectedItem().setVisible(true));
}
private void initialize() {
setSize(500, 500);
setTitle("JComboBox Selected Item");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setLayout(new FlowLayout(FlowLayout.LEFT));
// Create a combo box with four items and set it to editable so that
// user can
// enter their own value.
final JComboBox<String> comboBox =
new JComboBox<>(new String[]{"One", "Two", "Three", "Four"});
comboBox.setEditable(true);
getContentPane().add(comboBox);
// Create two button that will set the selected item of the combo box.
// The first button select "Two" and second button select "Four".
JButton button1 = new JButton("Set Two");
getContentPane().add(button1);
button1.addActionListener(e -> comboBox.setSelectedItem("Two"));
JButton button2 = new JButton("Set Four");
getContentPane().add(button2);
button2.addActionListener(e -> comboBox.setSelectedItem("Four"));
// Create a text field for displaying the selected item when we press
// the "Get Value" button. When user enter their own value the selected
// item returned is the string that entered by user.
final JTextField textField = new JTextField("");
textField.setPreferredSize(new Dimension(150, 20));
JButton button3 = new JButton("Get Value");
getContentPane().add(button3);
getContentPane().add(textField);
button3.addActionListener(
e -> textField.setText((String) comboBox.getSelectedItem()));
}
}
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024
Hi, I wanted to ask a question, if I should select a JComboBox item using the id that comes to me from the database, because I have a database structure with (id, name), I can’t use setSelectedItem because it selects the position and not the id . Is there a way to be able to pre-select a value of the JComboBox read from the database as an id? Thank you in advance.