Когда я запустил его, таблица должна быть пустой, но после нажатия кнопки «Загрузить данные» я хочу, чтобы она отображала данные, которые я получаю из базы данных. Когда я проверю возвращенные данные в этой части:Метод Java JTable repaint() не работает после изменения данных
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();
}
}
Try вызова Validate() или перепроверить() метод или Invalidate() вместе с перекрашивать(). –