简体   繁体   English

如何使用JFileChooser在JPanel中显示图像

[英]How to use JFileChooser to display image in a JPanel

I am trying to use a menubar that enables a user to choose a file and display it in JPanel and image should fit exactly in JPanel. 我正在尝试使用菜单栏,该菜单允许用户选择文件并在JPanel中显示它,图像应该完全适合JPanel。 But JFileChooser doesn't display anything upon successfully chosing file from dialog box. 但是,当从对话框中成功选择文件时,JFileChooser不会显示任何内容。 I tried refering to many links : How to add an image to a JPanel? 我试过引用很多链接: 如何将图像添加到JPanel? and Browse for image file and display it using Java Swing but nothing worked out. 浏览图像文件并使用Java Swing显示它但没有任何效果。 Please help. 请帮忙。 Following is my code: 以下是我的代码:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;

class Main {
private JFrame j;
private JMenu jmenu;
private JMenuBar jbar;
private JMenuItem jmi, jexit;
private JPanel jpanel, jpanelbar;
private JButton jpre, jnext;
JLabel image;
ImageIcon ic;
Image img;

Main() {
    j = new JFrame("Image Viewer");
    j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // j.setExtendedState(Frame.MAXIMIZED_BOTH);
    // j.setLocationRelativeTo(null);
    j.setLocationByPlatform(true);
    j.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    jpanel = new JPanel();
    c.anchor = GridBagConstraints.PAGE_START;
    c.fill = GridBagConstraints.HORIZONTAL;
    c.gridx = c.gridy = 0;
    c.gridwidth = 2;
    // c.weightx=0.1;
    c.weighty = 0.1;
    c.ipady = 600;
    c.insets = new Insets(5, 5, 10, 5);
    // jpanel.setBackground(Color.BLACK);
    j.add(jpanel, c);

    jpanelbar = new JPanel();
    jpanelbar.setBackground(Color.red);
    c.weightx = 0.1;
    c.gridx = 0;
    c.gridy = 1;
    c.fill = GridBagConstraints.HORIZONTAL;
    c.insets = new Insets(5, 5, 5, 5);
    c.ipady = 150;
    j.add(jpanelbar, c);

    jpanelbar.setLayout(new GridBagLayout());
    GridBagConstraints x = new GridBagConstraints();
    jpre = new JButton("Previous");
    x.gridx = 0;
    x.gridy = 0;
    x.gridwidth = 1;
    x.weightx = 0.1;
    // x.insets=new Insets(5,5,5,5);
    // x.fill=GridBagConstraints.NONE;
    jpanelbar.add(jpre, x);

    jnext = new JButton("Next");
    x.gridx = 1;
    jpanelbar.add(jnext, x);

    // Creating Menu
    jbar = new JMenuBar();
    jmenu = new JMenu("File");
    jmi = new JMenuItem("Open");
    jmi.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            JFileChooser fc = new JFileChooser();
            int result = fc.showOpenDialog(null);
            if (result == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                String sname = file.getName();
                image = new JLabel("", new ImageIcon(sname), JLabel.CENTER);
                jpanel.add(image, BorderLayout.CENTER);
            }
        }
    });
    jexit = new JMenuItem("Exit");
    jexit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            System.exit(0);
        }
    });
    jmenu.add(jmi);
    jmenu.add(jexit);
    jbar.add(jmenu);
    j.setJMenuBar(jbar);

    j.setSize(800, 600);
    j.setResizable(false);
    j.setVisible(true);
}

public static void main(String s[]) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            new Main();
        }
    });
}
}

The updated code as follows: 更新后的代码如下:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;

class Main {
private JFrame j;
private JMenu jmenu;
private JMenuBar jbar;
private JMenuItem jmi, jexit;
private JPanel jpanel, jpanelbar;
private JButton jpre, jnext;
JLabel image;
ImageIcon ic;
Image img;

Main() {
    j = new JFrame("Image Viewer");
    j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // j.setExtendedState(Frame.MAXIMIZED_BOTH);
    // j.setLocationRelativeTo(null);
    j.setLocationByPlatform(true);
    j.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    jpanel = new JPanel();
    c.anchor = GridBagConstraints.PAGE_START;
    c.fill = GridBagConstraints.HORIZONTAL;
    c.gridx = c.gridy = 0;
    c.gridwidth = 2;
    // c.weightx=0.1;
    c.weighty = 0.1;
    c.ipady = 600;
    c.insets = new Insets(5, 5, 10, 5);
    // jpanel.setBackground(Color.BLACK);
    j.add(jpanel, c);

    jpanelbar = new JPanel();
    jpanelbar.setBackground(Color.red);
    c.weightx = 0.1;
    c.gridx = 0;
    c.gridy = 1;
    c.fill = GridBagConstraints.HORIZONTAL;
    c.insets = new Insets(5, 5, 5, 5);
    c.ipady = 150;
    j.add(jpanelbar, c);

    jpanelbar.setLayout(new GridBagLayout());
    GridBagConstraints x = new GridBagConstraints();
    jpre = new JButton("Previous");
    x.gridx = 0;
    x.gridy = 0;
    x.gridwidth = 1;
    x.weightx = 0.1;
    // x.insets=new Insets(5,5,5,5);
    // x.fill=GridBagConstraints.NONE;
    jpanelbar.add(jpre, x);

    jnext = new JButton("Next");
    x.gridx = 1;
    jpanelbar.add(jnext, x);

    // Creating Menu
    jbar = new JMenuBar();
    jmenu = new JMenu("File");
    jmi = new JMenuItem("Open");
    jmi.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            JFileChooser fc = new JFileChooser();
            int result = fc.showOpenDialog(null);
            if (result == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                String sname = file.getName();
                image = new JLabel("", new ImageIcon(sname), JLabel.CENTER);
                jpanel.add(image, BorderLayout.CENTER);
                jpanel.revalidate();
                jpanel.repaint();
            }
        }
    });
    jexit = new JMenuItem("Exit");
    jexit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            System.exit(0);
        }
    });
    jmenu.add(jmi);
    jmenu.add(jexit);
    jbar.add(jmenu);
    j.setJMenuBar(jbar);

    j.setSize(800, 600);
    j.setResizable(false);
    j.setVisible(true);
}

public static void main(String s[]) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            new Main();
        }
    });
}
}

I got your code to semi work. 我把你的代码用于半工作。 There are many, many more problems to solve. 还有许多问题需要解决。

  • I added a BorderLayout to your jpanel. 我在你的jpanel中添加了BorderLayout。

  • I moved the initialization of image out of your open menu action listener, like Reimeus told you to do. 我将图像的初始化移出了打开的菜单动作监听器,就像Reimeus告诉你的那样。

  • I used ImageIO to read the image. 我使用ImageIO来读取图像。

You'll need this answer eventually. 你最终会需要这个答案。 Resize a picture to fit a JLabel 调整图片大小以适合JLabel

Here's my version of your code. 这是我的代码版本。 May God have mercy on your soul. 愿上帝怜悯你的灵魂。

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
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.SwingUtilities;

class Main {
    private JFrame      j;
    private JMenu       jmenu;
    private JMenuBar    jbar;
    private JMenuItem   jmi, jexit;
    private JPanel      jpanel, jpanelbar;
    private JButton     jpre, jnext;
    JLabel              image;
    ImageIcon           ic;
    Image               img;

    Main() {
        j = new JFrame("Image Viewer");
        j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // j.setExtendedState(Frame.MAXIMIZED_BOTH);
        // j.setLocationRelativeTo(null);
        j.setLocationByPlatform(true);
        j.setLayout(new GridBagLayout());

        GridBagConstraints c = new GridBagConstraints();
        jpanel = new JPanel();
        jpanel.setLayout(new BorderLayout());
        image = new JLabel(" ");
        jpanel.add(image, BorderLayout.CENTER);

        c.anchor = GridBagConstraints.PAGE_START;
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = c.gridy = 0;
        c.gridwidth = 2;
        // c.weightx=0.1;
        c.weighty = 0.1;
        c.ipady = 600;
        c.insets = new Insets(5, 5, 10, 5);
        // jpanel.setBackground(Color.BLACK);
        j.add(jpanel, c);

        jpanelbar = new JPanel();
        jpanelbar.setLayout(new GridBagLayout());
        jpanelbar.setBackground(Color.red);

        GridBagConstraints x = new GridBagConstraints();
        jpre = new JButton("Previous");
        x.gridx = 0;
        x.gridy = 0;
        x.gridwidth = 1;
        x.weightx = 0.1;
        // x.insets=new Insets(5,5,5,5);
        // x.fill=GridBagConstraints.NONE;
        jpanelbar.add(jpre, x);

        jnext = new JButton("Next");
        x.gridx = 1;
        jpanelbar.add(jnext, x);

        c.weightx = 0.1;
        c.gridx = 0;
        c.gridy = 1;
        c.fill = GridBagConstraints.HORIZONTAL;
        c.insets = new Insets(5, 5, 5, 5);
        c.ipady = 150;
        j.add(jpanelbar, c);

        // Creating Menu
        jbar = new JMenuBar();
        jmenu = new JMenu("File");
        jmi = new JMenuItem("Open");
        jmi.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                JFileChooser fc = new JFileChooser();
                int result = fc.showOpenDialog(null);
                if (result == JFileChooser.APPROVE_OPTION) {
                    File file = fc.getSelectedFile();
                    try {
                        image.setIcon(new ImageIcon(ImageIO.read(file)));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        jexit = new JMenuItem("Exit");
        jexit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                System.exit(0);
            }
        });
        jmenu.add(jmi);
        jmenu.add(jexit);
        jbar.add(jmenu);
        j.setJMenuBar(jbar);

//      j.setSize(800, 600);
        j.pack();
        j.setResizable(true);
        j.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new Main();
            }
        });
    }
}

Instead of getName() use getAbsolutePath() on the file object and call repaint() and revalidate() after rendering the image. 而不是getName()file对象上使用getAbsolutePath() repaint()并在渲染图像后调用repaint()revalidate()

Below code should resolve your problem: 下面的代码应解决您的问题:

jmi.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
        JFileChooser fc = new JFileChooser();
        int result = fc.showOpenDialog(null);
        if (result == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            String sname = file.getAbsolutePath(); //THIS WAS THE PROBLEM
            image = new JLabel("", new ImageIcon(sname), JLabel.CENTER);
            jpanel.add(image, BorderLayout.CENTER);
            jpanel.revalidate(); //ADD THIS AS WELL
            jpanel.repaint();  //ADD THIS AS WELL
        }
    }
});

You need to invoke 你需要调用

jpanel.revalidate();
jpanel.repaint();

after adding the JLabel image to jpanel , but why not simply add the JLabel at startup use setIcon to set the Image instead? JLabel image添加到jpanel ,为什么不在启动时简单地添加JLabel使用setIcon来设置Image

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

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