我正在使用模型,我可以刷新表格的内容吗?但我将它添加到 JPanel,现在我的第二个 JPanel,包含按钮,非常深入。我正在使用 GridLayout 来控制列的大小(preferredSize())。一开始我有http://www.funkyimg.com/u2/3264/877/343679Untitled.jpg然后我必须手动将它放大到http://www.funkyimg.com/u2/3264/878/776480Untitled2 .jpg我在上一篇文章中使用的源代码,稍作修改:
public class Arsti3 {
JFrame main = new JFrame("Arst");
JPanel tP = new JPanel(new GridLayout(1,0));
JPanel bP = new JPanel();
JButton one = new JButton("Test");
JButton two = new JButton("Two");
JTable table = new JTable();
DefaultTableModel model;
Vector columnNames = new Vector();
Vector data = new Vector();
Arsti3() {
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
main.setSize(840,400);
try {
reloadData();
model = new DefaultTableModel(data,columnNames);
table.setModel(model);
//table.setRowHeight(24);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
TableColumn col;
for(int i=0; i<table.getColumnCount(); i++) {
col = table.getColumnModel().getColumn(i);
col.setPreferredWidth(100);
col.setMaxWidth(500);
}
//table.setPreferredScrollableViewportSize(new Dimension(500,500));
//model.fireTableDataChanged();
tP.add(new JScrollPane(table));
bP.add(one);
bP.add(two);
main.add(tP,BorderLayout.NORTH);
main.add(bP,BorderLayout.SOUTH);
} catch(Exception e) {
e.printStackTrace();
}
main.setVisible(true);
}
private void reloadData() throws ClassNotFoundException, SQLException {
columnNames.clear();
data.clear();
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String Base = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)}; DBQ=SL.mdb";
Connection con = DriverManager.getConnection(Base,"","");
Statement st = con.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM Arsti");
ResultSetMetaData rsmd = res.getMetaData();
int column = rsmd.getColumnCount();
columnNames.addElement("ID");
columnNames.addElement("Vards");
columnNames.addElement("Uzvards");
columnNames.addElement("Dzimums");
columnNames.addElement("Personas kods");
columnNames.addElement("Telefona numurs");
columnNames.addElement("Nodalas ID");
columnNames.addElement("Amata ID");
while(res.next()) {
Vector row = new Vector(column);
for(int i=1; i<=column; i++) {
row.addElement(res.getObject(i));
}
data.addElement(row);
}
}
public static void main(String[] args) {
new Arsti3();
}
}