当我运行它时,表格应该是空的,但在我点击"加载数据"按钮我想让它显示我从数据库中获取的数据。当我检查这部分中返回的数据时:
for (i=0; i < data.length; i++){
for (j=0; j < 4; j++){
if (data[i][j] != null)
System.out.print(data[i][j] + " ");
}
if (data[i][j-1] != null)
System.out.println();
}
这是正确的,所以我认为没有问题。有人可以解释为什么repaint()
无法正常工作或我做错了什么?
这是我的代码:
public class UserInterface {
JFrame frame = new JFrame("User Interface");
JPanel panel = new JPanel();
JButton button = new JButton("Load Data");
JTable table;
JScrollPane scrollPane;
String[] columnNames = {"name", "age", "address", "phone number"};
String[][] data = new String[100][4];
public UserInterface(){
frame.getContentPane().setSize(200, 300);
table = new JTable(data, columnNames);
scrollPane = new JScrollPane(table);
panel.add(button);
panel.add(scrollPane);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
frame.pack();
frame.setVisible(true);
button.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
ConnectDatabase cd = new ConnectDatabase();
try {
data = cd.getData();
System.out.println("we got the data from db on the ui.");
int i, j;
for (i=0; i<data.length; i++){
for (j=0; j<4; j++){
if (data[i][j] != null)
System.out.print(data[i][j] + " ");
}
if (data[i][j-1] != null)
System.out.println();
}
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
table.repaint();
scrollPane.repaint();
System.out.println("table repaint is done.");
}
});
}
@SuppressWarnings("unused")
public static void main(String[] args) {
// TODO Auto-generated method stub
UserInterface ui = new UserInterface();
}
}
答案 0 :(得分:2)
当我在data
中设置值时,似乎对我有用。您正在使用data = cd.getData();
更改数据对象,以便表格不会知道您的操作。尝试浏览返回的数据并更新原始数组,例如:
String[][] temp = cb.getData();
for (i=0; i<temp.length; i++){
for (j=0; j<4; j++){
data[i][j] = temp[i][j];
}
}
虽然两个阵列的大小相同吗?我建议使用TableModel并执行此操作,例如:
DefaultTableModel model = new DefaultTableModel(new Object[]{"name", "age", "address", "phone number"},0);
table = new JTable(model);
// Now when you populate the table, you would do this for example:
String[][] temp = cb.getData();
for (i=0; i<temp.length; i++){
model.addRow(new Object[]{temp[i][0],temp[i][1],temp[i][2],temp[i][3]});
}
答案 1 :(得分:2)
repaint
不是这样做的方法。你应该删除两次调用repaint()。
更新阵列不会有所作为,因为JTable在构造过程中制作了它们的副本,并且根本不再使用它们。
您需要告诉您的表格模型使用(副本)新数据:
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.setDataVector(data, columnNames);