Hi,
I am working on SWING/AWT application,I write select box programs in swings.
my proble is what ever the name is selected that id should be stored in database how to passed the ID's in MAP how to stored whaterver select the name that ID should store in database
public class ComboBox{ public static void main(String[] args) { ComboBox b = new ComboBox(); } public ComboBox(){ String byers [] = {"radha","rani","vani","devi"}; JFrame frame = new JFrame("Creating a JComboBox Component"); JPanel panel = new JPanel(); combo = new JComboBox(byers); ........ combo.addItemListener(new ItemListener(){ public void itemStateChanged(ItemEvent ie){ String str = (String)combo.getSelectedItem(); txt.setText(str); } }); } }
plz give an example
Here is a required code.
import java.sql.*; import java.awt.*; import java.util.*; import java.util.*; import javax.swing.*; import java.awt.event.*; class ComboBox{ public static void main(String[] args) throws Exception{ JFrame f=new JFrame(); f.setLayout(null); JLabel lab=new JLabel("Select Name:"); String byers [] = {"radha","rani","vani","devi"}; final JComboBox combo=new JComboBox(byers); final Map map=new HashMap(); for(int i=0;i<byers.length;i++){ map.put(new Integer(i+1),byers[i]); } ActionListener actionListener = new ActionListener(){ public void actionPerformed(ActionEvent actionEvent) { ItemSelectable is = (ItemSelectable)actionEvent.getSource(); String name=selectedString(is); System.out.println(name); Set pset=map.entrySet(); int key=0; Iterator piterator=pset.iterator(); while(piterator.hasNext()) { Map.Entry m =(Map.Entry)piterator.next(); String value=(String)m.getValue(); if(value.equals(name)){ key=(Integer)m.getKey(); } } try{ Class.forName("com.mysql.jdbc.Driver").newInstance(); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root" ); Statement st=conn.createStatement(); st.executeUpdate("insert into data1(id) values("+key+")"); System.out.println("Inserted"); } catch(Exception e){ System.out.println(e); } } }; combo.addActionListener(actionListener); lab.setBounds(20,20,100,20); combo.setBounds(120,20,80,20); f.add(lab); f.add(combo); f.setVisible(true); f.setSize(300,120); } static private String selectedString(ItemSelectable is) { Object selected[] = is.getSelectedObjects(); return ((selected.length == 0) ? "null" : (String)selected[0]); } }
Ads