【问题标题】:revalidate() and repaint() not updating my JPanelrevalidate() 和 repaint() 没有更新我的 JPanel
【发布时间】: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


【解决方案1】:

如果您可以重新设计以更改表格内容,则无需担心手动重新绘制。

尝试将您的代码修改为

 table.setModel (method());

model () 返回TableModel 而不是JTable

您看不到任何更改,因为旧的JTable 仍添加到您的面板中。如果您坚持保持方法不变,则必须删除旧的/添加新的。

祝你好运。

【讨论】:

    猜你喜欢
    • 2011-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多