如何更新JPanel的内容?

时间:2015-02-04 00:01:24

标签: java swing jtable

我是Java的初学者。现在我正在实施这个小程序。它有一个按钮和一个包含一些随机信息的表格。当我单击按钮时,它将更新表的内容。

public class GUI extends JFrame{

private Container pane;
private JPanel topBar;
private JScrollPane tablePane;
private JButton repaint;
private JTable a,b;
private String[] columnNames = {"Name",
            "Age",
            "Major"};

public GUI(){
    pane = getContentPane();
    setLayout(new BorderLayout());
    Handler h = new Handler();
    //Create the button
    repaint = new JButton("Repaint");
    repaint.addActionListener(h);
    //the original table content
    String [][] data = { { "a", "a", "a"},
                   { "b", "b", "b"},
                   { "c", "c", "c" }};
    a = new JTable(data, columnNames);
    tablePane = new JScrollPane(a);

    pane.add(repaint,BorderLayout.NORTH);
    pane.add(tablePane,BorderLayout.SOUTH);
}
private class Handler implements ActionListener {
    public void actionPerformed(ActionEvent event){
        //update the table content
        String [][] data = { { "f", "f", "f"},
                   { "e", "e", "e"},
                   { "z", "z", "z" }};
        b = new JTable(data, columnNames);
        tablePane = new JScrollPane(b);
        pane.add(tablePane,BorderLayout.SOUTH);  
    }
}
}

现在该计划不起作用。表的内容不会改变。你能告诉我怎么做吗?我听说过一个名为repaint()的方法。我应该使用这种方法吗?

非常感谢

1 个答案:

答案 0 :(得分:2)

不要创建JTable的新实例,只需更改预先存在的表格的模型......

private class Handler implements ActionListener {
    public void actionPerformed(ActionEvent event){
        //update the table content
        String [][] data = { { "f", "f", "f"},
                   { "e", "e", "e"},
                   { "z", "z", "z" }};
        a.setModel(new DefaultTableModel(data, columnNames));
    }
}

查看How to Use Tables了解更多详情。您可能还会发现阅读Model-View-Controller很有帮助,这将有助于更好地理解Swing构建的基本前提。

您还应该查看Initial Threads并确保仅在事件调度线程中创建/修改UI

public GUI(){
    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() { 
            pane = getContentPane();
            setLayout(new BorderLayout());
            Handler h = new Handler();
            //Create the button
            repaint = new JButton("Repaint");
            repaint.addActionListener(h);
            //the original table content
            String [][] data = { { "a", "a", "a"},
                           { "b", "b", "b"},
                           { "c", "c", "c" }};
            a = new JTable(data, columnNames);
            tablePane = new JScrollPane(a);

            pane.add(repaint,BorderLayout.NORTH);
            pane.add(tablePane,BorderLayout.SOUTH);
        }
    });
}