【发布时间】:2016-01-05 19:04:50
【问题描述】:
我正在尝试制作一个程序,其中显示的 JTabel 会根据用户选择的文件而变化。他们通过单击调用某个方法()的按钮来输入此信息,该方法返回一个新的 JTable。但我无法让 GUI 中的表格更新。
public class program extends JFrame{
public JPanel panel;
public JTable table;
public program{
this.panel = new JPanel();
panel.setLayout(new FlowLayout());
JTable table = new JTable();
panel.add(table);
JButton button = new JButton();
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JFileChooser chooser = new JFileChooser();
if(browser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
table = method(); //some method that changes the values of the table
panel.revalidate();
panel.repaint();
}
};
});
panel.add(button);
setContentPane(panel);
setVisible(true);
}
private static JTable method(){ ... }
public static void main(String[] args){
program something = new program();
}
}
尽管阅读了很多关于 validate()、revalidate() 和 repaint() 的信息,但我并不完全确定它们之间的区别。我也试过table.revalidate() 等。相反,但这也不好。
编辑:感谢您的帮助,现在一切都已整理好 :) 我将我的 ActionListener 重写为 resueman 的“指示”:
JButton button = new JButton();
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JFileChooser chooser = new JFileChooser();
if(browser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
panel.remove(table);
table = method();
panel.add(table);
panel.revalidate();
panel.repaint();
}
};
});
我一直犹豫要不要这样做,因为 FlowLayout 会将它放在我不想要的地方。但是通过在主面板中添加额外的 JPanel,它可以被控制。
感谢 cmets,你们拯救了我的一天!
【问题讨论】:
-
但是如果要更新 JTable 数据,为什么要重新绘制和重新验证 JPanel?
-
为
table设置新值不会更改面板的内容。它仍然引用旧值。 -
更具体地说,
table = method(); //some method that changes the values of the table行的评论是在撒谎。这不会改变表的值;它可能会创建一个新表
标签: java swing user-interface jpanel repaint