繁体   English   中英

JFrame维度问题

[英]JFrame Dimension issue

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? 但是,图像已成功附加,如果我调整窗口大小可以看到该图像。

我不确定您是否希望两个静态字段的宽度高度对组件的实际尺寸有任何影响,还是只是将它们用于调试。 您已声明的静态字段遮蔽了Componentwidthheight字段。 使用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);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM