所以这是我的问题,一切正常,我只是看不到结果(我在显示方法中尝试了 System.out.print("done") ,一切正常,只是表格没有向我显示结果有任何帮助谢谢这是我的代码 我想我的 table 有问题,我需要改变一些东西吗? PS:“添加”方法有效,因此问题可能出在表和其他方法上!
public class Window extends JPanel{
JButton Reload = new JButton("Realod");
JButton Valider = new JButton("ADD");
Label label = new Label("Item : ");
JTextField TFname = new JTextField();
JTable table = new JTable();
private Connection con=null;
private PreparedStatement pst = null;
public Window() throws SQLException {
this.setLayout(null);
this.add(table);
this.add(Valider);
this.add(label);
this.add(TFname);
this.add(Reload);
label.setBounds(10,10,80,20);
TFname.setBounds(100, 10, 80,30);
Valider.setBounds(100, 40, 80,30);
Reload.setBounds(160,150, 80,30);
label.setFont(new Font("ARIAL",2,26));
table.setBounds(50,190,300,250);
con = Driver.connect();
Adding();
Showing();
}
private void Adding() throws SQLException {
Valider.addActionListener(S->{
if(!TFname.getText().isEmpty()) {
String requette = "insert into Test(Nom)Values(?)";
String Name = TFname.getText();
try {
pst=con.prepareStatement(requette);
pst.setString(1, Name);
int i = pst.executeUpdate();
if(i==1) {
System.out.println("ADDIND IS DONE");
}else {
System.out.println("Error in ADDING");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
pst.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}else {
System.out.println("ALL FIELD MUST BE FIELED");
}
});
}
public ArrayList<User>userList() throws SQLException{
ArrayList<User>userList = new ArrayList<>();
String query="Select * from Test";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
User user;
while(rs.next()) {
user=new User(rs.getString("Nom"));
userList.add(user);
}
return userList;
}
public void Showing() throws SQLException {
Reload.addActionListener(e->{
ArrayList<User> list;
try {
list = userList();
DefaultTableModel model = (DefaultTableModel) table.getModel();
Object[] row = new Object[1];
for(int i=0;i<list.size();i++) {
row[0]=list.get(i).getName();
model.addRow(row);
最佳答案
停下来,去读一下 How to Use Tables 。事实上,当您阅读时,请阅读 A Visual Guide to Layout Managers和 Creating a GUI With JFC/Swing以及。 SO 并不能替代优秀的教程、文档和研究。
您的“基本”问题归结为 JTable
尚未配置为实际显示任何内容(即列)。
所以添加一些类似...
DefaultTableModel model = new DefaultTableModel(new String[]{"Name"}, 0);
table.setModel(model);
给你的构造函数将解决你的“直接”问题
this.setLayout(null);
不会对你有帮助,它会让你的生活变得无限困难。学习使用布局管理器,花时间是值得的。
您还应该关闭数据库资源,这就是 try-with-resources
太强大了
try (Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query)) {
User user;
while (rs.next()) {
user = new User(rs.getString("Nom"));
userList.add(user);
}
}
您还混合使用 Swing 和 AWT 组件,当您的 UI 变得更加复杂时,这将产生巨大的麻烦。
关于java - JTable与SQL连接在eclipse中看不到结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53136398/