我当然有一个发送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();
我在这里和谷歌上看过以前的答案,有些州使用validate()或invalidate()同时调用repaint()来重绘JFrame.
任何建议/帮助将不胜感激.
编辑:我想我会调试更多,因为一定有其他问题.
最佳答案
例如
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();
}
});
}
}