简体   繁体   English

图片不会在第一次加载

[英]Image doesn't load the first time

I've been going on this example found online to write a similar program. 我一直在网上找到这个例子来编写类似的程序。 It's load images the first time when you click on it in the Filechooser, but I have to do it twice before the image is display. 第一次在Filechooser中单击它时会加载图像,但是在显示图像之前我必须做两次。 I've tried putting the repaint elsewhere, but it doesn't work, but the window resizes to the image I'm trying to load. 我尝试将重绘放置在其他位置,但是它不起作用,但是窗口会调整为要尝试加载的图像的大小。

Thanks! 谢谢!

 if(event.getSource() == menuitem1){

        dialog.setMode(FileDialog.LOAD);

        dialog.setVisible(true);

        try{
            if(!dialog.getFile().equals("")){
                File input = new File(dialog.getDirectory() + 
                    dialog.getFile()); 
                bufferedImage = ImageIO.read(input); 


                setSize(getInsets().left + getInsets().right + 
                    Math.max(400, bufferedImage.getWidth() + 60), 
                    getInsets().top + getInsets().bottom + 
                    Math.max(340, bufferedImage.getHeight() + 60));


                button1.setBounds(30, getHeight() - 30, 60, 20);
                button2.setBounds(100, getHeight() - 30, 60, 20);
                button3.setBounds(170, getHeight() - 30, 60, 20);
                button4.setBounds(240, getHeight() - 30, 60, 20);
                button5.setBounds(310, getHeight() - 30, 60, 20);
            }
        }
        catch(Exception e){
            System.out.println(e.getMessage());
        }

public void paint(Graphics g) 
{
    if(bufferedImage != null){
        g.drawImage(bufferedImage, 
            getSize().width / 2 - bufferedImage.getWidth() / 2,
            getInsets().top + 20, this);
    }
}

try calling paintComponent 尝试调用paintComponent

public void paintComponent(Graphics g) {
        super.paintComponent(g); 
         if(bufferedImage != null){
            g.drawImage(bufferedImage, 
            getSize().width / 2 - bufferedImage.getWidth() / 2,
            getInsets().top + 20, this);
         }
 }

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

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