【发布时间】:2011-09-17 01:28:40
【问题描述】:
首先:我知道这个问题似乎已经被问了几百万次,但其他问题的答案似乎都不适用于我。
有时,当我在下面的代码中运行 Message.popup(String, int) 时,文本会正确显示,但有时 JDialog 是空的,就像根本没有添加组件一样。
public class Message extends JDialog {
private int width;
private int height;
private JLabel content;
public Message(String _content, int _margin) {
super();
this.content = new JLabel(_content);
content.setFont(new Font("Monospaced", Font.BOLD, 20));
this.margin = _margin;
this.width = content.getPreferredSize().width + _margin;
this.height = content.getPreferredSize().height + _margin;
createComponents();
setProperties();
}
public static void popup(String _content, int _time) {
if (SwingUtilities.isEventDispatchThread()) {
runPopup(_content, _time);
}
else {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
runPopup(_content, _time);
}
});
}
}
private static void runPopup(String _content, int _time) {
final Message message = new Message(_content);
new Timer(_time, new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
message.dispose();
}
}).start();
}
private void createComponents() {
setLayout(new BorderLayout());
Box box = Box.createHorizontalBox();
box.add(Box.createHorizontalGlue());
box.add(content, BorderLayout.CENTER);
box.add(Box.createHorizontalGlue());
add(box);
}
private void setProperties() {
setSize(width, height);
setLocation(Coordinator.calculateCenteredWindowLocation(width, height));
setUndecorated(true);
setResizable(false);
setTitle(content.getText());
setVisible(true);
update(getGraphics());
}
}
没有update(getGraphics());,框架总是空的,但是有了它,这取决于风吹向什么方向......(想想看!)
【问题讨论】:
-
"..有时 JFrame 是空的" 什么 JFrame?为了尽快获得更好的帮助,请发布SSCCE(在您研究的数百万个线程中可能已经提到了几千次)。
-
@Andrew 抱歉,我更新了代码,它现在扩展了 JDialog 而不是 JFrame。我的错!已进行更改。