1

私の目標は、imageIconを作成し、それをJLabelに追加して、GUIに表示されるようにすることです。これまでのところ、私のコードは次のとおりです。

package classes;

import javax.swing.*;

public class Picture extends JFrame {

    private ImageIcon _image1;
    private JLabel _mainLabel;      

    public Picture(){           
        _image1 = new ImageIcon("picture1.jpg");
        _mainLabel = new JLabel(_image1);
        add(_mainLabel);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }    
}    

package classes;

public class Driver {    
    public static void main(String[] args) {
        Picture p = new Picture();    
    }    
}

問題は、画像がGUIに表示されないことです。誰か提案があれば教えてくださいありがとう!

4

2 に答える 2

3

Javaがpicture1.jpgファイルの正しい場所を探していると確信していますか?このファイルは現在の作業ディレクトリにありますか?

このコードをプログラムのどこかに配置して、プログラムの実行時に呼び出されるようにします。

// show the current working directory
System.out.println("current working directory is: " + System.getProperty("user.dir")); 

返される文字列は、Javaがどこを探しているか、現在の作業ディレクトリがどこにあるかを示します。次に、その情報を使用してパスを調整するか、画像ファイルへのフルパスをいつでも使用できます。

編集:
また、JFrameをパックして、コンポーネントをレイアウトし、それに応じてサイズを変更することを忘れないでください。

   public Picture() {

      _image1 = new ImageIcon(IMAGE);
      _mainLabel = new JLabel(_image1);
      add(_mainLabel);

      pack(); // to tell the layout managers to set up the GUI
      setLocationRelativeTo(null); // center things
      setVisible(true);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   }
于 2011-07-13T03:47:23.627 に答える
0

画像をjlabelに設定するには、プログラムに1行のコードを入力します。

yourlabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("your image location here")));

画像やテキストでJlabelを設定することもできます。

于 2012-05-14T06:49:46.937 に答える