[英]An ImageIcon not even used is affecting my JFrame/JPanel. Why?
I hope this isn't a stupid first question; 我希望这不是一个愚蠢的首要问题。 I can't seem to find an answer anyway. 无论如何,我似乎都找不到答案。
I have this JFrame
constructor where a JPanel
is added to the JFrame
. 我有这个JFrame
构造函数,其中将JPanel
添加到JFrame
。 The JPanel
paints a Rectangle
in the JFrame
, and that's fine. JPanel
在JFrame
绘制一个Rectangle
,这很好。 However , if I add an ImageIcon
object as in the code below (for later use), the rectangle isn't painted. 但是 ,如果按照下面的代码添加ImageIcon
对象(以供以后使用),则不会绘制矩形。 It does appear if I resize the window though. 如果我调整窗口大小,它确实会出现。
One solution is to put the setVisible(true)
as the last line, or to instantiate the ImageIcon
above the constructor, but I really want to understand this. 一种解决方案是将setVisible(true)
作为最后一行,或在构造函数上方实例化ImageIcon
,但我真的很想理解这一点。 It doesn't make sense to me that an object not even used can cause this behaviour. 对我来说,甚至不使用的物体也可能导致这种行为是没有意义的。 Thanks. 谢谢。
public class AJFrame extends JFrame {
ImageIcon ii;
public AJFrame() {
setSize(400,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
ImageIcon ii = new ImageIcon("Untitled.png");
JPanel jp = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
g.fillRect(0, 0, 50, 50);
}
};
add(jp);
}
public static void main(String[] args) {
AJFrame jf = new AJFrame();
}
}
All actions within a frame should be done in the EDT (Event Dispatching Thread) of Swing. 框架内的所有动作均应在Swing的EDT(事件调度线程)中完成。 Therefore the right way to start your frame is 因此,正确的开始框架的方法是
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new AJFrame().setVisible(true);
}
});
So maybe it all comes down to the wrong start of your frame. 因此,也许这一切都归结为帧的错误起点。
The main routine of a Java program is not started within the EDT. Java程序的主例程不在EDT中启动。 All Swing actions that are not within the EDT could produce strange refresh/visibility issues. 所有不在EDT中的Swing动作都可能产生奇怪的刷新/可见性问题。
Here is the complete sourcecode: 这是完整的源代码:
public class AJFrame extends JFrame {
ImageIcon ii;
public AJFrame() {
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
//setVisible(true);
//ImageIcon ii = new ImageIcon("Untitled.png");
JPanel jp = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
g.fillRect(0, 0, 50, 50);
}
};
add(jp);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new AJFrame().setVisible(true);
}
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.