【问题标题】:Displaying an Image using Swing in Java在 Java 中使用 Swing 显示图像
【发布时间】:2017-05-20 17:03:42
【问题描述】:

我一直在爬取 Oracle 和 Stack Overflow 试图找到解决我的问题的方法,但我没有找到我想要的东西。

下面我有两个类,目前程序需要做的就是允许用户使用JFileChooser打开一个图像文件并将其显示在GUI中(所以稍后可以对其进行一些图像处理)

我已经测试了代码执行到我知道ImageGUI 类中的变量img 正在初始化为我想要在第 99 行的图片。我的问题是让图像在之前的 GUI 中显示我pack();它。

我错过了什么?

 public class ImageEditLaunch {

public static void main(String[] args) {
    ImageEditEngine program = new ImageEditEngine();

}

}

import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

public class ImageEditEngine {

    private static int[][][] originalImage;
    private static BufferedImage originalImageBuffer;

    public ImageEditEngine() {
        originalImage = new int[0][0][0];
        ImageGUI gui = new ImageGUI();
        gui.setVisible(true);
    }

    public static ImageIcon openImage(String filepath){
        try{

        File f = new File(filepath);
        BufferedImage image = ImageIO.read(f);
        originalImageBuffer = image;
        ImageIcon icon = new ImageIcon(image);
        return icon;

        }
        catch(Exception e){
            e.printStackTrace();
            return new ImageIcon();
        }

    }
}

import java.awt.Dimension;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.UIManager;

public class ImageGUI extends JFrame implements ActionListener{

    private JFrame window;

    private JMenuItem mOpenFile;
    private JMenuItem mSaveFile;
    private JMenuItem mExitCommand;

    private JMenuBar parentBar;
    private JMenu fileMenu;
    private JMenu commandMenu;

    private JPanel mainPanel;

    public ImageIcon img;

    private JLabel mLabel;

    public ImageGUI(){
        super();
        try{
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        }
        catch(Exception e){
            e.printStackTrace();
        }
        //setup CommandMenu
        commandMenu = makeMenu("Command", 'C');

        //setup FileMenu
        fileMenu  = makeMenu("File", 'F');
        mOpenFile     = makeMenuItem(fileMenu, "Open...", 'O');
        mSaveFile     = makeMenuItem(fileMenu, "Save...", 'S');
        mExitCommand  = makeMenuItem(fileMenu, "Exit", 'X');

        //setup parentBar
        parentBar = new JMenuBar();
        parentBar.add(fileMenu);
        parentBar.add(commandMenu);

        //main panel
        mainPanel = new JPanel(new BorderLayout());
        mLabel = new JLabel();
        mainPanel.add(mLabel, BorderLayout.CENTER);
        setJMenuBar(parentBar);
        setSize(new Dimension(400, 300));

    }

    protected JMenuItem makeMenuItem(JMenu menu, String name, char mnemonic){
        JMenuItem m = new JMenuItem(name, (int) mnemonic);
        m.addActionListener(this);
        menu.add(m);
        return m;
    }

    protected JMenu makeMenu(String name, char mnemonic){
        JMenu menu = new JMenu(name);
        menu.setMnemonic(mnemonic);
        return menu;
    }


    @Override
    public void actionPerformed(ActionEvent arg0) {
        if(arg0.getSource()==mOpenFile){
            String path = null;

            JFileChooser jfc = new JFileChooser();
            jfc.setCurrentDirectory(new File("."));

            int result = jfc.showOpenDialog(this);

            if (result == JFileChooser.APPROVE_OPTION) {
                File file = jfc.getSelectedFile();
                path = file.getAbsolutePath();
            }

            img=ImageEditEngine.openImage(path);
            mLabel= new JLabel(img);
            mLabel.setVisible(true);
            this.repaint();
            pack();

        }

    }
}

mLabel 上 toString() 的值就在:

mLabel = new JLabel(img);

如下

javax.swing.JLabel[,0,0,0x0,invalid,alignmentX=0.0,alignmentY=0.0,
border=,flags=8388608,maximumSize=,minimumSize=,preferredSize=,
defaultIcon=javax.swing.ImageIcon@2bd58ce,disabledIcon=,
horizontalAlignment=CENTER,horizontalTextPosition=TRAILING,
iconTextGap=4,labelFor=,text=,verticalAlignment=CENTER,
verticalTextPosition=CENTER]

【问题讨论】:

  • 1) 文件选择器返回File,因此传递该文件而不是String。 2) 您要打开的文件名和扩展名到底是什么? JRE 将只能加载特定类型的图像。
  • 我现在试试,我正在尝试打开一个 jpg 文件
  • “我正在尝试打开一个 jpg 文件” JPEG 是一种“容器格式”,可以通过多种方式进行编码。 Java 可以接受其中的一些,但不能接受其他的。下载this answer 中提到的一张图片 并尝试加载它。它们绝对是“Java 兼容的”。
  • 1) 不要将代码或异常输出放在难以辨认的 cmets 中。将其作为edit 添加到问题中,并使用代码格式。 2) 将问题简化为minimal reproducible example,并热链接到该问题的图像(即通过 URL 加载它们),以便其他人测试。请注意,MCVE 需要 main(String[]) 方法来启动它,导入.. 基本上所有需要的东西都可以通过单个复制/粘贴/编译/运行来演示问题。

标签: java image swing jfilechooser


【解决方案1】:

根本问题是面板从未添加到框架中。代码还有许多其他问题,其中一些是我修复的(通过删除它的整个部分),还有一些是我调整的。下面显示的代码还有其他问题需要修复(我在惰性编码中介绍了其中一两个问题 - 但它们不是致命的)。

话虽如此,这段代码现在可以工作了。仔细查看它以获取提示。请注意,它是一个热链接到图像的 MCVE,所以它应该很容易测试。

import java.awt.image.*;
import java.awt.*;
import javax.swing.*;
import javax.imageio.*;
import java.net.URL;

public class ImageEditEngine {

    private static int[][][] originalImage;
    private static BufferedImage originalImageBuffer;

    public ImageEditEngine() {
        originalImage = new int[0][0][0];
        ImageGUI gui = new ImageGUI();
        gui.setVisible(true);
    }

    public static ImageIcon openImage(){
        try{
            URL url = new URL("https://i.stack.imgur.com/OVOg3.jpg");

            BufferedImage image = ImageIO.read(url);
            originalImageBuffer = image;
            ImageIcon icon = new ImageIcon(image);
            return icon;

        }
        catch(Exception e){
            e.printStackTrace();
            return new ImageIcon();
        }
    }

    public static void main(String[] args) {
        new ImageEditEngine();
    }
}


class ImageGUI extends JFrame {

    private JPanel mainPanel;

    public ImageIcon img;

    private JLabel mLabel;

    public ImageGUI(){
        super();
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        try{
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        }
        catch(Exception e){
            e.printStackTrace();
        }
        //main panel
        mainPanel = new JPanel(new BorderLayout());
        mLabel = new JLabel();
        mainPanel.add(mLabel, BorderLayout.CENTER);

        add(mainPanel);

        setSize(new Dimension(400, 300));

        img=ImageEditEngine.openImage();
        mLabel.setIcon(img);
        mLabel.setVisible(true);
        this.repaint();
        pack();
    }
}

【讨论】:

    【解决方案2】:

    如果我想在 GUI 上显示图像,我将图像嵌入到 JLabel 中。它完美地工作。

    BufferedImage img = ImageIO.read(new File(IMG_PATH));
    ImageIcon icon = new ImageIcon(img);
    JLabel label = new JLabel(icon);
    

    Displaying an image in Java Swing

    这应该可行!

    【讨论】:

    • 就我而言,它是通过 toString(); JLabel 从未被初始化,尽管我的代码是 'mLabel = new JLabel(img);'其中 img 是我检查过的已初始化的图像图标。
    • 这个答案没有解决问题中代码中的核心问题。
    猜你喜欢
    • 2015-05-16
    • 1970-01-01
    • 2021-06-08
    • 1970-01-01
    • 2014-12-18
    • 1970-01-01
    • 2010-10-09
    • 2010-09-07
    相关资源
    最近更新 更多