【问题标题】:How to make an image path show up on a JPanel in Java?如何使图像路径显示在 Java 中的 JPanel 上?
【发布时间】:2018-06-05 00:58:49
【问题描述】:

我一直在浏览代码,但我的图像是唯一没有出现在我的最终项目中的东西。我似乎无法找出问题所在。我已将图像路径放在我的闪存驱动器和桌面上,但它似乎不起作用。请看看你能做什么。谢谢!下面是完整的代码。

import javax.swing.*;
import java.awt.*;
import javax.swing.JTabbedPane;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JComponent;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import java.awt.Color;
import java.net.MalformedURLException;
import java.io.File;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.UnsupportedLookAndFeelException;


public class LatinLife extends JPanel{

    public LatinLife() {
        super(new GridLayout(1, 1));
        Test Bub = new Test();
        //maybe make the file a picture instead of a text file


        JTabbedPane tabbedPane = new JTabbedPane();
        ImageIcon icon = createImageIcon("/Volumes/APCOMSCI/hh.jpg");
        JComponent panel1 = makeImagePanel("Latin Life Saver");
        tabbedPane.addTab("Home", icon, panel1,
                "Does nothing");
        tabbedPane.setMnemonicAt(0, KeyEvent.VK_1);
        panel1.setBackground(Color.white);

        JComponent panel2 = makeImagePanel("/Users/ashleyvpalermo/Desktop/Screen Shot 2018-05-31 at 3.33.25 PM.png");
        ImageIcon acon = createImageIcon("/Volumes/APCOMSCI/Smiling_Face_Emoji_large.png");
        tabbedPane.addTab("Cum Clauses", acon, panel2,
                "Does nothing");
        JLabel nice = new JLabel("Cum Clauses");
        nice.setIcon(acon);
        tabbedPane.setMnemonicAt(0, KeyEvent.VK_2);
        panel2.setBackground(Color.yellow);


        JComponent panel3 = makeImagePanel("Ut clauses");
        ImageIcon bcon = createImageIcon("/Volumes/APCOMSCI/images-1.jpeg");
        tabbedPane.addTab("Ut Clauses", bcon, panel3,
                "Ut Clauses");
        tabbedPane.setMnemonicAt(1, KeyEvent.VK_3);
        panel3.setBackground(Color.pink);

        JComponent panel4 = makeImagePanel("Vocab");
        ImageIcon ccon = createImageIcon("/Volumes/APCOMSCI/images.jpeg");
        tabbedPane.addTab("Vocab", ccon, panel4,
                "Still does nothing");
        tabbedPane.setMnemonicAt(2, KeyEvent.VK_4);
        panel4.setBackground(Color.white);

        JComponent panel5 = makeImagePanel("Ablatives");
        ImageIcon jcon = createImageIcon("/Volumes/APCOMSCI/Unknown-1.jpeg");
        panel5.setPreferredSize(new Dimension(410, 50));
        tabbedPane.addTab("Ablatives", jcon, panel5,
                "Does nothing at all");
        tabbedPane.setMnemonicAt(3, KeyEvent.VK_5);
        panel5.setBackground(Color.yellow);

        JComponent panel6 = makeImagePanel("Culture");
        ImageIcon kcon = createImageIcon("/Volumes/APCOMSCI/Unknown.jpeg");
        tabbedPane.addTab("Culture", kcon, panel6,
                "Still does nothing");
        tabbedPane.setMnemonicAt(2, KeyEvent.VK_6);
        panel6.setBackground(Color.pink);

         //Add the tabbed pane to this panel.
    add(tabbedPane);
        //The following line enables to use scrolling tabs.
        tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
        JPanel panel = new JPanel();

    }

    protected JComponent makeImagePanel(String path) {
        JPanel panel = new JPanel(false);
        JLabel filler = new JLabel(path);
        filler.setHorizontalAlignment(JLabel.CENTER);
        panel.setLayout(new GridLayout(1, 1));
        panel.add(filler);
        return panel;
    }

    /** Returns an ImageIcon, or null if the path was invalid. */
    protected static ImageIcon createImageIcon(String path) {
        //        java.net.URL imgURL = NewJApplet.class.getResource(path);

        try {
            java.net.URL imgURL = (new File(path)).toURL();
            if (imgURL != null) {
                return new ImageIcon(imgURL);
            } else {
                System.err.println("Couldn't find file: " + path);
            }
        } catch (MalformedURLException ex) {
            System.out.println(ex);
        }
        return null;
    }

    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from
     * the event dispatch thread.
     */
    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("Latin Life Saver");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Add content to the window.
        frame.add(new LatinLife(), BorderLayout.CENTER);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {

        //Schedule a job for the event dispatch thread:
        //creating and showing this application's GUI.
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                //Turn off metal's use of bold fonts
        UIManager.put("swing.boldMetal", Boolean.FALSE);
        createAndShowGUI();

            }
        });

    }

    public class Test {
        public Test() {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                        ex.printStackTrace();
                    }

                    JFrame frame = new JFrame("Testing");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.add(new TestPane());
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                }
            });
        }

    public class TestPane extends JPanel {

        private BufferedImage img = null;

        public TestPane() {
            try {
                img = ImageIO.read(new FileInputStream("/Users/ashleyvpalermo/Desktop/Screen Shot 2018-05-31 at 3.33.25 PM.png"));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        @Override
        public Dimension getPreferredSize() {
            return img == null ? new Dimension(200, 200) : new Dimension(img.getWidth(), img.getHeight());
        }

        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            if (img != null) {
                g2d.drawImage(img, 0, 0, this);
            }
            g2d.dispose();
        }

    }
}
}

这部分我遇到了困难,因为我最初让它作为文本工作,但现在我想在框架内放一张图片。我该怎么做?

        JComponent panel2 = makeImagePanel("/Users/ashleyvpalermo/Desktop/Screen Shot 2018-05-31 at 3.33.25 PM.png");

【问题讨论】:

  • 作为个人喜好,你应该考虑使用ImageIO.read而不是ImageIcon,因为ImageIO会在图像无法加载时抛出异常
  • TabbedPaneDemo.class.getResource(path) 假定资源可以通过在类路径元素前加上前缀来定位,但这种情况不太可能发生。您可以将图像放在您的应用程序上下文中(即 Jar 文件)并使用从项目根目录到它的路径
  • @MadProgrammer 我该怎么做呢?
  • 嵌入图像/资源?这将取决于您的 IDE/构建过程。大多数 IDE 允许您将资源放入其src 文件夹中,它们将自动包含在 Jar 中
  • 嗯,进入你的项目是一样的。加载它将遵循Class#getResourceClass#getResourceAsStream

标签: java image jpanel


【解决方案1】:

我写了一个简短的测试应用来试试这个,然后把这个:

ImageIcon icon = new ImageIcon("C:/Volumes/APCOMSCI/second_ed_sourcecode-2/APCS Final Project Latin Life Saver/Cum_Clauses_Pic.jpg");

(本地文件也是 jpg)

它奏效了。

我认为地址中的空格可能是个问题,但我的很好。

(我正在访问桌面上的 jpg,所以我把它放在一个名为“新文件夹”的新文件夹中,尽管空间很大,但它工作正常)

从资源 URL 加载它通常是如果您想将其 jar 或其他东西,然后图像的地址将是相对的(例如,您希望它通常也被打包在 jar 中)


如果你想使用 URL,你可以试试这个:

        java.net.URL imgURL = (new File(path)).toURL();

(您还需要捕获 MalformedURLException)

protected static ImageIcon createImageIcon(String path) {
//        java.net.URL imgURL = NewJApplet.class.getResource(path);

  try {
    java.net.URL imgURL = (new File(path)).toURL();
    if (imgURL != null) {
      return new ImageIcon(imgURL);
    } else {
      System.err.println("Couldn't find file: " + path);
    }
  } catch (MalformedURLException ex) {
    System.out.println(ex);
  }
  return null;
}

但是您的 IDE 应该抱怨它已被弃用 - javadoc 建议先将其转换为 URI

例如

        java.net.URL imgURL = (new File(path)).toURI().toURL();

那么为什么要通过文件呢?原因是(如果你把它作为自己的变量分开)你可以调用有用的方法,比如 .exists();

例如

        File f = new File(path);
        if (f.exists()) {
            java.net.URL imgURL = f.toURI().toURL();

(等)

【讨论】:

  • 所以我文件中的所有信息是什么让程序感到困惑? @rick
  • @AvPalermo_10:虽然 Rick 的意思很好,但请遵循 MadProgrammer 的领导,因为它迄今为止最好的答案。用户资源,而不是文件。
  • @HovercraftFullOfEels 好的,谢谢!
  • 从资源 URL 加载它通常是如果你想把它 jar 或其他东西,然后图像的地址将是相对的(例如,你希望它通常被打包在罐子也是
  • 您使用的是 IDE 吗?它应该告诉你它需要哪些类。我必须导入的小测试应用程序:import java.io.File;导入 java.net.MalformedURLException;导入 javax.swing.ImageIcon;导入 javax.swing.JFrame;导入 javax.swing.JPanel;
猜你喜欢
  • 2016-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-17
  • 1970-01-01
  • 2013-06-17
  • 2013-11-24
相关资源
最近更新 更多