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?但是,图像已成功附加,如果我调整窗口大小可以看到该图像。
最佳答案
我不确定您是否希望两个静态字段的宽度和高度对组件的实际尺寸有任何影响,还是只是将它们用于调试。您声明的静态字段遮盖了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);
}
}