我已经设置了一个JTable
分页 - 效果很好,但是我在将数据更新到表时遇到了问题。table.repaint() 不起作用。这是我正在使用的代码。提前致谢!
String[][] data = new String[100][4];
String[] columnNames = new String[]{
"IP", "PC_NAME", "ttl", "db"};
构造函数:
gui(){
JTable table = new JTable(data, columnNames);
JScrollPane scrollPane = new JScrollPane(table);
JButton next = new JButton("next");
JButton prev = new JButton("prev");
next.addActionListener(this);
prev.addActionListener(this);
JPanel panel = new JPanel(new BorderLayout());
JPanel buttonPanel = new JPanel();
buttonPanel.add(prev);
buttonPanel.add(next);
panel.add(buttonPanel, BorderLayout.SOUTH);
panel.add(table.getTableHeader(), BorderLayout.PAGE_START);
panel.add(scrollPane, BorderLayout.CENTER);
getContentPane().add(panel);}
动作监听器:
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand() == "next") {
Rectangle rect = scrollPane.getVisibleRect();
JScrollBar bar = scrollPane.getVerticalScrollBar();
int blockIncr = scrollPane.getViewport().getViewRect().height;
bar.setValue(bar.getValue() + blockIncr);
scrollPane.scrollRectToVisible(rect);
}
if (e.getActionCommand() == "prev") {
Rectangle rect = scrollPane.getVisibleRect();
JScrollBar bar = scrollPane.getVerticalScrollBar();
int blockIncr = scrollPane.getViewport().getViewRect().height;
bar.setValue(bar.getValue() - blockIncr);
scrollPane.scrollRectToVisible(rect);
}}
这是将数据存储到数组中的函数:
int i=0;
public void WriteMonitorData (String IP, String PC_NAME, String ttl, String gw)
{
data[i][0]=IP;
data[i][1]=PC_NAME;
data[i][2]=ttl;
data[i][3]=gw;
i++;
table.repaint();
scrollPane.repaint();
}
编辑1:
我尝试使用 DefaultTableModel 仍然没有运气。这是我用于更新表的代码。构造函数代码没有改变。宣言:
private static final long serialVersionUID = 1L;
String[][] data = new String[100][4];
String[] columnNames = new String[]{
"IP", "PC_NAME", "ttl", "db"};
DefaultTableModel model = new DefaultTableModel(data,columnNames);
JTable table = new JTable(model);
JScrollPane scrollPane = new JScrollPane(table);
这是更新表的函数:
public void WriteMonitorData (String IP, String PC_NAME, String ttl, String gw)
{
System.out.println(IP);
model.setValueAt(IP, i, 0);
model.setValueAt(PC_NAME, i, 1);
model.setValueAt(ttl, i, 2);
model.setValueAt(gw, i, 3);
i++;
model.fireTableDataChanged();
table.repaint();
scrollPane.repaint();
}