所以我有一个带有JTable的应用程序。 JTable位于JScrollPane中,JScrollPane绘制在JFrame上。
现在在我的应用程序中,我打开一个新窗口向该表添加一个新行,然后在单击按钮保存更改后,新窗口关闭。
现在我尝试在新窗口关闭后添加这些行:
askTableInfo(); //a method to save the info in database to table and then save the table to variable 'table'
table.repaint();
scrollPane.repaint();
当然重绘();通过它自己。但它似乎仍然没有在JFrame中更新我的表。
这可能是什么问题?
public class AppWindow extends JFrame implements ActionListener {
String user = "";
JLabel greetText = new JLabel();
JPanel panel = new JPanel();
JPanel panel2 = new JPanel(new GridLayout(1, 3));
JScrollPane scrollPane;
JTable tabel;
JButton newBook = new JButton("Add a book");
JButton deleteBook = new JButton("Remove a book");
JButton changeBook = new JButton("Change a book");
int ID;
public AppWindow(String user, int ID) {
this.ID = ID;
this.user = user;
setSize(500, 500);
setTitle("Books");
setLayout(new BorderLayout());
greetText.setText("Hi "+user+" here are your books:");
add(greetText, BorderLayout.NORTH);
askData();
panel.add(scrollPane);
add(panel, BorderLayout.CENTER);
panel2.add(newBook);
panel2.add(deleteBook);
panel2.add(changeBook);
add(paneel2, BorderLayout.SOUTH);
newBook.addActionListener(this);
setVisible(true);
}
private void askData() {
DataAsker asker = null;
try {
asker = new AndmeKysija(ID);
} catch (SQLException e) {
e.printStackTrace();
}
table = asker.giveTable();
scrollPane = new JScrollPane(tabel);
}
public static void main(String[] args){
AppWindow window = new AppWindow("Name", 2);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == newBook){
new BookAdded(ID);
panel.revalidate();
panel.add(scrollPane);
panel.repaint();
repaint();
}
}
}
答案 0 :(得分:1)
不是最好的方法,但它可以让你跨越......
public AppWindow(String user, int ID) {
this.ID = ID;
this.user = user;
setSize(500, 500);
setTitle("Books");
setLayout(new BorderLayout());
greetText.setText("Hi "+user+" here are your books:");
add(greetText, BorderLayout.NORTH);
JTable table = askData();
scrollPane.setViewportView(table);
panel.add(scrollPane);
add(panel, BorderLayout.CENTER);
panel2.add(newBook);
panel2.add(deleteBook);
panel2.add(changeBook);
add(paneel2, BorderLayout.SOUTH);
newBook.addActionListener(this);
setVisible(true);
}
private JTable askData() {
DataAsker asker = null;
try {
asker = new AndmeKysija(ID);
} catch (SQLException e) {
e.printStackTrace();
}
return asker.giveTable();
}
public static void main(String[] args){
AppWindow window = new AppWindow("Name", 2);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == newBook){
new BookAdded(ID);
JTable table = askData();
scrollPane.setViewportView(table);
}
}
您应该做的是从TableModel
的结果中创建新的AndmeKysija
,AndmeKysija
应该有UI的想法或概念。然后,您只需使用JTable#setModel
来更新视图...
Swing使用Model-View-Controller范例的变量