如何在Java中的JPanel上显示图像路径?

时间:2018-06-05 00:58:50

标签: java image jpanel

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

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

1 个答案:

答案 0 :(得分:0)

我写了一个简短的测试应用程序试试这个,然后加入:

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

(使用本地文件也是jpg)

它有效。

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

(我在桌面上访问了一个jpg,所以我将它放在一个名为'New folder'的新文件夹中,尽管有空间,但它仍能正常工作)

从资源URL加载它通常是如果你想要它或它的东西,然后图像的地址将是相对的(例如,你希望它通常也包装在jar中)< / p>

如果您想使用网址,可以试试这个:

        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

E.g。

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

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

e.g。

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

(等)