我打开关于它的案例,但我不理解推荐的文章。因为我没有找到关于它的好例子。如果有人为下面的场景编写示例代码对我很有帮助。让我解释一下我的问题;
我在MSSQL DB中有SQL表,如;
Column 1: "Mach" (varchar)
Column 2: "ID" (int)
Column 3: "Status" (varchar)
Column 4: "IsActive" (bit) (values 1 or 0 under db table) //this one must show as checkbox in jTable
我想用抽象表模型创建一个jTable。使用此模型创建表时,表将第4列显示为复选框。我有几个尝试,但所有的节目在jTable的第4列都是“真实”或“假”。
提前致谢。
答案 0 :(得分:0)
最后我解决了这个问题。让我们分享我的代码;
表模型类;
class MyTableModel extends AbstractTableModel {
private String[] columnNames = {"Mach",
"ID",
"Status",
"IsActive"};
private Vector<Vector<Object>> data = new Vector<Vector<Object>>();
public MyTableModel() {try {
fetchDB();
} catch (Exception ex) {
Logger.getLogger(Config.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void fetchDB ()throws Exception{
ResultSet rs;
Statement stmt;
ResultSetMetaData rsmtd;
String query = "select Mach,ID,Status,IsActive from Configs\n" +
"order by Machine,ID";
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "jdbc:sqlserver://192.168.100.100;" + "databaseName=DBST;" + "user=" + "user1" + ";" + "password=" + "user1pass" + ";";
Connection con = DriverManager.getConnection(connectionUrl);
stmt = con.createStatement();
rs = stmt.executeQuery(query);
rsmtd = rs.getMetaData();
int columnCount = rsmtd.getColumnCount();
while (rs.next()) {
Vector<Object> vector = new Vector<Object>();
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
vector.add(rs.getObject(columnIndex));
}
data.add(vector);
}
}
catch(SQLException se){
se.printStackTrace();
}
catch (ClassNotFoundException ex) {
Logger.getLogger(Config.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
public int getColumnCount() {
return columnNames.length;
}
@Override
public int getRowCount() {
return data.size();
}
@Override
public String getColumnName(int col) {
return columnNames[col];
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
return data.elementAt(rowIndex).elementAt(columnIndex);
}
@Override
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
}
主桂;
jTable1 = new javax.swing.JTable (new MyTableModel());