所以我是java和netbeans的新手,但是我编写了一个代码来从数据库中加载一些数据并在JTable中显示它,当我几天前做它时工作得很好并且显示了所有内容然而,当我今天打开它时它不显示任何东西,我真的不知道为什么,我几乎检查了一切。 这是代码:
注意:我上传了所有代码,以防需要,但您应该检查执行插入的按钮btnLoad的方法。
package cinemaohadid;
import java.awt.Component;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
public class AllMovies extends javax.swing.JFrame {
public AllMovies() {
initComponents();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
tblAllMovies = new javax.swing.JTable();
btnLoad = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Watch All Movies");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 325, Short.MAX_VALUE)
);
tblAllMovies.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"ID", "Title", "Genre", "Show Time"
}
) {
Class[] types = new Class [] {
java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.Object.class
};
boolean[] canEdit = new boolean [] {
false, false, false, false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
tblAllMovies.setPreferredSize(new java.awt.Dimension(400, 0));
jScrollPane1.setViewportView(tblAllMovies);
tblAllMovies.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
if (tblAllMovies.getColumnModel().getColumnCount() > 0) {
tblAllMovies.getColumnModel().getColumn(0).setMinWidth(20);
tblAllMovies.getColumnModel().getColumn(0).setPreferredWidth(20);
tblAllMovies.getColumnModel().getColumn(1).setPreferredWidth(200);
tblAllMovies.getColumnModel().getColumn(2).setPreferredWidth(60);
tblAllMovies.getColumnModel().getColumn(3).setResizable(false);
tblAllMovies.getColumnModel().getColumn(3).setPreferredWidth(120);
}
btnLoad.setText("Load");
btnLoad.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnLoadActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 488, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(btnLoad)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(btnLoad)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void btnLoadActionPerformed(java.awt.event.ActionEvent evt) {
String user = "aa";
String pass = "aa";
String host = "jdbc:derby://localhost:1527/Results";
DefaultTableModel dtm = (DefaultTableModel) tblAllMovies.getModel();
Connection con;
try {
con = DriverManager.getConnection(host, user, pass);
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
String SQL = "SELECT * FROM Movies";
ResultSet rs = stmt.executeQuery(SQL);
int rowcount=-1;
while (rs.next()) {
rowcount++;
int movieID = rs.getInt("MOVIEID");
String movieName = rs.getString("MOVIENAME");
Timestamp movieTime = rs.getTimestamp("MOVIETIME");
String movieGenre = rs.getString("MOVIEGENRE");
dtm.addRow(new Object[]{movieID,movieName ,movieGenre ,movieTime});
}
dtm.fireTableDataChanged();
stmt.close();
rs.close();
} catch (SQLException err) {
System.out.println(err.getMessage());
}
//btnLoad.setVisible(false);
}
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(AllMovies.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(AllMovies.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(AllMovies.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(AllMovies.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new AllMovies().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton btnLoad;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable tblAllMovies;
// End of variables declaration
}
答案 0 :(得分:1)
关闭结果集后,您是否尝试在pack();
方法中加入btnLoadActionPerformed
?您似乎在告诉表格其值已更改但未更新图形元素。
对于它的价值,我就是这样做的。首先创建一个扩展默认表模型的新类:
class MovieTableModel extends DefaultTableModel {
private static boolean[] canEdit = new boolean[] {false, false, false, false};
public MovieTableModel() {
super();
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit[columnIndex]; // or just return false if it's always going to be false
}
}
然后将btnLoadActionPerformed
更改为
private void btnLoadActionPerformed(java.awt.event.ActionEvent evt) {
String user = "aa";
String pass = "aa";
String host = "jdbc:derby://localhost:1527/Results";
Connection con;
try {
con = DriverManager.getConnection(host, user, pass);
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
String SQL = "SELECT * FROM Movies";
ResultSet rs = stmt.executeQuery(SQL);
MovieTableModel mtm = new MovieTableModel();
mtm.addColumn("ID");
mtm.addColumn("Title");
mtm.addColumn("Genre");
mtm.addColumn("Show Time");
Vector<Object> row;
while (rs.next()) {
row = new Vector<Object>();
row.add(rs.getInt("MOVIEID"));
row.add(rs.getString("MOVIENAME"));
row.add(rs.getTimestamp("MOVIETIME"));
row.add(rs.getString("MOVIEGENRE"));
mtm.addRow(row);
}
tblAllMovies = new JTable(mtm);
stmt.close();
rs.close();
pack();
} catch (SQLException err) {
System.out.println(err.getMessage());
}
}
我希望这有帮助!
== EDIT ==
更新了使用向量而不是数组来填充表格的方法。
答案 1 :(得分:1)
你可以编辑代码或给我一个代码,在我的代码中替换什么
//dtm.addRow(new Object[]{movieID,movieName ,movieGenre ,movieTime});
Vector<Object> row = new Vector<Object>();
row.addElement(movieID);
row.addElement(movieName);
row.addElement(movieGenre);
row.addElement(movieTime);
关于索引的评论是针对moarCoffee发布的示例。 Vector只是按顺序添加对象,因此您无需担心对索引进行硬编码。
此外,此建议无法解决您的问题。
编辑:
发布SSCCE的目的是简化代码。我们无权访问您的数据库,因此无法运行代码。所以你的SSCCE应该是演示问题的代码。这是通过删除SQL逻辑而不是使用:
来完成的private void btnLoadActionPerformed(java.awt.event.ActionEvent evt)
{
DefaultTableModel dtm = (DefaultTableModel) tblAllMovies.getModel();
dtm.addRow( new Object[]{new Integer(1), "movieName1" , "movieGenre1", "movieTime1"} );
dtm.addRow( new Object[]{new Integer(2), "movieName2" , "movieGenre2", "movieTime2"} );
dtm.addRow( new Object[]{new Integer(3), "movieName3" , "movieGenre3", "movieTime3"} );
dtm.addRow( new Object[]{new Integer(4), "movieName4" , "movieGenre4", "movieTime4"} );
}
确实问题仍然存在,因此验证问题不在于SQL。
接下来,我看一下IDE生成的所有垃圾代码来进行布局。果然我找到了以下一行:
tblAllMovies.setPreferredSize(new java.awt.Dimension(400, 0));
当我注释掉那条线时,它起作用了。使用Swing时不要使用setPreferredSize()
方法。
另一个建议是不要使用IDE来生成布局代码。代码是不可理解的,如果您移动到另一个IDE,则无法移植。
布局可以用几行代码完成:
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane, BorderLayout.CENTER);
Box east = Box.CreateVerticalBox();
east.add(Box.createVerticalGlue());
east.add(button);
frame.add(east, BorderLayout.LINE_END);
相反,它比IDE生成的所有代码更简单,更容易理解。你可以轻松地自定义上面的内容,添加一些Borders,使其看起来完全符合另外两行代码的需要。