4

に画像を表示しようとしていますJPanel。画像のレンダリングにを使用してImageIconいますが、画像はクラス ファイルと同じディレクトリにあります。ただし、画像は表示されておらず、エラーは発生していません。誰かが私のコードの何が問題なのかを理解するのを手伝ってくれませんか...

package ev;

import java.awt.Graphics;
import javax.swing.ImageIcon;
import javax.swing.JPanel;

public class Image extends JPanel {

    ImageIcon image = new ImageIcon("peanut.jpg");
    int x = 10;
    int y = 10;

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        image.paintIcon(this, g, x, y);
    }
}
4

2 に答える 2

4

これは、プログラマの間でよくある混乱です。getClass().getResource(path)クラスパスからリソースをロードします。

ImageIcon image = new ImageIcon("peanut.jpg");

画像ファイルの名前のみを指定すると、Java は現在の作業ディレクトリでそれを探します。NetBeans を使用している場合、CWD はプロジェクト ディレクトリです。次の呼び出しを使用して、実行時に CWD を把握できます。

System.out.println(new File("").getAbsolutePath());

以下は、これを自分でテストできるコード例です。

package com.zetcode;

import java.awt.Dimension;
import java.awt.Graphics;
import java.io.File;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

class DrawingPanel extends JPanel {

    private ImageIcon icon;

    public DrawingPanel() {

        loadImage();
        int w = icon.getIconWidth();
        int h = icon.getIconHeight();
        setPreferredSize(new Dimension(w, h));

    }

    private void loadImage() {

        icon = new ImageIcon("book.jpg");
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        icon.paintIcon(this, g, 0, 0);
    }

}

public class ImageIconExample extends JFrame {

    public ImageIconExample() {

        initUI();
    }

    private void initUI() {

        DrawingPanel dpnl = new DrawingPanel();
        add(dpnl);

        // System.out.println(new File("").getAbsolutePath());         

        pack();
        setTitle("Image");
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        
    }

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

            @Override
            public void run() {                
                JFrame ex = new ImageIconExample();
                ex.setVisible(true);                
            }
        });
    }
}

次の図は、コンストラクターにイメージ名のみを提供する場合に、NetBeans で book.jpg イメージを配置する場所を示していますImageIcon

NetBeans プロジェクト内のイメージの場所

コマンドラインから同じプログラムがあります。ImageIconExample ディレクトリ内にいます。

$ pwd
/home/vronskij/prog/swing/ImageIconExample

$ツリー
.
├──本.jpg
└──コム
    └──ゼットコード
        ├── DrawingPanel.class
        ├── ImageIconExample$1.class
        ├── ImageIconExample.class
        └── ImageIconExample.java

2 ディレクトリ、5 ファイル

プログラムは次のコマンドで実行されます。

$ ~/bin/jdk1.7.0_45/bin/java com.zetcode.ImageIconExample

詳細については、Javaチュートリアルで画像を表示するを参照してください。

于 2014-01-28T12:51:15.573 に答える
2

使用する必要があります

ImageIcon image = new ImageIcon(this.getClass()
                .getResource("org/myproject/mypackage/peanut.jpg"));
于 2012-04-10T08:23:49.663 に答える