我有两张MySQL
表格,如下图所示
MOVIE_TITLE
JComboBox combo = new JComboBox();
combo.setBounds(125, 15, 190, 20);
try {
DatabaseConnection db=new DatabaseConnection();
Connection connect=db.getConnection();
String sql="Select title FROM movie_title";
PreparedStatement ps=connect.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String name = rs.getString("title");
combo.addItem(name);
}
} catch (Exception e) {
System.out.println("null");
}
combo.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
JComboBox comboBox=(JComboBox) event.getSource();
Object selected = comboBox.getSelectedItem();
displayDay(selected);
}
private void displayDay(Object selected) {
// TODO Auto-generated method stub
try {
combo1.removeAllItems();
DatabaseConnection db=new DatabaseConnection();
Connection connect=db.getConnection();
String sql="Select movie_day FROM movie WHERE movie_title = ?";
PreparedStatement ps=connect.prepareStatement(sql);
ps.setObject(1, selected);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String day = rs.getString("movie_day");
combo1.addItem(day);
}
} catch (Exception e) {
System.out.println("null");
}
}
});
我在ActionListener
中实施了comboBox
。当用户选择电影Marvel的美国队长时,它将从电影中获取movie_day
项并加载到combo1中。 有没有办法让combo1只显示2016年4月28日星期日的movie_day而不是两次?
修改
private void displayDay(Object selected) {
// TODO Auto-generated method stub
try {
combo1.removeAllItems();
DatabaseConnection db=new DatabaseConnection();
Connection connect=db.getConnection();
String sql="Select movie_day FROM movie WHERE movie_title = ?";
PreparedStatement ps=connect.prepareStatement(sql);
ps.setObject(1, selected);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String day = rs.getString("movie_day");
DefaultComboBoxModel model = (DefaultComboBoxModel)combo1.getModel();
if (model.getIndexOf(day) == -1)
{
combo1.addItem(day);
}
}
} catch (Exception e) {
System.out.println("null");
}
答案 0 :(得分:2)
有没有办法可以让combo1只显示2016年4月28日星期日的movie_day而不是两次?
在将日期添加到组合框之前,您需要检查日期是否已存在。
DefaultComboBoxModel model = (DefaultComboBoxModel)comboBox.getModel();
if (model.getIndexOf(theDate) == -1)
{
comboBox.addItem( theDate );
}
您还可以将SQL语句更改为仅获取" unique"日期,但我不太了解SQL,以便为您提供实际的语法。也许这个SQL Tutorial会有所帮助,否则你需要找到一个更好的教程。