public class bioscope extends Component{
static int width;
static int height;
public void paint(Graphics g){
try {
BufferedImage crow = ImageIO.read(new File("photos/houseCrow.jpg"));
this.width = crow.getWidth();
this.height = crow.getHeight();
System.out.println(this.height);
System.out.println(this.width);
g.drawImage(crow, 0, 0, null);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Bioscope: Have a peek!");
frame.getContentPane().add(new bioscope());
frame.setVisible(true);
frame.setSize(bioscope.width, bioscope.height);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame.setResizable(false);
System.out.println(bioscope.height);
System.out.println(bioscope.width);
}
}
输出窗口的高度和宽度为零,这令人沮丧但仍然可以解释。让我感到震惊的是println命令的输出。我预计这将是一个四行输出:492,640,492,640。但它首先打印出0,0,然后显然停止了。但是全屏,打印输出会附加492,640!现在你知道谁会在每次全屏时调用println,另外还会附加492,640。如果您最小化或尝试调整JFrame窗口的大小,将会出现类似的附加内容。
为什么会发生这种情况,为什么JFrame窗口首先不是492,640的尺寸?但是,如果我调整窗口大小,可以看到图像已成功附加。
答案 0 :(得分:1)
我不确定您是否希望您的两个静态字段 width 和 height 对组件的实际尺寸产生任何影响,或者如果您&# 39;重新使用它们进行调试。您声明的静态字段会影响width
中的height
和Component
字段。使用getWidth()
和getHeight()
来跟踪超类使用的实际值更合适。
首先打印0, 0
因为静态字段在第一次绘制之前未初始化。 paint
方法仅在重绘帧时调用,这就是每次更改窗口大小时都会看到日志行的原因。
试试这个:
public class bioscope extends JComponent {
transient BufferedImage crow;
public bioscope() {
try {
crow = ImageIO.read(new File("photos/houseCrow.jpg"));
} catch (IOException e) {
throw new ExceptionInInitializerError(e);
}
setPreferredSize(new Dimension(crow.getWidth(), crow.getHeight()));
}
public void paint(Graphics g){
g.drawImage(crow, 0, 0, null);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Bioscope: Have a peek!");
bioscope bioscope = new bioscope();
frame.getContentPane().add(bioscope);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
frame.setResizable(false);
}
}