Thursday, May 22, 2014

how to edit and display combobox item in java?




A component that combines a button or editable field and a drop-down list. The user can select a value from the drop-down list, which appears at the user's request. If you make the combo box editable, then the combo box includes an editable field into which the user can type a value.


comboboxd.java

package packge;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class comboboxd extends JFrame implements ItemListener,ActionListener
{
JComboBox box,box1;
JLabel lbl;
JButton b1,b2,b3;
public comboboxd()
{
Container c=getContentPane();
c.setLayout(new FlowLayout());
c.setBackground(Color.cyan);
box=new JComboBox();
box1=new JComboBox();
lbl=new JLabel();
lbl.setFont(new Font("Arial black",Font.BOLD,12));
b1=new JButton("Set");
b2=new JButton("Show Index");
b3=new JButton("Item at Index");
box.addItem("India");
box.addItem("America");
box.addItem("Germany");
box.addItem("Japan");
box.addItem("France");
box.setEditable(true);      // To edit in ComboBox
box1.addItem("Africa");
box1.addItem("America");
box.addItemListener(this);
box1.addItemListener(this);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
c.add(box);
c.add(box1);
c.add(b1);
c.add(b2);
c.add(b3);
c.add(lbl);
}

public void itemStateChanged(ItemEvent ie)
{
/*
itemStateChanged method called twice because it runs when item is selected or deselected.
above problem is resolved using getStateChange() method.
getStateChange() method returns 1 for selected item and 2 for
*/
//deselected item.
int select=ie.getStateChange();
if(select==1)
{
//if box1 item is clicked then perform the logic
if(ie.getSource()==box)
{
String str=String.valueOf(box.getSelectedItem());
lbl.setText("You selected:" +str+" of ComboBox1");
}
//if box2 item is clicked then perform the logic
if(ie.getSource()==box1)
{
/*hello will print twice because itemStateChanged() method
called twice. one for item selected and second for item
deselected.
*/
System.out.println("hello");
String str=String.valueOf(box.getSelectedItem());
lbl.setText("You selected:" +str+" of ComboBox2");
}
}//close of if(select==1)
}//close of itemStateChanged(ItemEvent ie)

public void actionPerformed(ActionEvent ae)
{ 
if(ae.getSource()==b1)
 box.addItem(box.getSelectedItem());
if(ae.getSource()==b2)
 lbl.setText("Your selected Item  index: " +String.valueOf(box.getSelectedIndex()));
if(ae.getSource()==b3)
 lbl.setText("Item at Index: " +String.valueOf(box.getSelectedIndex()) +" is "+String.valueOf(box.getItemAt(box.getSelectedIndex())));
}

public static void main(String args[])
{
comboboxd demo=new comboboxd();
demo.setTitle("combo Box");
demo.setSize(850,300);
demo.setVisible(true);
demo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

OUTPUT:-

No comments:

Post a Comment