基本上我想做的是:
“Dan Munteanu”
我这样做了
try{
String sql="select * from profesori";
PreparedStatement pst=connection.prepareStatement(sql);
ResultSet rs=pst.executeQuery();
while(rs.next()){
int idprof=rs.getInt("idProfesor");
String nume=rs.getString("Nume");
String prenume=rs.getString("Prenume");
comboBoxProfesor.addItem(nume+" "+prenume);
}
}catch(Exception e1){
JOptionPane.showMessageDialog(null, e1);
}
this is my database diagram || this is my applet add panel
到目前为止,我正在尝试此查询:
try {
String sql="insert into Elevi (NumeElev,InitialaTata,PrenumeElev,ScoalaDeProvenienta,Clasa,Nota,IdProfesor,IdMaterie) values (?,?,?,?,?,?,?,?)";
PreparedStatement pst=connection.prepareStatement(sql);
pst.setString(1, textNumeElev.getText());
pst.setString(2, textInitialaTata.getText());
pst.setString(3, textPrenumeElev.getText());
pst.setString(4, textScoala.getText());
pst.setString(5, textClasa.getText());
pst.setString(6, textNota.getText());
pst.setString(7, comboBoxProfesor.getSelectedItem().toString());
pst.setString(8, comboBoxMaterie.getSelectedItem().toString());
pst.execute();
JOptionPane.showMessageDialog(null, "Data Saved");
pst.close();
} catch (Exception e3){
e3.printStackTrace();
}
当然它不会起作用,因为我的7和8值应该是INT类型但我把它们作为字符串...基本上我想在我执行查询时填充ComboBox(在某处)后台)并仅在我在主表中执行FK的最后一个查询时添加它。我知道如果我只让我的组合框只返回我教授桌子的INT值,我就能做到这一点,但是我希望它能够被那些不知道这些ID号码意味着什么的人轻易使用。
对不起,如果我困扰你们,我希望你能得到我的问题:)
答案 0 :(得分:0)
您可以将各种对象放在JComboBox
中。组合框使用toString
方法确定如何显示项目。您可以在自定义类中添加id
等其他信息,例如下面示例中的Professor
类。
修改:将类名和ID添加到Professor
类
正如上面问题的评论中所讨论的,您还可以将类名和类ID添加到Professor
类。这样,当您从组合框中选择教授时,教授ID和班级ID都可用(该组合框可以显示教授的姓名和班级名称):
import javax.swing.*;
public class ObjectComboBox {
public static void main(String[] arguments) {
SwingUtilities.invokeLater(() -> new ObjectComboBox().createAndShowGui());
}
private void createAndShowGui() {
JFrame frame = new JFrame("Stack Overflow");
frame.setBounds(100, 100, 800, 600);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
JComboBox<Professor> comboBox = new JComboBox<>(new Professor[]{
new Professor("Dan Munteanu", 123456, "Mathematics", 3),
new Professor("Daniel Roy Connelly", 424242, "English", 1)
});
panel.add(comboBox);
comboBox.addActionListener(
actionEvent -> {
Professor professor = (Professor) comboBox.getSelectedItem();
System.out.println("Professor id: " + professor.getId());
System.out.println("Class id: " + professor.getClassId());
}
);
frame.getContentPane().add(panel);
frame.setVisible(true);
}
}
class Professor {
private final String name;
private final int id;
private final String className;
private final int classId;
Professor(String name, int id, String className, int classId) {
this.name = name;
this.id = id;
this.className = className;
this.classId = classId;
}
public String getName() {
return name;
}
public int getId() {
return id;
}
public String getClassName() {
return className;
}
public int getClassId() {
return classId;
}
@Override
public String toString() {
return name + ": " + className;
}
}