- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to pre-select JComboBox item by index in Java?
The following is an example to pre-select JComboBox item by index in Java. Here, we have selected the 3rd item by default i.e. whenever the Swing program will run, the third item would be visible instead of the 1st.
Example
import java.awt.BorderLayout; 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.JTextArea; public class SwingDemo { public static void main(String[] args) { JPanel panel = new JPanel(new BorderLayout()); String[] strArr = new String[] { "Laptop", "Mobile", "Desktop", "Tablet" }; JComboBox<String> comboBox = new JComboBox<>(strArr); panel.add(comboBox, BorderLayout.NORTH); JTextArea text = new JTextArea(5, 5); panel.add(text, BorderLayout.CENTER); JButton btn = new JButton("Click"); // selecting the index comboBox.setSelectedIndex(2); btn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { text.setText((String) comboBox.getSelectedItem()); comboBox.setSelectedIndex(0); } }); panel.add(btn, BorderLayout.SOUTH); JFrame frame = new JFrame(); frame.add(panel); frame.pack(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }
The output is as follows. The 3rd item is by default selected i.e. index 2:
Output
Here, you can check all the items:
- Related Articles
- Java Program to disable the first item on a JComboBox
- How to select the second index in Java JList?
- Java Program to select the first item in JList
- How to select one item at a time from JCheckBox in Java?
- How to display a value when select a JList item in Java?
- How to insert an item into a C# list by using an index?
- How to remove an item from a C# list by using an index?
- How to handle action event for JComboBox in Java?
- How to display the items in a JComboBox in Java
- Java Program to set JComboBox in JOptionPane
- How to select maximum item in each group with MongoDB?
- How can we implement editable JComboBox in Java?
- How to select an item from a dropdown list using Selenium WebDriver with java?
- How to display the first element in a JComboBox in Java
- How to add items in a JComboBox on runtime in Java

Advertisements