2013-03-03 15 views
6

JComboBoxからアイテムが選択されるたびに、イメージのフォルダからアイコンをJLabelに設定しようとしています。 JComboBoxの項目の名前とフォルダ内の画像の名前は同じです。したがって、JComboBoxから項目が選択されると、同じ名前の対応するイメージをJLabelのアイコンとして設定する必要があります。私はこのようなことをしようとしています。 フォルダからの画像からアイコンをJLabelに設定する方法は?

private void cmb_movieselectPopupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt){                
     updateLabel(cmb_moviename.getSelectedItem().toString()); 
} 





protected void updateLabel(String name) { 
     ImageIcon icon = createImageIcon("C:\\Users\\xerof_000\\Pictures\\tmspictures\\" + name + ".jpg"); 
     if(icon != null){ 
      Image img = icon.getImage(); 
      Image newimg = img.getScaledInstance(lbl_pic.getWidth(), lbl_pic.getHeight(), java.awt.Image.SCALE_SMOOTH); 
      icon = new ImageIcon(newimg); 
      lbl_pic.setIcon(icon); 
      lbl_pic.setText(null); 
     } 
     else{ 
      lbl_pic.setText("Image not found"); 
      lbl_pic.setIcon(null); 
     } 
    } 





protected static ImageIcon createImageIcon(String path) { 
     URL imgURL; 
     imgURL = NowShowing.class.getResource(path); 
     if (imgURL != null) { 
      return new ImageIcon(imgURL); 
     } else { 
      return null; 
     } 
    } 

が、私は問題はであると思った "C:\ Users \ユーザーxerof_000 \写真\ tmspictures \" 私が使用してみました "C:/ユーザ/ xerof_000 /画像は/ tmspictures /" それでもそれは動作しませんでした。そして私が何をしても、JLabelには "Image not found"としか表示されません。

+2

(http://stackoverflow.com/a/9866659/1057230)[自分のリソースフォルダに画像を追加]する方法のために、それかもしれないが、いくつかの助けになるだろう、私のこの答えを見てください。あなたが手動でIDEを使わずにすべてをやっているならば、最後のリンクはあなたを確実に導くでしょう。それでもまだ不明な点がある場合は、 –

+1

質問してください。新しいImageIcon( "C:\\ Users \\ xerof_000 \\ Pictures \\ tmspictures \\" + name + ".jpg" ; 'はすぐに働くでしょうか? (これはあなたのコンピュータ上でしか動作しないので、これはあまり保守できませんが、私は同意します)。 –

+0

@GagandeepBali NetBeansからそれをやっているので、NetBeansのリンクを確認しました。問題は、.jarファイルの実行時に画像フォルダに画像を追加することです。.jarファイルを実行しているときに、.jarファイルのパッケージに画像を追加することはできません。では、.jarファイルが実行されているフォルダから画像を読み取る方法はありますか? –

答えて

12

これは私のディレクトリ構造です:NOW

package swing.imagetest;  

import java.awt.*; 
import java.awt.event.*; 
import java.net.*; 
import javax.swing.*; 
     
public class ComboExample { 

    private String[] data = new String[]{ 
              "geek0", 
              "geek1", 
              "geek2", 
              "geek3", 
              "geek4" 
             }; 
    private String MESSAGE = "No Image to display yet..."; 
    private JLabel imageLabel; 
    private JComboBox cBox; 
    private ActionListener comboActions =  
          new ActionListener() { 
     @Override 
     public void actionPerformed(ActionEvent ae) { 
      JComboBox combo = (JComboBox) ae.getSource(); 
      ImageIcon image = new ImageIcon(
         getClass().getResource(
          "/" + combo.getSelectedItem() + ".gif")); 
      if (image != null) { 
       imageLabel.setIcon(image); 
       imageLabel.setText(""); 
      } else { 
       imageLabel.setText(MESSAGE); 
      } 
     }     
    }; 

    private void displayGUI() { 
     JFrame frame = new JFrame("Combo Example"); 
     frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 

     JPanel contentPane = new JPanel(); 
     imageLabel = new JLabel(MESSAGE, JLabel.CENTER); 
     cBox = new JComboBox(data); 
     cBox.addActionListener(comboActions); 

     contentPane.add(imageLabel); 
     contentPane.add(cBox); 

     frame.setContentPane(contentPane); 
     frame.pack(); 
     frame.setLocationByPlatform(true); 
     frame.setVisible(true); 
    } 

    public static void main(String... args) { 
     EventQueue.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       new ComboExample().displayGUI(); 
      } 
     }); 
    } 
} 

COMPILATION:

       packageexample 
             | 
        ------------------------------------------- 
        |     |      | 
       build(folder)  src(folder)   manifest.txt 
        |     | 
      swing(package)  ComboExample.java 
        | 
      imagetest(subpackage) 
        | 
    ComboExample.class + related .class files 

これはComboExample.javaファイルの内容ですCOへmpile私はこれをしなかった:マニフェストファイルの

Gagandeep [email protected] ~/c/Mine/JAVA/J2SE/src/packageexample 
$ javac -d build src/*.java 

内容:

enter image description here

JARファイルの作成:

Gagandeep [email protected] ~/c/Mine/JAVA/J2SE/src/packageexample 
$ cd build 

Gagandeep [email protected] ~/c/Mine/JAVA/J2SE/src/packageexample/build 
$ jar -cfm imagecombo.jar ../manifest.txt * 

は今有する任意の場所にこのJAR Fileを取りますこれらの画像(geek0.gifgeek1.gifgeek2.gifgeek3.gifgeek4.gif)、そしてあなたはJLabelのを使用しているので、あなたは簡単な使用HTMLタグは、ちょうど< HTML>と、使用してラベルテキストを開始することができJAR Fileを実行し、

+2

+1 [チュートリアル](http://docs.oracle.com/javase/tutorial/uiswing/components/icon.html)にこの回答を引用してください。 – trashgod

+1

ありがとうございました:)私はずっと助けてくれました。 –

+0

お二人ともお世話になりました.--) –

3

メソッドでは、How to Use Iconsで説明したように、プログラムのJARファイル内にイメージが存在することが予想されます。イメージをプロジェクトに移動する必要があります。 IconDemoは完全な例です。

+0

これは私が前にやっていたやり方で、働いていた。しかし、私は新しい画像を追加することができません。私はどのように私はそのフォルダから読み取るために新しい画像を追加することができますので、瓶の外の特定のフォルダから読み取ることができます。 –

+0

[_file URI_](http://en.wikipedia.org/wiki/File_URI_scheme#Windows)または 'new ImageIcon(path)'を試すことができます。 – trashgod

0

:-)結果を参照してくださいツアーの場合は、ラベルのHTMLタグが必要です。 < img src = filepth \ imagefile.jpg> :これを置き換えるには、これを使用できます。笑顔のアイコンで。

0
 /* 

Create an Image File whose size is 700 x 472 (pixels) in any image editor. 
Here Image was created using MS - Paint. 

Make sure that the Image File and the main file are in the same folder. 

The size of the JFrame should be set to 700 x 472 (pixels) in the program. 


Set the JLabel's IconImage. 

Add the JLabel to the JFrame. 

Set JFrame properties. 

Display JFrame. 

------------------------------------------------------------------------------ 

label.setIcon(getClass().getResources(String name)); 

label.setIcon(new ImageIcon(String file)); 


These 2 methods, don't always work with us. 


So, we create a method "getImageIcon(File f)" that returns a new ImageIcon Object, 
everytime a new File Object is passed to it. 


*/ 




import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JButton; 


import java.awt.Image; 
import javax.imageio.ImageIO; 
import java.io.File; 
import java.io.IOException; 


import javax.swing.ImageIcon; 

import static javax.swing.WindowConstants.*; 






public class ImageDemo 
{ 

    JFrame frame = new JFrame();  //initialized 


    JLabel label = new JLabel();  //initialized 


    JButton button = new JButton(); //initialized 


    ImageIcon ii;    //not initialized 





    public void displayImage() 
    { 

     //Layout Type: Null Layout. 

     label.setIcon(getImageIcon(new File("print.png"))); 


     button.setBounds(150,150,358,66); 
     //Note that sizes of the Image and Button are same. 
     button.setIcon(getImageIcon(new File("Button.png"))); 



     label.add(button); 
     //add the button to the label 


     frame.add(label); 
     frame.setBounds(300, 50, 700, 472); 
     //(300 x 50 = HorizontalAlignment x VerticalAlignment) 
     //(700 x 472 = Width x Height)  

     frame.setTitle("Image Demo"); 
     frame.setDefaultCloseOperation(EXIT_ON_CLOSE); //WindowConstants.EXIT_ON_CLOSE 
     frame.setVisible(true); 


    } 





    public ImageIcon getImageIcon(File f) 
    { 


     try 
     { 
      Image im = ImageIO.read(f); 


      ii = new ImageIcon(im); 


     } 
     catch(IOException i) 
     { 

      i.printStackTrace(); 


     } 



     finally 
     { 

      return ii; 

     } 


    } 



    public static void main(String[] args) 
    { 

     ImageDemo id = new ImageDemo(); 

     id.displayImage(); 


    } 





} 
関連する問題