繁体   English   中英

Java Swing 从文件选择器加载图像未显示

[英]Java Swing loading image from file chooser not displaying

这是一个课堂作业。 我应该加载一个文件并将其显示在我的 Swing 应用程序上。

我遵循了笔记中的流程,但它们含糊不清,我还使用了其他 stackoverflow 帖子,但我无法使其正常工作。 当我加载图像时,程序不会崩溃,但没有显示任何内容。

- 加载图像后是否必须重新绘制或刷新文件? 我试过了,但没有用。 我究竟做错了什么? 重绘方法有注释。

import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Part1 {

    public static File selectedFile;

      public static void main(String[] args) {
        JFrame frame = buildFrame();
        JButton button = new JButton("Select File");
        frame.add(button);

        button.addActionListener(new ActionListener() 
        {
            public void actionPerformed(ActionEvent ae) 
            {
                JFileChooser fileChooser = new JFileChooser();
                int returnValue = fileChooser.showOpenDialog(null);
                if (returnValue == JFileChooser.APPROVE_OPTION) 
                {
                    selectedFile = fileChooser.getSelectedFile();
                    CardImagePanel image = new CardImagePanel(selectedFile);
                    frame.add(image);
//                  frame.repaint();
                }
            }
        });
      }

      private static JFrame buildFrame() 
      {
            JFrame frame = new JFrame();
            frame.setSize(1000,1000);
            frame.setLayout(new FlowLayout());
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
            return frame;
      }
}

class CardImagePanel extends JPanel {
    private BufferedImage image;

    public CardImagePanel(File newImageFile)
    {
    try {
        image = ImageIO.read(newImageFile);
    } catch (IOException e){
        e.printStackTrace();}
    }

    public void paintComponent(Graphics g) {
      super.paintComponent(g);
      g.drawImage(image, 0, 0, 500, 500, this);
    }
}

如前所述,您需要调用frame.revalidate(); 添加新组件后。

您还应该调用image.setPreferredSize(new Dimension(500, 500)); 或类似的以确保您的图像不小。

暂无
暂无

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

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