how to set the selected item in combo box as displayed in java. please help me

Recommended Answers

All 3 Replies

from the JComboBox documentation...

setSelectedIndex(int anIndex) Selects the item at index anIndex.
setSelectedItem(Object anObject) Sets the selected item in the combo box display area to the object in the argument.

Check out this example.

import javax.swing.*;
import java.awt.event.*;

public class demo_combo{
JComboBox combo;
JTextField txtBox;
public static void main(String[] args){
demo_combo ar = new demo_combo();
}

public demo_combo(){
JFrame frame = new JFrame("Add-Remove Item of a Combo Box");
String items[] = {"Java", "JSP", "PHP", "C", "C++"};
combo = new JComboBox(items);
JButton button1 = new JButton("Add");
txtBox = new JTextField(20);
button1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if (!txtBox.getText().equals("")){
int a = 0;
for(int i = 0; i < combo.getItemCount(); i++){
if(combo.getItemAt(i).equals(txtBox.getText())){
a = 1;
break;
}
}
if (a == 1)
JOptionPane.showMessageDialog(null,"Combo has already this item.");
else
combo.addItem(txtBox.getText());
}
else{
JOptionPane.showMessageDialog(null,"Please enter text in Text Box");
}
}
});
JButton button2 = new JButton("Remove");
button2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if (combo.getItemCount() > 0)
combo.removeItemAt(0);
else
JOptionPane.showMessageDialog(null,"Item not available");
}
});
JPanel panel = new JPanel();
JPanel panel1 = new JPanel();
panel.add(txtBox);
panel.add(combo);
panel.add(button1);
panel.add(button2);
frame.add(panel);
// frame.add(panel1);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}
}

Interesting code,but just a few points of feedback:
1. please put code in code tags so we can read it easily.
2. int a = 0 or 1 is a very un-Java way. Please use a boolean for true/false.
3. how does this address the OP's request re setting the selected item?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.