簡體   English   中英

有人可以告訴我它從哪里拾取圖像嗎?

[英]Can someone tell me where is it picking images from?

package demo;

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

/*`enter code here`
 * ComboBoxDemo.java uses these additional files:`enter code here`
 *   images/Bird.gif
 *   images/Cat.gif
 *   images/Dog.gif
 *   images/Rabbit.gif
 *   images/Pig.gif
 */
public class Demo extends JPanel
implements ActionListener {
    JLabel picture;

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public Demo() {
        super(new BorderLayout());

        String[] petStrings = { "Bird", "Cat", "Dog", "Rabbit", "Pig" };

        //Create the combo box, select the item at index 4.
        //Indices start at 0, so 4 specifies the pig.
        JComboBox petList = new JComboBox(petStrings);
        petList.setSelectedIndex(4);
        petList.addActionListener(this);

        //Set up the picture.
        picture = new JLabel();
        picture.setFont(picture.getFont().deriveFont(Font.ITALIC));
        picture.setHorizontalAlignment(JLabel.CENTER);
        updateLabel(petStrings[petList.getSelectedIndex()]);
        picture.setBorder(BorderFactory.createEmptyBorder(10,0,0,0));

        //The preferred size is hard-coded to be the width of the
        //widest image and the height of the tallest image + the border.
        //A real program would compute this.
        picture.setPreferredSize(new Dimension(177, 122+10));

        //Lay out the demo.
        add(petList, BorderLayout.PAGE_START);
        add(picture, BorderLayout.PAGE_END);
        setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
    }

    /** Listens to the combo box. */
    public void actionPerformed(ActionEvent e) {
        JComboBox cb = (JComboBox)e.getSource();
        String petName = (String)cb.getSelectedItem();                                                          
        updateLabel(petName);
    }

    protected void updateLabel(String name) {
        ImageIcon icon = createImageIcon("images/" + name + ".png");
        picture.setIcon(icon);
        picture.setToolTipText("A drawing of a " + name.toLowerCase());
        if (icon != null) {
            picture.setText(null);
        } else {
            picture.setText("Image not found");
        }
    }

    /** Returns an ImageIcon, or null if the path was invalid. */
    protected static ImageIcon createImageIcon(String path) {
        java.net.URL imgURL = Demo.class.getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL);
        } else {
            System.err.println("Couldn't find file: " + path);
            return null;
        }
    }

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


        JComponent newContentPane = new Demo();
        newContentPane.setOpaque(true);
        frame.setContentPane(newContentPane);


        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

這是我從oracle那里獲得的代碼,但是我不知道從何處拾取圖像,因為每次我創建帶有圖像的源文件夾時,它仍然不會拾取它。 或者,如果您能告訴我代碼的哪一部分正在拾取圖像? 我的工作需要使用相同的代碼。

屏幕截圖

Demo.java所在的文件夾中創建一個名為images的文件夾。 並將您的圖像放置在那里。 根據您的代碼,圖像名稱為“ Bird.png”,“ Cat.png”,“ Dog.png”,“ Rabbit.png”,“ Pig.png”。

所以您的項目結構是這樣的:

demo
    src
    └───demo
        │   Demo.java
        └───images
                Bird.png
                Cat.png
                Dog.png
                Rabbit.png
                Pig.png
ImageIcon icon = createImageIcon("images/" + name + ".png");

該行提供的圖像路徑為images/name.pngname值可以在{"Bird", "Cat", "Dog", "Rabbit", "Pig"}

picture.setIcon(icon);

上一行將icon設置為JLabel picture

在項目的根目錄中創建一個名為images的文件夾,並將所有.png圖像放入images文件夾中。

請參閱: http : //www.thinkplexx.com/learn/howto/java/system/java-resource-loading-explained-absolute-and-relative-names-difference-between-classloader-and-class-resource-loading

我終於找到了問題所在,但我不明白為什么他們用Oracle編寫代碼的方式行不通。

返回在https://www.codetantra.com/java/jdk6.0/tutorial/uiswing/examples/components/ComboBoxDemoProject/src/components/ComboBoxDemo.java發布的原始代碼

您需要轉到項目所在的文件夾。 您將看到:bin images src

images文件夾中可能包含所有預期的圖像文件,但是程序無法以某種方式獲取它們。 將gif文件復制到保存bin,圖像和src的文件夾中。

現在,您將看到:bin images src Bird.gif Cat.gif等。

現在返回並更改Oracle的代碼:

// ImageIcon圖標= createImageIcon(“ images /” +名稱+“ .gif”); //這種方式行不通。

    ImageIcon icon = createImageIcon(name + ".gif");

如果要調試程序在何處提取文件,可以使用以下步驟創建File對象並請求其絕對路徑。

伊迪奧

System.out.println(new File("images/Bird.png").getAbsolutePath()); // C:\... or /...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM