例子1(没有对数据库操作):
import java.awt.BorderLayout;
import java.awt.Component;}
例子2(对数据库操作):
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.plaf.basic.BasicComboBoxRenderer;
public class ComboKeyValue extends JFrame implements ActionListener {
public ComboKeyValue() {
JComboBox comboBox;
Vector model = new Vector();
String locationid = "";
String locationname = "";
try {
Connection conn = getConnection();
Statement st = conn.createStatement();
String sqllocations = "select id, name from locations";
ResultSet rss = st.executeQuery(sqllocations);
while (rss.next()) {
locationid = rss.getString("id");
locationname = rss.getString("name");
KeyValue Itemlocation = new KeyValue(locationid, locationname);
model.addElement(Itemlocation);
}
} catch (SQLException e) {
e.printStackTrace();
}
comboBox = new JComboBox(model);
comboBox.addActionListener(this);
getContentPane().add(comboBox, BorderLayout.NORTH);
}
public void actionPerformed(ActionEvent e) {
JComboBox comboBox = (JComboBox) e.getSource();
KeyValue item = (KeyValue) comboBox.getSelectedItem();
System.out.println(item.getId() + " 对应 " + item.getName());
}
class KeyValue {
private String id;
private String name;
public KeyValue(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String toString() {
return name;
}
}
public static Connection getConnection() {
Connection conn = null;
Statement stmt = null;
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException ce) {
System.out.print(ce.getMessage());
}
try {
String url = "jdbc:postgresql://localhost:5432/openbravopos";
String username = "postgres";
String password = "123";
conn = DriverManager.getConnection(url, username, password);
stmt = conn.createStatement();
} catch (Exception e) {
System.out.println(e.getMessage());
}
return conn;
}
public static void main(String[] args) {
JFrame frame = new ComboKeyValue();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}