我正在Netbeans中使用Swings。当我单击查看按钮时,我创建了一个名为“查看”的按钮,它应获取数据库表并在同一页面上的查看按钮下方显示该表。
我的代码:
private void viewActionPerformed(java.awt.event.ActionEvent evt) {
showData(); }
public void showData()
{
Connection con=null;
Statement st=null;
ResultSet rs=null;
String s;
try
{
con=DriverManager.getConnection("jdbc:mysql://localhost/testm","root","root");
st=con.createStatement();
s="select * from smpl";
rs=st.executeQuery(s);
ResultSetMetaData rsmt= rs.getMetaData();
int c=rsmt.getColumnCount();
Vector column=new Vector(c);
for(int i=1;i<=c;i++)
{
column.add(rsmt.getColumnName(i));
}
Vector data= new Vector();
Vector row= new Vector();
while(rs.next())
{
row=new Vector(c);
for(int i=1;i<=c;i++)
{
row.add(rs.getString(i));
}
data.add(row);
}
JFrame smp=new JFrame();
smp.setSize(1000,500);
// smp.setLocation(0, 300);
//smp.setUndecorated(true);
smp.setLocationRelativeTo(null);
smp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel=new JPanel();
// paneldes.setLocation(20, 100);
JTable table= new JTable(data,column);
JScrollPane jsp= new JScrollPane(table);
panel.setLayout(new BorderLayout());
//paneldes.setLocation(100, 200);
panel.add(jsp,BorderLayout.CENTER);
// paneldes.add(jsp);
// jsp.setLocation(100, 200);
this.setContentPane(panel);
this.setVisible(true);
SwingUtilities.getAncestorOfClass(null, jsp);
}
catch(Exception e)
{JOptionPane.showMessageDialog(null,"ERROR");
}finally{
try{
st.close();
rs.close();
con.close();
}catch(Exception e){
JOptionPane.showMessageDialog(null,"ERROR CLOSE");
}}}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new smplvi().setVisible(true);
}
});
}
提前致谢
最佳答案
尝试这样,而不是用向量
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
String data1 = something1.columnOneFromDB;
String data2 = something2.columnTwoFromDB;
String data3 = something3.columnThreeFromDB();
String data4 = something4.columnFourFromDB();
Object[] row = { data1, data2, data3, data4 };
model.addRow(row);