怎样用Java实现将在数据库中查询到的数据显示在表格中

我在Java中自己定义了一个表格,我想将在数据库中查询到的数据显示在这个表格中

JTable的有一个方法是getTableModel().返回提供此 JTable 所显示数据的 TableModel.
TableModel是一个接口,实际上返回的是DefaultTableModel类,它实现了TableModel接口。这个类中有一个方法是void addRow(Object[] rowData)。它就是将一行插入到JTable中。
不过JTable的setValueAt方法应该就可以实现。
楼主可以定义个一个线程类来完成。
比如你需要插入100行数据,可以在线程的run方法中写一个循环,在循环中写两行代码,一行是setValueAt,一行是刷新JTable,然后再让线程睡眠,这样一行一行的显示的效果就可以出来了!
或者楼主可以用进度条来打发等待的时间,就像打开netbeans的那个进度条一样,这个可以用JProgressBar类。楼主可以去查看一下源代码。如果楼主还是没有头绪,我干脆就写个例子得了!
关于组件的添加或者类似设置窗口的大小,布局管理器等我就不做解释了!
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.table.*;

public class Test extends JFrame implements ActionListener
{

private JButton button1;
private JButton button2;
private JButton button3;
private DefaultTableModel model;
private JTable table;
private JProgressBar bar;
private JScrollPane scrollpane;
private JPanel panel;

public Test()
{
button1=new JButton("演示1");
button2=new JButton("演示2");
button3=new JButton("清空");
panel=new JPanel();
bar=new JProgressBar(0,100);
String[] colnames={"数据一","数据二"};
model=new DefaultTableModel(colnames,100);
table=new JTable(model);
scrollpane=new JScrollPane(table);
panel.setLayout(new FlowLayout());
button1.addActionListener(this);
button2.addActionListener(this);
button3.addActionListener(this);
panel.add(button1);
panel.add(button2);
panel.add(button3);
panel.add(bar);
this.setLayout(new GridLayout(2,1));
this.setSize(500,600);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.add(scrollpane);
this.add(panel);
}

public void actionPerformed(ActionEvent e)
{
String command=e.getActionCommand();
if(command.equals("演示1"))
{
ShowModel show=new ShowModel(true);
Thread thread=new Thread(show);
thread.start();
}
else if(command.equals("演示2"))
{
ShowModel show=new ShowModel(false);
Thread thread=new Thread(show);
thread.start();
}
else
{
String[] colnames={"数据一","数据二"};
model=new DefaultTableModel(colnames,100);
table.setModel(model);
}
}

private class ShowModel implements Runnable
{

private boolean type;//当type为true时,则说明是“演示1”的线程,false则相反

public ShowModel(boolean type)
{
this.type=type;
}

public void run()
{

if(type)//这个就是让线程睡眠,并且设置JTable的值
{
try{

for(int i=0;i<100;i++)
{
Test.this.table.setValueAt(String.valueOf(i),i,0);
Test.this.table.setValueAt(String.valueOf(i),i,1);
Thread.sleep(100);
}

}catch(Exception e)
{
e.printStackTrace();
}
}
else//这个就是进度条的演示
{
try{
Test.this.table.setVisible(false);
for(int i=0;i<100;i++)
{
Test.this.table.setValueAt(String.valueOf(i),i,0);
Test.this.table.setValueAt(String.valueOf(i),i,1);
Test.this.bar.setValue(i+1);
Test.this.bar.setString(String.valueOf(i+1)+"%");
Thread.sleep(40);
if(i==99)
{
Test.this.table.setVisible(true);
JOptionPane.showMessageDialog(Test.this,"OK");
Test.this.bar.setValue(0);
}

}

}catch(Exception e)
{
e.printStackTrace();
}
}
}
}

public static void main(String[] args)
{
Test test=new Test();
test.setVisible(true);
}

}追答

参考,有问题问我

温馨提示:答案为网友推荐,仅供参考
相似回答