图像第一次不加载

时间:2015-02-27 01:17:51

标签: java image

我一直在网上找到一个类似程序的例子。它是在Filechooser中第一次点击它时加载图像,但是在显示图像之前我必须做两次。我曾尝试将重复版本放在其他位置,但它不起作用,但窗口会调整为我尝试加载的图像。

谢谢!

 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);
    }
}

1 个答案:

答案 0 :(得分:0)

尝试拨打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);
         }
 }