web-dev-qa-db-ja.com

Java:Jlabelに画像を追加する方法は?

Image image = GenerateImage.toImage(true); //this generates an image file
JLabel thumb = new JLabel();
thumb.setIcon(image)
22
KJW

JLabelにIcon実装(つまりImageIcon)を提供する必要があります。質問のようにsetIconメソッドを介して、またはJLabelコンストラクターを介して実行できます。

Image image=GenerateImage.toImage(true);  //this generates an image file
ImageIcon icon = new ImageIcon(image); 
JLabel thumb = new JLabel();
thumb.setIcon(icon);

JLabelIcon 、および ImageIcon のJavadocを読むことをお勧めします。 。また、詳細については ラベルの使用方法のチュートリアル を確認してください。

28
Tomas Narros

URLから画像を取得するには、次のコードを使用できます。

ImageIcon imgThisImg = new ImageIcon(PicURL));

jLabel2.setIcon(imgThisImg);

それは私にとって完全に機能します。 PicUrlは、画像のURLを取得する文字列変数です。

23
Nitesh Verma

(NetBeans IDEを使用している場合)プロジェクト内に、srcフォルダーの外側にフォルダーを作成するだけです。フォルダにImagesという名前を付けました。そして、画像を画像フォルダに入れて、以下のコードを書きます。

// Import ImageIcon     
ImageIcon iconLogo = new ImageIcon("Images/YourCompanyLogo.png");
// In init() method write this code
jLabelYourCompanyLogo.setIcon(iconLogo);

プログラムを実行します。

12
mezba z

最短のコードは次のとおりです。

JLabel jLabelObject = new JLabel();
jLabelObject.setIcon(new ImageIcon(stringPictureURL));

stringPictureURL is [〜#〜] path [〜#〜] of image。

4

書くことができるシンプルなコードmain(String [] args) function

    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//application will be closed when you close frame
    frame.setSize(800,600);
    frame.setLocation(200,200);

    JFileChooser fc = new JFileChooser();
    if(fc.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION){
        BufferedImage img = ImageIO.read(fc.getSelectedFile());//it must be an image file, otherwise you'll get an exception
        JLabel label = new JLabel();
        label.setIcon(new ImageIcon(img));
        frame.getContentPane().add(label);
    }

    frame.setVisible(true);//showing up the frame
1
alexlz