简体   繁体   中英

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. 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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