gpt4 book ai didi

java - 如何更新 JPanel 的内容?

转载 作者:行者123 更新时间:2023-12-02 05:00:40 24 4
gpt4 key购买 nike

我是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() 的方法。我应该使用这种方法吗?

非常感谢

最佳答案

不要创建 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);
}
});
}

关于java - 如何更新 JPanel 的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28311135/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com