我想创建一个java程序,其中有一个JTable(它从mysql数据库获取内容,其中一列是 boolean 值)。只有一个按钮,单击该按钮时,应弹出一条消息,显示已选中哪些行(选中复选框的行)。 这是我的代码;
public class NewJFrame extends javax.swing.JFrame {
public NewJFrame() {
initComponents();
setTitle("Found Items");
try {
String myDriver = "com.mysql.cj.jdbc.Driver";
String myUrl = "jdbc:mysql://localhost:3306/lostfound";
Class.forName(myDriver);
Connection c = DriverManager.getConnection(myUrl, "root", "");
String sql = "SELECT * FROM found";
Statement st = c.createStatement();
// execute the query, and get a java resultset
ResultSet rs =st.executeQuery(sql);
int row =0;
while(rs.next())
{
private static final int BOOLEAN_COLUMN = 4;
String name = rs.getString("name");
String description = rs.getString("description");
String location = rs.getString("location");
meza.getModel().setValueAt(name, row, 0);
meza.getModel().setValueAt(description, row, 1);
meza.getModel().setValueAt(location, row, 2);
row++;
}
}
catch (SQLException e)
{
System.out.println( e.getMessage() );
} catch (ClassNotFoundException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
meza.show();
claim.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
for(int i =0; i<meza.getRowCount(); i++)
{
Boolean checked = Boolean.valueOf(meza.getValueAt(i,3).toString());
String col = meza.getValueAt(i, 1).toString();
//DISPLAY POP UP
if(checked)
{
JOptionPane.showMessageDialog(null,col);
}
}
}
});
}
但是,我收到此错误。
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at NewJFrame$1.actionPerformed(NewJFrame.java:65)
请帮忙
最佳答案
不要在方法中使用 private 或 public 声明变量:
private static final int BOOLEAN_COLUMN = 4; //this is forbidden
改为使用:
int BOOLEAN_COLUMN = 4;
关于java - 从表中的复选框获取选中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43213435/