我目前有一个发送 HTTP 请求的 SwingWorker,我重写了 SwingWorker 的 done() 方法以更改 JFrame 中的内容。我想基本上删除所有内容,并根据从服务器返回的值在 JFrame 上添加一个新的成员面板。
现在,我面临的问题是,当我在 JFrame 上调用以下方法时,它不会从 JFrame 中删除任何内容,也不会更改 Frame 中包含的内容。
//TODO: Investigate why JFrame content pane won't repaint.
f.removeAll();
//Pass the frame f reference only into MainDisplay, it doesn't actually do anything apart from allowing a class to add a JMenuBar on the JFrame.
f.add(new MainDisplay(f));
f.getContentPane().invalidate();
f.getContentPane().validate();
f.getContentPane().repaint();
我目前的修复是下面这个,但我宁愿更改 JFrame 的内容而不是加载一个新的内容。
f.dispose();
f=new ApplicationFrame();
我在这里和 Google 上查看了以前的答案,有些状态在调用 repaint() 重绘 JFrame 时使用 validate() 或 invalidate()。
如有任何建议/帮助,我们将不胜感激。
编辑:我想我要进行更多调试,因为一定有其他地方出错了。
最佳答案
例如
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyFrame extends JFrame {
private static final long serialVersionUID = 1L;
public MyFrame() {
final JPanel parentPanel = new JPanel();
parentPanel.setLayout(new BorderLayout(10, 10));
final JPanel childPanel1 = new JPanel();
childPanel1.setBackground(Color.red);
childPanel1.setPreferredSize(new Dimension(300, 40));
final JPanel childPanel2 = new JPanel();
childPanel2.setBackground(Color.blue);
childPanel2.setPreferredSize(new Dimension(800, 600));
JButton myButton = new JButton("Add Component ");
myButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
parentPanel.remove(childPanel1);
parentPanel.add(childPanel2, BorderLayout.CENTER);
parentPanel.revalidate();
parentPanel.repaint();
pack();
}
});
setTitle("My Empty Frame");
setLocation(10, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
parentPanel.add(childPanel1, BorderLayout.CENTER);
parentPanel.add(myButton, BorderLayout.SOUTH);
add(parentPanel);
pack();
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
MyFrame myFrame = new MyFrame();
}
});
}
}
关于java - JFrame 删除 JPanel 并添加新的 JPanel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8248152/