我发现当我在JPanel中使用removeAll(),然后尝试通过add()添加新内容(例如简单的文本JLabel)时,原始内容会被清除,但新内容不会出现。是的,我记得之后在JPanel上订购了repaint()操作,是的,我正在SwingUtilities.invokeLater()中进行这些操作。但是如果我保持框架不变,则不会出现JPanel的新内容。
但是,如果我手动调整框架大小,则会显示内容。
有人可以就如何让内容自行显示给我任何建议吗?感谢。
示例代码:
public class SimpleTester extends JFrame implements WindowListener {
private static final long serialVersionUID = 6768852132139940161L;
private JPanel panel;
public SimpleTester() throws HeadlessException {
super("SimpleTester");
panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
panel.add(Box.createRigidArea(new Dimension(60, 60)));
this.getContentPane().setLayout(new BoxLayout(this.getContentPane(), BoxLayout.Y_AXIS));
this.getContentPane().add(panel);
this.addWindowListener(this);
this.pack();
}
public static void main(String[] args) {
SimpleTester tester = new SimpleTester();
tester.setVisible(true);
final String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int pos = 0;
while(true) {
SwingUtilities.invokeLater(new Replacer(tester.mainPanel(), new JLabel(alphabet.substring(pos, pos+1))));
pos++;
if(pos>=alphabet.length()) {
pos = 0;
}
synchronized(tester) {
try {
tester.wait(3000L);
} catch (InterruptedException e) {
System.exit(0);
}
}
}
}
@Override
public void windowActivated(WindowEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void windowClosed(WindowEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void windowClosing(WindowEvent arg0) {
System.exit(0);
}
@Override
public void windowDeactivated(WindowEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void windowDeiconified(WindowEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void windowIconified(WindowEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void windowOpened(WindowEvent arg0) {
// TODO Auto-generated method stub
}
public JPanel mainPanel() {
return panel;
}
public static class Replacer implements Runnable {
private JPanel holder;
private Component [] fillers;
public Replacer(JPanel host, Component... contents) {
holder = host;
fillers = contents;
}
@Override
public void run() {
holder.removeAll();
holder.repaint();
if(fillers==null) {
} else {
for(int x=0;x<fillers.length;x++) {
holder.add(fillers[x]);
}
holder.repaint();
}
}
}
}