John Joe John Joe - 6 months ago 33
SQL Question

Load data from MySQL into JComboBox

I have two

MySQL
tables as image below

movie
enter image description here

movie_title

enter image description here

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");
}

}
});


I have implemented
ActionListener
in
comboBox
. When user select movie Marvel's Captain America, it will get the
movie_day
item from movie and load into combo1. Is there a way I can make the combo1 display the movie_day which is Sunday, 28 Apr 2016 one time only instead of two ?

Edit

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");
}

Answer

Is there a way I can make the combo1 display the movie_day which is Sunday, 28 Apr 2016 one time only instead of two ?

Before adding the date to the combo box you need to check if the date already exists.

DefaultComboBoxModel model = (DefaultComboBoxModel)comboBox.getModel();

if (model.getIndexOf(theDate) == -1)
{
    comboBox.addItem( theDate );
}

You could also change the SQL statement to only get "unique" dates, but I don't know SQL well enough to give you the actual syntax. Maybe this SQL Tutorial will help, otherwise you need to find a better tutorial.

Comments