jtable 不显示的问题,谢谢(jtable中显示sql中查询的结果集)
import java.sql.*;
import javax.swing.table.*;
import java.util.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class Demo extends JFrame implements ActionListener
{
JPanel jp1,jp2;
DefaultTableModel dtm=null;
JTable jtb;
JScrollPane jsp=null;
Vector row=null;
Vector col=null;
JButton jb=null;
//java.sql.ResultSet rs;
public Demo()
{
jp1=new JPanel();
jp2=new JPanel();
jb=new JButton( "ok ");
jb.addActionListener(this);
dtm=new DefaultTableModel();
jtb=new JTable(dtm);
jtb.setPreferredScrollableViewportSize(new Dimension(400,300));
jsp=new JScrollPane(jtb);
jp1.add(jb);
jp2.add(jsp);
this.add(jp1, "North ");
this.add(jp2, "Center ");
this.pack();
this.show();
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==jb)
{
try
{
Class.forName( "com.microsoft.jdbc.sqlserver.SQLServerDriver ");
java.sql.Connection conn = java.sql.DriverManager.getConnection( "jdbc:microsoft:sqlserver://127.0.0.1:1433;DatabaseName=Northwind ", "sa ", " ");
java.sql.Statement stmt = conn.createStatement();
ResultSetrs = stmt.executeQuery( "select * from Customers ");
ResultSetMetaData rsmd=rs.getMetaData();
for (int i = 1; i <=rsmd.getColumnCount(); i++)
{
System.out.println (rsmd.getColumnName(i));//这句话能打印出第第一列的列名 "CustomerID " 说明 连接数据库没有问题啊
col.add(rsmd.getColumnName(i));///ljlajflajflafja
}
while(rs.next())
{
Vector v=new Vector();
for (int i = 1; i <=rsmd.getColumnCount(); i++)
{
v.add(rs.getString(i));
}
row.add(v);
}
dtm.setDataVector(row,col);
}
catch (Exception ex)
{
System.out.println (ex.getMessage()+ "error ");
}
}
}
public static void main(String[] args)
{
new Demo();
}
}
[解决办法]
up
[解决办法]
给大家介绍个技术群
大家一起学习,一起提高
21189212
[解决办法]
光是这些代码的话可能问题出在这里。
Vector row=null;
Vector col=null;
后面也没见你初始化。
一开始就初始化试试看
Vector row=new Vector();
Vector col= new Vector();
[解决办法]
package org.chenliang.interview;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class TableTest {
public static void main(String[] args) {
JFrame Frame = new JFrame( "Frame ");
DefaultTableModel dtm = new DefaultTableModel();
Vector <String> colData = new Vector <String> ();
colData.addElement( "1 ");
colData.addElement( "2 ");
colData.addElement( "3 ");
colData.addElement( "4 ");
Vector <Vector> rowData = new Vector <Vector> ();
for (int i = 0; i < 38; i++) {
Vector <String> v = new Vector <String> ();
for (int j = 0; j < colData.size(); j++) {
v.add( " " + j);
}
rowData.add(v);
}
dtm.setDataVector(rowData, colData);
JTable table = new JTable(dtm);
Frame.add(new JScrollPane(table));
Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Frame.setSize(200, 200);
Frame.setVisible(true);
}
}