我的目标是将JList与我的数据库中的数据放在2个JTextFields上,但我不知道该怎么做。你们男孩和女孩知道错误是什么以及我如何解决它? (变量personList包含所有数据。只需要将它放在JList中。但是这个变量personList是一个ArrayList。)
public class Datenbank2 extends JFrame {
public Datenbank2() {
super("Datenbank der Lehrlinge 1 Lehrjahr");
JPanel centerPanel = new JPanel();
JPanel southPanel = new JPanel();
JPanel linkesPanel = new JPanel();
this.setBounds(600, 300, 500, 450);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
try {
Class.forName("org.sqlite.JDBC");
Connection connection = DriverManager
.getConnection("jdbc:sqlite:C://Users/N-YP/workspace/UebungJava/ch/nyp/uebungen/datenbanken/SqLiteDB.db");
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("SELECT * FROM Person");
ArrayList<JLabel> personList = new ArrayList<JLabel>();
while (rs.next()) {
String vorname = rs.getString("Vorname");
String nachname = rs.getString("Nachname");
personList.add(new JLabel(vorname + " " + nachname));
System.out.println(vorname + " " + nachname);
}
JTextField eingVorname = new JTextField();
JTextField eingNachname = new JTextField();
eingVorname.setPreferredSize(new Dimension(230, 30));
eingNachname.setPreferredSize(new Dimension(230, 30));
BorderLayout borderLayout = new BorderLayout();
this.getContentPane().setLayout(borderLayout);
this.add(centerPanel, BorderLayout.CENTER);
this.add(southPanel, BorderLayout.SOUTH);
centerPanel.add(linkesPanel, BorderLayout.WEST);
FlowLayout flowLayout = new FlowLayout();
centerPanel.setLayout(flowLayout);
for (JLabel personLabel : personList) {
centerPanel.add(personLabel);
}
southPanel.setLayout(flowLayout);
southPanel.add(eingVorname);
southPanel.add(eingNachname);
}
catch (Exception exc) {
exc.printStackTrace();
System.exit(0);
System.out
.println("Datenbank geöffnet (muss später aber wieder geschlossen werden).");
}
}
public static void main(String[] args) {
Datenbank2 javamitdb = new Datenbank2();
javamitdb.setVisible(true);
}
}
谢谢你,祝你有个美好的一天。
答案 0 :(得分:1)
在while循环中使用DefaultListModel及其 addElement()方法以添加每个结果,如下所示:
listModel = new DefaultListModel();
while (rs.next()) {
String vorname = rs.getString("Vorname");
String nachname = rs.getString("Nachname");
listModel.addElement(vorname + " " + nachname);
System.out.println(vorname + " " + nachname);
}
//then create a list with this model
list = new JList(listModel);
请查看How to Use Lists以获取更多信息。