ImageIcons

Hello, I have a question regarding the following code. I have excluded the irrelevant parts and only left the code that there is a problem with.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
public class HandType extends JFrame implements ActionListener
  static String hookString = "Hooked Hand";                                                                                         
  static String normalString = "Regular Hand";                                                                                                                                                                                 
  JRadioButton radioHook;                                                                                                      
  JRadioButton radioNormal;                                                                                                        
    public HandType()  
    setSize(750, 300);                                                                                                              
    setTitle("Hand Dominance: CP Dehli 2010");                                                                                    
    Container contentPane = getContentPane();                                                                                           contentPane.setLayout(new BorderLayout());                                                                                     
    JPanel handPanel = new JPanel();                                                                                                
    handPanel.setBackground(Color.WHITE);                                                                                           
    handPanel.setLayout(new FlowLayout());                                                                                            
    ImageIcon hookButtonIcon = createImageIcon("/Users/CP/Desktop/Java/Project File/Pictures/HookWriting.JPG");    
    ImageIcon normButtonIcon = createImageIcon("/Users/CP/Desktop/Java/Project File/Picture/NormalWriting.JPG"); 
    radioHook = new JRadioButton(hookString, hookButtonIcon);                                                             
    handPanel.add(radioHook);                                                                                                
    radioNormal = new JRadioButton(normalString, normButtonIcon);                                                                    
    handPanel.add(radioNormal);                                                                                             
    ButtonGroup buttonGroup = new ButtonGroup();                                                                   
    buttonGroup.add(radioHook);                                                                                       
    buttonGroup.add(radioNormal);  
}           Now when I press Compile I get the two following errors.
2 errors found:
File: /Users/CP/Desktop/Java Project File/HandType.java [line: 32]
Error: cannot find symbol
symbol : method createImageIcon(java.lang.String)
location: class HandType
File: /Users/CP/Desktop/Java Project File/HandType.java [line: 33]
Error: cannot find symbol
symbol : method createImageIcon(java.lang.String)
location: class HandType
This is my second thread here and I am very grateful for all the help I received in my first thread. As I said earlier I am a beginner, and any help and/or criticism will be greatly appreciated. Thanks!

I changed my code to the following and now there are no compiling errors. However when I run the main method and when the radio buttons should show up with an image they do not. Instead only words show up with the actual button and images not being shown. This is the Screenshot of what I get. As always help will always be greatly appreciated!
ImageIcon hookButtonIcon = new ImageIcon("/Users/CP/Desktop/Java/Project File/Pictures/HookWriting.JPG", "A hooked hand");   
ImageIcon normButtonIcon = new ImageIcon("/Users/CP/Desktop/Java/Project File/Picture/NormalWriting.JPG", "A normal hand");

Similar Messages

  • Resized animated gif ImageIcon not working properly with JButton etc.

    The problem is that when I resize an ImageIcon representing an animated gif and place it on a Jbutton, JToggelButton or JLabel, in some cases the image does not show or does not animate. More precicely, depending on the specific image file, the image shows always, most of the time or sometimes. Images which are susceptible to not showing often do not animate when showing. Moving over or clicking with the mouse on the AbstractButton instance while the frame is supposed to updated causes the image to disappear (even when viewing the non-animating image that sometimes appears). No errors are thrown.
    Here some example code: (compiled with Java 6.0 compliance)
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Test
         public static void main(String[] args)
              new Test();
         static final int  IMAGES        = 3;
         JButton[]           buttons       = new JButton[IMAGES];
         JButton             toggleButton  = new JButton("Toggle scaling");
         boolean            doScale       = true;
         public Test()
              JFrame f = new JFrame();
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              JPanel p = new JPanel(new GridLayout(1, IMAGES));
              for (int i = 0; i < IMAGES; i++)
                   p.add(this.buttons[i] = new JButton());
              f.add(p, BorderLayout.CENTER);
              f.add(this.toggleButton, BorderLayout.SOUTH);
              this.toggleButton.addActionListener(new ActionListener() {
                   @Override
                   public void actionPerformed(ActionEvent e)
                        Test.this.refresh();
              f.setSize(600, 300);
              f.setVisible(true);
              this.refresh();
         public void refresh()
              this.doScale = !this.doScale;
              for (int i = 0; i < IMAGES; i++)
                   ImageIcon image = new ImageIcon(i + ".gif");
                   if (this.doScale)
                        image = new ImageIcon(image.getImage().getScaledInstance(180, 180, Image.SCALE_AREA_AVERAGING));
                   image.setImageObserver(this.buttons);
                   this.buttons[i].setIcon(image);
                   this.buttons[i].setSelectedIcon(image);
                   this.buttons[i].setDisabledIcon(image);
                   this.buttons[i].setDisabledSelectedIcon(image);
                   this.buttons[i].setRolloverIcon(image);
                   this.buttons[i].setRolloverSelectedIcon(image);
                   this.buttons[i].setPressedIcon(image);
    Download the gif images here:
    http://djmadz.com/zombie/0.gif
    http://djmadz.com/zombie/1.gif
    http://djmadz.com/zombie/2.gif
    When you press the "Toggle scaling"button it switches between unresized (properly working) and resized instances of three of my gif images. Notice that the left image almost never appears, the middle image always, and the right image most of the time. The right image seems to (almost) never animate. When you click on the left image (when visble) it disappears only when the backend is updating the animation (between those two frames with a long delay)
    Why are the original ImageIcon and the resized ImageIcon behaving differently? Are they differently organized internally?
    Is there any chance my way of resizing might be wrong?

    It does work, however I refuse to use SCALE_REPLICATE for my application because resizing images is butt ugly, whether scaling up or down. Could there be a clue in the rescaling implementations, which I can override?
    Maybe is there a way that I can check if an image is a multi-frame animation and set the scaling algorithm accordingly?
    Message was edited by:
    Zom-B

  • Can not display ImageIcon in a JLabel where you want in the code ???

    Hello, everybody. I need your help to solve a problem I am on it for 2 days now :
    In the constructor of my class, I have a lot of initializing methods. If I try to display an image (with ImageIcon in a JLabel) within one of these methods, there is no problem and the image is correctely displayed. To try that, I use an image stored on my local disk in "c:\\".
    public class Bedes extends javax.swing.JFrame {
    public Bedes() {
    initComponents();
    -- further initializations
    initConnection();
    public void initConnection() {
    try {
    String driverName = "sun.jdbc.odbc.JdbcOdbcDriver";
    Properties systemProperties = System.getProperties();
    systemProperties.put("jdbc.drivers", driverName);
    System.setProperties(systemProperties);
    String dbURL = "jdbc:odbc:Bandes Dessin�es";
    String strUtilisateur = "bedes";
    String strMotDePasse = "cdle";
    connectBedes = DriverManager.getConnection(dbURL,strUtilisateur,strMotDePasse);
    catch (Exception e) {
    System.out.println("Exception in DB Contact " + e);
    // Here, I display an image in my JLabel, and it works :
    couvertureAlbumString = "c:\\myImage.jpg";
    couvertureAlbumsIcon = new ImageIcon(couvertureAlbumString);
    couvertureAlbumsJLabel.setIcon(couvertureAlbumsIcon);
    couvertureAlbumsJLabel.repaint();
    }The problem is that I do not want to display these images there, but in a method that read some data's in a Database (with "try"-"catch" blocks). If there is a name of an image store in the DB, then it must be displayed in the JLabel (located in a JFrame -> JDeskTopPane -> JTabbedPane -> JPanel).
    private void searchDetailsForAlbum(String albumsDetailsToSearch) {
    String nomImageCouverture;
    String couvertureAlbumString;
    ImageIcon couvertureAlbumsIcon;
    try {
    PreparedStatement requeteDetailsAlbums = connectBedes.prepareStatement("SELECT * FROM bandes_dess WHERE bede_nom_tome = ?");
    requeteDetailsAlbums.setString(1, albumsDetailsToSearch);
    ResultSet resultatDetailsAlbums = requeteDetailsAlbums.executeQuery();
    resultatDetailsAlbums.next();
    collectionAlbumsJTextField.setText(resultatDetailsAlbums.getString(6));
    genreAlbumsJTextField.setText(resultatDetailsAlbums.getString(9));
    dessinateurAlbumsJTextField.setText(resultatDetailsAlbums.getString(10));
    scenaristeAlbumsJTextField.setText(resultatDetailsAlbums.getString(11));
    coloristeAlbumsJTextField.setText(resultatDetailsAlbums.getString(12));
    prixAchatAlbumsJTextField.setText(resultatDetailsAlbums.getString(13));
    // Here is the name of the Image to de read
    nomImageCouverture = resultatDetailsAlbums.getString(14);
    catch (Exception e) {
    System.out.println("Exception in searchDetailsForAlbum" + e);
    couvertureAlbumString = "c:\\";
    // Here, I check if there is a name for a picture in the DB
    if (!(nomImageCouverture.equals("No"))) {
    // If Yes, I want to display it
    couvertureAlbumString = couvertureAlbumString + nomImageCouverture;
    couvertureAlbumsIcon = new ImageIcon(couvertureAlbumString);
    couvertureAlbumsJLabel.setIcon(couvertureAlbumsIcon);
    couvertureAlbumsJLabel.repaint();
    }My JLabel is well displayed, but empty, without any image on it. WHY ???
    MLK, you asked me to add some debug code. OK, with pleasure, but what is that "debug code" ???
    Thanks a lot in advance if you could help me.
    Christian.

    DEBUG: couvertureAlbumString: c:\Aldebaran-La-Photo
    OK, the extension of the file was NOT present !!!
    I added it and ..... it works pretty good !!!
    Thank you for your idea of the DEBUG.
    Christian.

  • Using ImageIcon load an image

    Hi I'm having a lot of trouble getting the below code to work. Its copied out of my textbook and its supposed to load an image using the getImage method in the ImageIcon class. The strange thing is I have gotten this to work before, but after I installed Windows 2000 the image doesn't seem to load right anymore.
    getWidth and getHeight - on the image afterwards returns -1.
    Could this be windows 2000's problem? I'm pretty sure it isn't .. but when you run out of ideas, it feels good to put the blame on something other than yourself.
    import java.awt.*;
    import javax.swing.*;
    import java.net.*;
    public class DisplayImage extends JApplet
    public void init()
    ImageIcon icon = null;
    try
    icon = new ImageIcon(new URL(getCodeBase(), "Images/backTile.bmp"));
    catch(MalformedURLException e)
    System.out.println("Failed to create URL:\n"+e);
    return;
    int imageWidth = icon.getIconWidth();
    int imageHeight = icon.getIconHeight();
    resize(imageWidth, imageHeight);
    ImagePanel imagePanel = new ImagePanel(icon.getImage());
    getContentPane().add(imagePanel);
    class ImagePanel extends JPanel
    public ImagePanel(Image image)
    this.image = image;
    public void paint(Graphics g)
    g.drawImage(image,0,0,this);
    Image image;
    Again thx a lot. I know its a lot of code to read. Any help at all would be much appreciated.

    ".bmp" ? Windows bitmap isn't a supported file type, you should save your image as .gif, .png, or as .jpg.

  • Problem with JFileChooser and ImageIcon

    I'm trying to create an ImageIcon object from file selected in JFileChooser. The problem is that jfc.getSelectedFile().getAbsolutePath() returns a string with backslashes and the constructor of ImageIcon requires the string to have slashes. I`ve tried to create it via URL but it doesn't work as well...
    String lastUsedPath;
    URL imageURL;
    JFileChooser fc = new JFileChooser();
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    int returnVal = fc.showDialog(frame,title);
    if(returnVal==JFileChooser.APPROVE_OPTION){                    
         lastUsedPath = fc.getSelectedFile().getAbsolutePath();
         imageURL = getClass().getResource(lastUsedPath);     //don't really get this but I copied it from Java Swing Tutorial          
    }else{
         return null;
    int curH, curW;            
    ImageIcon srcIcon = new ImageIcon(imageURL);                              
    curW = srcIcon.getIconWidth();
    curH = srcIcon.getIconHeight();If I use it this way imageURL is set to null.
    If I set the imageURL as 'fc.getSelectedFile().toURL()' the string is eg.: "file:/E:/file.jpg" instead of "E:/file.jpg". After that the ImageIcon is created but width and height return -1.
    If I try to create ImageIcon by 'new ImageIcon(lastUsedPath)' I get a not null object but the width & height of the ImageIcon is -1 as well.
    What do I have to do to be able to create an ImageIcon from file selected in JFileChooser? Why is this so hard and mind blowing?

    It still returns the ImageIcon object with width & height set to -1.
    EDIT:
    Got it finally:
    lastUsedPathForStupidImageIcon = fc.getSelectedFile().getPath();     
    img = ImageIO.read(new File(lastUsedPathForStupidImageIcon));
    curH = img.getHeight(this);
    curW = img.getWidth(this);The key was to use another String variable and hold the path instead of the absolute path
    Edited by: Beholder on Jan 17, 2010 1:35 PM

  • Bug: IconUIResource doesn't paint an animated ImageIcon

    I was recently playing with Icons and found that javax.swing.plaf.IconUIResource doesn't paint an ImageIcon that contains an animated GIF. Found the reason in these bug fixes.
    [http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4215118]
    [http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4215118]
    From that, I could arrive at a workaround: extend ImageIcon to implement the UIResource marker interface and use this class instead of wrapping an ImageIcon in a IconUIResource. Interestingly, NetBeans autocomplete revealed the existance of sun.swing.ImageIconUIResource which I determined to be a direct subclass of ImageIcon, with two constructors that take an Image and byte[] respectively.
    Test SSCCE: import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.MalformedURLException;
    import java.net.URL;
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
    import javax.swing.JOptionPane;
    import javax.swing.UIManager;
    import javax.swing.plaf.IconUIResource;
    import javax.swing.plaf.UIResource;
    public class IconUIResourceBug {
      public static void main(String[] args) {
        try {
          URL imageURL = new URL("http://www.smiley-faces.org/smiley-faces/smiley-face-rabbit.gif");
          InputStream is = imageURL.openStream();
          ByteArrayOutputStream baos = new ByteArrayOutputStream();
          int n;
          byte[] data = new byte[1024];
          while ((n = is.read(data, 0, data.length)) != -1) {
            baos.write(data, 0, n);
          baos.flush();
          byte[] bytes = baos.toByteArray();
          ImageIcon imageIcon = new ImageIcon(bytes);
          Icon icon = new IconUIResource(imageIcon);
          UIManager.put("OptionPane.errorIcon", icon);
          JOptionPane.showMessageDialog(null, "javax.swing.plaf.IconUIResource", "Icon not shown",
                  JOptionPane.ERROR_MESSAGE);
          icon = new ImageIconUIResource(bytes);
          UIManager.put("OptionPane.errorIcon", icon);
          JOptionPane.showMessageDialog(null, "ImageIconUIResource", "Icon shown",
                  JOptionPane.ERROR_MESSAGE);
          icon = new sun.swing.ImageIconUIResource(bytes);
          UIManager.put("OptionPane.errorIcon", icon);
          JOptionPane.showMessageDialog(null, "sun.swing.ImageIconUIResource", "Icon shown",
                  JOptionPane.ERROR_MESSAGE);
        } catch (MalformedURLException ex) {
          ex.printStackTrace();
        } catch (IOException ex) {
          ex.printStackTrace();
    class ImageIconUIResource extends ImageIcon implements UIResource {
      public ImageIconUIResource(byte[] bytes) {
        super(bytes);
    }I can't see any alternative fix for the one carried out in response to the quoted bug reports, so have held off on making a bug report. Any ideas?
    Thanks for reading, Darryl
    I'm also posting this to JavaRanch for wider discussion, and shall post the link here as soon as possible. I'll also keep both threads updated with all significant suggestions received.
    edit [http://www.coderanch.com/t/498351/GUI/java/Bug-IconUIResource-doesn-paint-animated]
    Edited by: DarrylBurke

    Animated gif is working fine for me.
    You can check the delay time between the images in the gif, to see that it's not too short.
    Here's a simple example:import java.net.URL;
    import javax.imageio.ImageIO;
    import javax.imageio.stream.ImageInputStream;
    import javax.swing.ImageIcon;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import com.sun.imageio.plugins.gif.GIFImageMetadata;
    import com.sun.imageio.plugins.gif.GIFImageReader;
    public class AnimatedGifTest {
        public static void main(String[] args) {
            try {
                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JDialog.EXIT_ON_CLOSE);
                URL url = new URL("http://www.gifanimations.com/action/SaveImage?path=/Image/Animations/Cartoons/~TS1176984655857/Bart_Simpson_2.gif");
                frame.add(new JLabel(new ImageIcon(url)));
                frame.pack();
                frame.setVisible(true);
                // Read the delay time for the first frame in the animated gif
                GIFImageReader reader = (GIFImageReader) ImageIO.getImageReadersByFormatName("GIF").next();
                ImageInputStream iis = ImageIO.createImageInputStream(url.openStream());
                reader.setInput(iis);
                GIFImageMetadata md = (GIFImageMetadata) reader.getImageMetadata(0);           
                System.out.println("Time Delay = " + md.delayTime);
                reader.dispose();
                iis.close();
            } catch (Exception e) {e.printStackTrace();}
    }

  • Help with ImageIcon

    Hi,
    I'm giving Java another try and I'm working through the short courses and Magercises. I'm having a problem with the code below.
    <pre>
    package examples.myapps.test;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class FirstSwing extends JFrame {
    // The initial width and height of the frame
    public static int WIDTH = 300;
    public static int HEIGHT = 300;
    // images for buttons
    public Icon bee = new ImageIcon("bee.gif");
    public Icon dog = new ImageIcon("dog.gif");
    public FirstSwing(String lab) {
    super(lab);
    JButton top = new JButton("A bee", bee);
    top.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    System.out.println("bee");
    JButton bottom = new JButton("and a dog", dog);
    bottom.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    System.out.println("dog");
    top.setMnemonic (KeyEvent.VK_B);
    bottom.setMnemonic (KeyEvent.VK_D);
    Container content = getContentPane();
    content.setLayout(new GridLayout(2,1));
    content.add(top);
    content.add(bottom);
    public static void main(String args[]) {
    FirstSwing frame = new FirstSwing("First Swing Stuff");
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {System.exit(0);}
    frame.setSize(WIDTH, HEIGHT);
    frame.setVisible(true);
    </pre>
    The problem is that the icons don't appear. The image files (bee.gif and dog.gif) are in the same directory as the source file. I get no errors, the images just do not appear in the button like they are supposed to according to the example. What am I doing wrong?
    Thanks,
    Mike

    I had the same problem with ONE STUDIO 4 trying the example below ... the image is in the same directory as the class is and it�s ok ... it only work fine if I set the full absolute path, but not with a relative one ....
    But I tryed the same example in the same dir with Jbuider 3 ... and it works fine and the ImageIcon appears .... I think it�s something related to Filesystems in the Studio One ....
    Jo�o Carlos
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class LabelTest extends JFrame {
    private JLabel label1, label2, label3;
    public LabelTest()
    super( "Testing JLabel" );
    Container c = getContentPane();
    c.setLayout( new GridLayout(3,1) );
    // JLabel constructor with a string argument
    label1 = new JLabel( "Label with text" );
    label1.setToolTipText( "This is label1" );
    c.add( label1 );
    // JLabel constructor with string, Icon and
    // alignment arguments
    //Icon bug = new ImageIcon( "C:\\Documents and Settings\\Administrador\\examples\\ch12\\fig12_04\\bug1.GIF" );
    Icon bug = new ImageIcon( "bug1.GIF" );
    label2 = new JLabel( "Label with text and icon",
    bug, SwingConstants.LEFT );
    label2.setToolTipText( "This is label2" );
    c.add( label2 );
    // JLabel constructor no arguments
    label3 = new JLabel();
    label3.setText( "Label with icon and text at bottom" );
    label3.setIcon( bug );
    label3.setHorizontalTextPosition(
    SwingConstants.CENTER );
    label3.setVerticalTextPosition(
    SwingConstants.BOTTOM );
    label3.setToolTipText( "This is label3" );
    c.add( label3 );
    setSize( 275, 170 );
    show();
    public static void main( String args[] )
    LabelTest app = new LabelTest();
    app.addWindowListener(
    new WindowAdapter() {
    public void windowClosing( WindowEvent e )
    System.exit( 0 );
    if your source is in
    C:\foo\examples\myapps\test
    put the gifs in
    C:\fooThanks, but this isn't working either. My source is
    in:
    c:\java-ide\sampledir\examples\myapps\test.
    I've placed the gifs in c:\java-ide,
    c:\java-ide\sampledir, c:\java-ide\sampledir\examples,
    etc. (all directories) and nothing shows the gifs in
    the buttons. Any ideas?

  • Japplet with imageicon

    Hi, im working on a simple paint program in a Japplet. I'm stuck right now on getting an icon on a button by giving the ImageIcon constructor a file path. I get an error when I try to run the applet with the imaging code in, not without.
    I've read in a few places that this won't work for general applets or jar files. Is there anyway that i can get it to load from my computer without resorting to having to load the .gif files from a internet site?
    // i have this (which doesn't work)
          JButton draw = new JButton(new ImageIcon("images/0.gif"));
          draw.addActionListener(canvas);
          toolsPanel.add(draw);
    //as compared to this (which does without an image)
          JButton line = new JButton("Line");        
          line.addActionListener(canvas);            
          toolsPanel.add(line);

    JButton draw = new JButton(new ImageIcon(new java.net.URL(getCodeBase(),"images/0.gif")));

  • Imageicon in a JComboBox

    hi, i do a program to create "business case table", but i've a problem in the 2nd part of the table, because in my 2nd table i have a JComboBox with image, when i click the combobox the images are show, but when select some figure the cell don�t keep the image, only keep the text.
    Anyone can help me???
    Here is my principal class that create the principal screen and tables:
    /*                      Poseidon                                 */
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    import javax.swing.table.*;
    * Summary description for Poseidon
    *2052102
    public class Poseidon extends JFrame
         // Variables declaration
         private JTabbedPane jTabbedPane1;
         private JPanel contentPane, paineltabela, painelgrafo, painelvariavel, paineltarefa;
         private JTable tabelavariavel,tabelatarefa, tabelateste;
         private JScrollPane scrollvariavel, scrolltarefa;
         private int totallinhas, alt, al, linhastarefa,cont, linhas, tamanholinhas,
                        controlalinhas, index, contastring;
         private String variavel;
         private JComboBox combobox;
         JMenuItem sair, abrir, guardar, miadtarefa, miadvariavel;
         JTable [] tabelasvar = new JTable[30];
         JFrame w;
         // End of variables declaration
         public Poseidon()
              super("Poseidon");
              initializeComponent();
              this.setVisible(true);
          * This method is called from within the constructor to initialize the form.
          * WARNING: Do NOT modify this code. The content of this method is always regenerated
          * by the Windows Form Designer. Otherwise, retrieving design might not work properly.
          * Tip: If you must revise this method, please backup this GUI file for JFrameBuilder
          * to retrieve your design properly in future, before revising this method.
         private void initializeComponent()
              JMenuBar barra = new JMenuBar();
              setJMenuBar(barra);
              TratBarra trat = new TratBarra();
              tabelavariavel = new JTable();
              tabelatarefa = new JTable();
              tabelavariavel.getTableHeader().setReorderingAllowed(false);
              tabelavariavel.setModel(new DefaultTableModel());
              tabelavariavel.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
              tabelavariavel.setBackground(Color.cyan);
              tabelatarefa.getTableHeader().setReorderingAllowed(false);
              tabelatarefa.setModel(new DefaultTableModel());
              tabelatarefa.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
              tabelatarefa.setBackground(Color.white);
              CaixaCombinacao combobox = new CaixaCombinacao();
              DefaultCellEditor editor = new DefaultCellEditor(combobox);
              tabelatarefa.setDefaultEditor(Object.class, editor);
              painelvariavel = new JPanel();
              painelvariavel.setLayout(new GridLayout(1, 0));
              painelvariavel.setBorder(new TitledBorder("Variaveis"));
              painelvariavel.setBounds(15, 35, 490, 650);
              painelvariavel.setVisible(false);
              this.add(painelvariavel);
              scrollvariavel = new JScrollPane();
              scrollvariavel.setViewportView(tabelavariavel);
              painelvariavel.add(scrollvariavel);
              paineltarefa = new JPanel();
              paineltarefa.setLayout(new GridLayout(1,0));
              paineltarefa.setBorder(new TitledBorder("Tarefas"));
              paineltarefa.setBounds(506, 35, 490,650);
              paineltarefa.setVisible(false);
              this.add(paineltarefa);
              scrolltarefa = new JScrollPane();
              scrolltarefa.setViewportView(tabelatarefa);
              paineltarefa.add(scrolltarefa);
              tamanholinhas = 1;
              linhas=1;
              cont=0;
              JMenu arquivo = new JMenu("Arquivo");
              JMenu mtabela = new JMenu("Tabela");
              arquivo.setMnemonic(KeyEvent.VK_A);
              mtabela.setMnemonic(KeyEvent.VK_T);
              miadvariavel = new JMenuItem("Adicionar Variavel");
              miadtarefa = new JMenuItem("Adicionar Tarefa");
              abrir = new JMenuItem("Abrir");
              guardar = new JMenuItem("Guardar");
              sair = new JMenuItem("Sair");
              sair.addActionListener(trat);
              miadvariavel.addActionListener(trat);
              miadtarefa.addActionListener(trat);
              mtabela.add(miadvariavel);
              miadvariavel.setMnemonic(KeyEvent.VK_V);
              mtabela.add(miadtarefa);
              miadtarefa.setMnemonic(KeyEvent.VK_F);
              arquivo.add(abrir);
              abrir.setMnemonic(KeyEvent.VK_B);
              arquivo.add(guardar);
              guardar.setMnemonic(KeyEvent.VK_G);
              arquivo.addSeparator();
              arquivo.add(sair);
              sair.setMnemonic(KeyEvent.VK_S);
              barra.add(arquivo);
              barra.add(mtabela);
              jTabbedPane1 = new JTabbedPane();
              contentPane = (JPanel)this.getContentPane();
              paineltabela = new JPanel();
              painelgrafo = new JPanel();
              // jTabbedPane1
              jTabbedPane1.addTab("Tabela", paineltabela);
              jTabbedPane1.addTab("Grafo", painelgrafo);
              jTabbedPane1.addChangeListener(new ChangeListener() {
                   public void stateChanged(ChangeEvent e)
                        painelvariavel.setVisible(false);
              // contentPane
              contentPane.setLayout(null);
              addComponent(contentPane, jTabbedPane1, 11,10,990,690);
              // paineltabela
              paineltabela.setLayout(null);
              // painelgrafo
              painelgrafo.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
              // Poseidon
              this.setTitle("UMa Poseidon");
              this.setLocation(new Point(2, 1));
              this.setSize(new Dimension(558, 441));
              this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
              this.setExtendedState(MAXIMIZED_BOTH);
         /** Add Component Without a Layout Manager (Absolute Positioning) */
         private void addComponent(Container container,Component c,int x,int y,int width,int height)
              c.setBounds(x,y,width,height);
              container.add(c);
         // TODO: Add any appropriate code in the following Event Handling Methods
         private void jTabbedPane1_stateChanged(ChangeEvent e)
              System.out.println("\njTabbedPane1_stateChanged(ChangeEvent e) called.");
              // TODO: Add any handling code here
         // TODO: Add any method code to meet your needs in the following area
         private class TratBarra implements ActionListener{
              public void actionPerformed(ActionEvent e){
                   if(e.getSource() == sair){
                        int op = JOptionPane.showConfirmDialog(null, "Deseja mesmo fechar o aplicativo?","Sair", JOptionPane.YES_NO_OPTION);
                        if(op == JOptionPane.YES_OPTION){
                             System.exit(0);
                   if(e.getSource() == miadvariavel){
                        final JFrame w = new JFrame();
                        new AdVariavel(w);
                   if(e.getSource() == miadtarefa){
                        final JFrame w = new JFrame();
                        new AdTarefa(w);
    //============================= Testing ================================//
    //=                                                                    =//
    //= The following main method is just for testing this class you built.=//
    //= After testing,you may simply delete it.                            =//
    //======================================================================//
         public static void main(String[] args)
              Spash sp = new Spash(3000);
              sp.mostraTela();
              JFrame.setDefaultLookAndFeelDecorated(true);
              JDialog.setDefaultLookAndFeelDecorated(true);
              try
                   UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
              catch (Exception ex)
                   System.out.println("Failed loading L&F: ");
                   System.out.println(ex);
              new Poseidon();
    //= End of Testing =
    private class AdVariavel extends JDialog
         // Variables declaration
         private JLabel jLabel1;
         private JTextField jTextField1;
         private JButton varOK;
         private JButton varCancel;
         private JPanel contentPane;
         private JTextField jTextField2;
         private JList listadominio;
         private JScrollPane jScrollPane1;
         private JButton varAdiciona;
         private JButton varRemove;
         private JPanel jPanel1;
         private DefaultListModel modelo1;
         // End of variables declaration
         public AdVariavel(Frame w)
              super(w);
              initializeComponent();
              // TODO: Add any constructor code after initializeComponent call
              this.setVisible(true);
          * This method is called from within the constructor to initialize the form.
          * WARNING: Do NOT modify this code. The content of this method is always regenerated
          * by the Windows Form Designer. Otherwise, retrieving design might not work properly.
          * Tip: If you must revise this method, please backup this GUI file for JFrameBuilder
          * to retrieve your design properly in future, before revising this method.
         private void initializeComponent()
              modelo1 = new DefaultListModel();
              jLabel1 = new JLabel();
              jTextField1 = new JTextField();
              varOK = new JButton();
              varCancel = new JButton();
              contentPane = (JPanel)this.getContentPane();
              jTextField2 = new JTextField();
              listadominio = new JList(modelo1);
              jScrollPane1 = new JScrollPane();
              varAdiciona = new JButton();
              varRemove = new JButton();
              jPanel1 = new JPanel();
              // jLabel1
              jLabel1.setText("Nome da vari�vel:");
              // jTextField1
              jTextField1.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        jTextField1_actionPerformed(e);
              // varOK
              varOK.setText("OK");
              varOK.setMnemonic(KeyEvent.VK_O);
              varOK.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        varOK_actionPerformed(e);
              // varCancel
              varCancel.setText("Cancelar");
              varCancel.setMnemonic(KeyEvent.VK_C);
              varCancel.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        varCancel_actionPerformed(e);
              // contentPane
              contentPane.setLayout(null);
              addComponent(contentPane, jLabel1, 12,12,105,18);
              addComponent(contentPane, jTextField1, 118,10,137,22);
              addComponent(contentPane, varOK, 170,227,83,28);
              addComponent(contentPane, varCancel, 257,227,85,28);
              addComponent(contentPane, jPanel1, 12,42,332,180);
              // jTextField2
              jTextField2.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        jTextField2_actionPerformed(e);
              // listadominio
              listadominio.addListSelectionListener(new ListSelectionListener() {
                   public void valueChanged(ListSelectionEvent e)
                        listadominio_valueChanged(e);
              // jScrollPane1
              jScrollPane1.setViewportView(listadominio);
              // varAdiciona
              varAdiciona.setText("Adicionar");
              varAdiciona.setMnemonic(KeyEvent.VK_A);
              varAdiciona.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        varAdiciona_actionPerformed(e);
              // varRemove
              varRemove.setText("Remover");
              varRemove.setMnemonic(KeyEvent.VK_R);
              varRemove.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        varRemove_actionPerformed(e);
              // jPanel1
              jPanel1.setLayout(null);
              jPanel1.setBorder(new TitledBorder("Dominio:"));
              addComponent(jPanel1, jTextField2, 17,22,130,22);
              addComponent(jPanel1, jScrollPane1, 165,21,154,144);
              addComponent(jPanel1, varAdiciona, 56,50,89,28);
              addComponent(jPanel1, varRemove, 57,84,88,28);
              // AdTarefas
              this.setTitle("Adicionar Variavel");
              this.setLocation(new Point(1, 0));
              this.setSize(new Dimension(367, 296));
              this.setLocationRelativeTo(null);
              this.setResizable(false);
         /** Add Component Without a Layout Manager (Absolute Positioning) */
         private void addComponent(Container container,Component c,int x,int y,int width,int height)
              c.setBounds(x,y,width,height);
              container.add(c);
         // TODO: Add any appropriate code in the following Event Handling Methods
         private void jTextField1_actionPerformed(ActionEvent e)
              System.out.println("\njTextField1_actionPerformed(ActionEvent e) called.");
              // TODO: Add any handling code here
         private void varOK_actionPerformed(ActionEvent e)
              System.out.println("\nvarOK_actionPerformed(ActionEvent e) called.");
              if (jTextField1 == null){
                   return;
              if (jTextField1.getText().length()<1){
                   JOptionPane.showMessageDialog(null,"N�o introduziu nenhuma variavel","AVISO", 1 );
                   jTextField1.requestFocus();
                   return;
              else {
                   if (modelo1.getSize() == 0){
                        JOptionPane.showMessageDialog(null,"N�o introduziu nenhum dominio","AVISO", 1 );
                        return;
                   else{
                        painelvariavel.add(scrollvariavel);
                        index = 0;
                        variavel = jTextField1.getText();
                        contastring = variavel.length();
                        System.out.println(contastring);
                        DefaultTableModel dtm = (DefaultTableModel)tabelavariavel.getModel();
                        tabelavariavel.getTableHeader().setBackground(Color.yellow);
                        dtm.addColumn(variavel, new Object[]{});
                        al = modelo1.getSize();
                        totallinhas = al;
                        for(int i = 0;i < modelo1.getSize();i++){
                             listadominio.setSelectedIndex(index) ;
                             Object dominio = listadominio.getSelectedValue();
                             dtm.addRow(new Object[]{dominio});
                             index ++;
                        tabelasvar[cont] = tabelavariavel;
                        cont++;
                        System.out.println(cont);
                        for(int i=0;i<cont;i++){
                             tabelateste = tabelasvar;
                             linhas = tabelateste.getRowCount();
                             if (linhas >= tamanholinhas){
                                  tamanholinhas = linhas;
                        for (int i=0;i<cont;i++){
                             tabelateste = tabelasvar[i];
                             System.out.println(linhas);
                             linhas = tabelateste.getRowCount();
                             tabelateste.setRowHeight((tamanholinhas/linhas)*20);
                             tabelasvar[i] = tabelateste;
                             System.out.println(tabelateste);
                   tabelavariavel = new JTable();
              scrollvariavel = new JScrollPane();
              painelvariavel.add(tabelavariavel);
              tabelavariavel.setBackground(Color.cyan);
         tabelavariavel.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
                   scrollvariavel.setViewportView(tabelavariavel);
                   painelvariavel.setVisible(true);
         tabelavariavel.getTableHeader().setReorderingAllowed(false);
         this.setVisible(false);
         miadtarefa.setEnabled(true);
         miadvariavel.setEnabled(true);
         DefaultTableModel dtm = (DefaultTableModel)tabelatarefa.getModel();
                   tabelatarefa.getTableHeader().setBackground(Color.yellow);
                   controlalinhas = tamanholinhas - linhastarefa;
                   for(int i = 0;i < controlalinhas;i++){
                             dtm.addRow(new Object[]{});
                             linhastarefa++;
                   tabelatarefa.setRowHeight((tamanholinhas/linhas)*20);
              // TODO: Add any handling code here
         private void varCancel_actionPerformed(ActionEvent e)
              System.out.println("\nvarCancel_actionPerformed(ActionEvent e) called.");
              this.setVisible(false);
         private void jTextField2_actionPerformed(ActionEvent e)
              System.out.println("\njTextField2_actionPerformed(ActionEvent e) called.");
              // TODO: Add any handling code here
         private void listadominio_valueChanged(ListSelectionEvent e)
              System.out.println("\nlistadominio_valueChanged(ListSelectionEvent e) called.");
              if(!e.getValueIsAdjusting())
                   Object o = listadominio.getSelectedValue();
                   System.out.println(">>" + ((o==null)? "null" : o.toString()) + " is selected.");
                   // TODO: Add any handling code here for the particular object being selected
         private void varAdiciona_actionPerformed(ActionEvent e)
              System.out.println("\nvarAdiciona_actionPerformed(ActionEvent e) called.");
              if(jTextField2.getText().length()>=1){
                   modelo1.addElement(jTextField2.getText());
                   jTextField2.setText("");
                   jTextField2.requestFocus();
         private void varRemove_actionPerformed(ActionEvent e)
              System.out.println("\nvarRemove_actionPerformed(ActionEvent e) called.");
              int index = listadominio.getSelectedIndex();
              modelo1.remove(index);
         // TODO: Add any method code to meet your needs in the following area
    private class AdTarefa extends JDialog
         // Variables declaration
         private JLabel jLabel1;
         private JTextField jTextField1;
         private JButton tarOK;
         private JButton tarCancel;
         private JPanel contentPane;
         private JPanel jPanel1;
         // End of variables declaration
         public AdTarefa(Frame w)
              super(w);
              initializeComponent();
              // TODO: Add any constructor code after initializeComponent call
              this.setVisible(true);
         * This method is called from within the constructor to initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is always regenerated
         * by the Windows Form Designer. Otherwise, retrieving design might not work properly.
         * Tip: If you must revise this method, please backup this GUI file for JFrameBuilder
         * to retrieve your design properly in future, before revising this method.
         private void initializeComponent()
              jLabel1 = new JLabel();
              jTextField1 = new JTextField();
              tarOK = new JButton();
              tarCancel = new JButton();
              contentPane = (JPanel)this.getContentPane();
              // jLabel1
              jLabel1.setText("Nome da tarefa:");
              // jTextField1
              jTextField1.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        jTextField1_actionPerformed(e);
              // tarOK
              tarOK.setText("OK");
              tarOK.setMnemonic(KeyEvent.VK_O);
              tarOK.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        tarOK_actionPerformed(e);
              // tarCancel
              tarCancel.setText("Cancelar");
              tarCancel.setMnemonic(KeyEvent.VK_C);
              tarCancel.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e)
                        tarCancel_actionPerformed(e);
              // contentPane
              contentPane.setLayout(null);
              addComponent(contentPane, jLabel1, 12,12,105,18);
              addComponent(contentPane, jTextField1, 118,10,120,22);
              addComponent(contentPane, tarOK, 10,50,83,28);
              addComponent(contentPane, tarCancel, 153,50,85,28);
              // AdTarefas
              this.setTitle("Adicionar Tarefa");
              this.setLocation(new Point(1, 0));
              this.setSize(new Dimension(250, 120));
              this.setLocationRelativeTo(null);
              this.setResizable(false);
         /** Add Component Without a Layout Manager (Absolute Positioning) */
         private void addComponent(Container container,Component c,int x,int y,int width,int height)
              c.setBounds(x,y,width,height);
              container.add(c);
         // TODO: Add any appropriate code in the following Event Handling Methods
         private void jTextField1_actionPerformed(ActionEvent e)
              System.out.println("\njTextField1_actionPerformed(ActionEvent e) called.");
              // TODO: Add any handling code here
         private void tarOK_actionPerformed(ActionEvent e)
              System.out.println("\ntarOK_actionPerformed(ActionEvent e) called.");
              if (jTextField1 == null){
                   return;
              if (jTextField1.getText().length()<1){
                   JOptionPane.showMessageDialog(null,"N�o introduziu nenhuma tarefa","AVISO", 1 );
                   jTextField1.requestFocus();
                   return;
              else{
                   String variavel = jTextField1.getText();
                   DefaultTableModel dtm = (DefaultTableModel)tabelatarefa.getModel();
                   dtm.addColumn(variavel,new Object[]{});
                   controlalinhas = tamanholinhas - linhastarefa;
                   for(int i = 0;i < controlalinhas;i++){
                             dtm.addRow(new Object[]{});
                             linhastarefa++;
                   for(int i=0; i < tabelatarefa.getColumnCount(); i++){
                        tabelatarefa.getColumnModel().getColumn(i).setPreferredWidth(100);
                   tabelatarefa.getColumnModel().getColumn(i).setResizable(false);
                   tabelatarefa.getTableHeader().setBackground(Color.yellow);
                   tabelatarefa.setRowHeight((tamanholinhas/linhas)*20);
                   paineltarefa.setVisible(true);
         tabelatarefa.getTableHeader().setReorderingAllowed(true);
         this.setVisible(false);
         miadtarefa.setEnabled(true);
         miadvariavel.setEnabled(true);
         // TODO: Add any handling code here
         private void tarCancel_actionPerformed(ActionEvent e)
              System.out.println("\ntarCancel_actionPerformed(ActionEvent e) called.");
              this.setVisible(false);
    now the code to create the JComboBox is here:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class CaixaCombinacao extends JComboBox{
         ImageIcon[] imagens;
        String[] op = {"x", "check"};
    public CaixaCombinacao(){
         imagens = new ImageIcon[op.length];
        Integer[] intArray = new Integer[op.length];
        for (int i = 0; i < op.length; i++) {
             intArray[i] = new Integer(i);
            imagens[i] = createImageIcon("imagens/" + op[i] + ".gif");
            this.addItem(imagens);
    if (imagens[i] != null) {
    imagens[i].setDescription(op[i]);
         JComboBox lista = new JComboBox(intArray);
         ComboBoxRenderer renderer= new ComboBoxRenderer();
         lista.setRenderer(renderer);
    protected static ImageIcon createImageIcon(String path) {
    java.net.URL imgURL = CaixaCombinacao.class.getResource(path);
    if (imgURL != null) {
         return new ImageIcon(imgURL);
    return null;
    class ComboBoxRenderer extends JLabel
    implements ListCellRenderer {
    public ComboBoxRenderer() {
    setOpaque(true);
    setHorizontalAlignment(CENTER);
    setVerticalAlignment(CENTER);
    public Component getListCellRendererComponent(
    JList list,
    Object value,
    int index,
    boolean isSelected,
    boolean cellHasFocus) {
                   int selectedIndex = ((Integer)value).intValue();
                   if (isSelected) {
    setBackground(list.getSelectionBackground());
    setForeground(list.getSelectionForeground());
    } else {
    setBackground(list.getBackground());
    setForeground(list.getForeground());
                   ImageIcon icon = imagens[selectedIndex];
                   String opc = op[selectedIndex];
    setIcon(icon);
    return this;

    I'm sure 90% of the code posted here has nothing to do with displaying images in a JTable.
    Here is an example that shows how to display an icon in a table:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class TableIcon extends JFrame
         public TableIcon()
              String[] columnNames = {"Picture", "Description"};
              Object[][] data =
                   {new ImageIcon("copy16.gif"), "Copy"},
                   {new ImageIcon("add16.gif"), "Add"},
              DefaultTableModel model = new DefaultTableModel(data, columnNames);
              JTable table = new JTable( model )
                   //  Returning the Class of each column will allow different
                   //  renderers to be used based on Class
                   public Class getColumnClass(int column)
                        return getValueAt(0, column).getClass();
              table.setPreferredScrollableViewportSize(table.getPreferredSize());
              JScrollPane scrollPane = new JScrollPane( table );
              getContentPane().add( scrollPane );
         public static void main(String[] args)
              TableIcon frame = new TableIcon();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setVisible(true);
    }If this doesn't help then post a similiar demo program that shows the problems you are having, not your entire application.

  • JLabel ImageIcon not opaque.

    Hi I am having a little problem with my program that I am trying to develop.
    I have created a JFrame and instead of having the background the usual grey I have used an image.
    I then wanted to create some nice big buttons with nice smooth curved edges but was having trouble using the JButton so decicded to use a JLabel and attach a MouseListener to it. This seems to be working fine at the mo.
    The only problem is that instead of my nice gradient filled background being displayed I get a big white border around the JLabel. The rest of the background is perfectly displayed having only a problem around the JLabel. I have tried not using a background image and it shows the JLabel correctly and the button looks nice and smooth.
    I think it might be something to do with the rendering sequence maybe but I am at a loss. If any one has any ideas on how to fix it or a better way of doing it I would be most grateful.
    Many thanks for your help in advance.
    Matt
    PS now heres my code:
    public class GUI extends JFrame implements MouseListener {
         ImageIcon icon;
         JPanel buttonPanel = new JPanel();
         public GUI(){
              super("Property Works - Estate Agent Management System");
              icon = new ImageIcon("images/bg.jpg");
              JPanel panel = new JPanel(){
                   protected void paintComponent(Graphics g){
                        //g.drawImage(icon.getImage(), 0, 0, null);
                        Dimension d = getSize();
                        //g.drawImage(icon.getImage(), 0, 0, d.width, d.height, null);                    
                        super.paintComponent(g);                    
              panel.setOpaque(false);
              addButton();
              panel.add(buttonPanel);
              getContentPane().add(panel);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              setExtendedState(JFrame.MAXIMIZED_BOTH);
              setVisible(true);
         public void addButton(){
              ImageIcon icon1 = new ImageIcon("images/buttons/addProperty.gif");
              JLabel addProperty = new JLabel(icon1);
              addProperty.setOpaque(false);
              addProperty.setToolTipText("Add a new property");
              addProperty.addMouseListener(this);
              JLabel tester = new JLabel("Tester");
              tester.setOpaque(false);
              buttonPanel.add(addProperty);
              buttonPanel.add(tester);     
         public void mousePressed(MouseEvent arg0) {
              // TODO Auto-generated method stub
              System.out.println("Button Clicked");
    }

    Swing related questions should be posted in the Swing forum.
    Use the "code" tags when you post code so the formatting is retained.
    The code you posted doesn't compile so we can't see the incorrect behaviour.
    Using code I already have I do not see any white border around the image. I tested using a "Duke" image which is found in many of the Swing tutorial examples. Maybe your image is the problem.

  • Need help importing animated gif by ImageIcon in Japplet

    Hello. Im new to Java, but I want to import this animated gif with Java in a Japplet using ImageIcon, but it does not work and I would really appreciate if anyone could help me with this.
    import java.applet.*;                                   
    import java.awt.*;   
    import java.net.*;
         public class Bilder extends Japplet{                               
         public ImageIcon(java.net."http://pixelninja.se/kappawin.gif");
      Image[] bild = new Image[1];                            
      int nr=0;                                                
      public void init(){                                     
        setBackground(Color.black);                         
        bild[0] = getImage(getCodeBase(),"4a.gif");     
      public void paint(Graphics g){
        g.drawImage(bild[0],50,50,212,282,this);
    }

    You cant do animated gifs this way.
    Also you should remember that you cannot load images in to an applet if it is hosted somewere else than the host that hosts the applet.
    Esiast way to display an image icon with a animated gif will be creating a Image Label and adding it to the applet.
    Ex:-
    public class MyImageApplet extends JApplet{
       public void init(){
          getConentPane().setLayout(new BorderLayout());
           URL imageURL = getClass().getResource("/myImage.gif"); 
          // Above image file should be in the code base or in the archive file of the applet
          getConentPane().add(new JLabel(new ImageIcon(imageURL)));
    }

  • Importing gif file to ImageIcon

    Hi,
    I am trying to use a gif file that I have included in my project (using Windows XP). I am trying to stick the image from the gif file into a ImageIcon variable, and sticking the variable into a label. Here is the code that I am using to have the program access the gif file:
    private ImageIcon redX = new ImageIcon( " \\JAVA programs\\Week 8\\lab8_1a\\redshd.gif " );
    I have a classPath setup in my environment variables/system variables as follows:
    .;C:\Documents and Settings\Jim Roth\My Documents\Visual Studio Projects\Programs
    and the path to the gif file is as follows:
    C:\Documents and Settings\Jim Roth\My Documents\Visual Studio Projects\Programs\JAVA programs\Week 8\Lab8_1A\redshd.gif
    When I run the program, the screen comes up empty. I am using a basic frame, with a GridLayout. When I change the input into the label to a string, it shows up on the label when the program runs.
    In debug mode, I am not quite sure of what the values apply to, but oneonf them shows up as 'null'.
    I think my problem lies with the program just not finding the gif.file. Any suggestions?
    Thanks a lot!
    Jimbo

    OK, here is the program.....it is my very first stab at anything gui. We are supposed to display a tic tac toe grid, and have it randomly put x's and o's (or something simiilar) in a3x3 grid in a random fashion. Here it is:
    import javax.swing.*;
    import java.awt.*;
    import java.util.*;
    public class TicTacToe extends JFrame
    private ImageIcon redX = new ImageIcon("\\JAVA programs\\Week 8\\lab8_1a\\redshd.gif");
    private ImageIcon blueCirc = new ImageIcon("\\JAVA programs\\Week 8\\lab8_1a\\qmark.gif");
    /** Default constructor for TicTacToe */
    public TicTacToe()
    setLayout(new GridLayout(3,3,2,2));//sets grid layout for a 3x3 grid with 2 pixel spacing
    //add 9 JLabels to hold image icons
    for(int i =0; i < 10; ++i)
    add(this.generateJLabel());
    public static void main(String[] args)
    TicTacToe game = new TicTacToe();
    game.setTitle("Tic Tac Toe");
    game.setLocationRelativeTo(null);
    game.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    game.setSize(250, 250);
    game.setVisible(true);
    protected JLabel generateJLabel()
    Random rand = new Random();//instantiate random object to generate ints
    int randNum = rand.nextInt(4);//generate ints between 0 and 4 (exclusive)
    /*The following switch statement looks at random number generated by the Random
    object and assigns an image to a JLabel according to the int returned./
    switch (randNum)
    case 1:
    JLabel temp = new JLabel(this.redX);
    return temp;
    case 2:
    JLabel temp1 = new JLabel(this.blueCirc);
    return temp1;
    default:
    JLabel temp2 = new JLabel();
    return temp2;
    }

  • Error when trying to use ImageIcon

    Hi,
    I am trying to use an ImageIcon to store an icon for plugins so that they can customize their menu and toolbar entries. I use a generic class, PaletteClass, to design all the plugins, and then extend PaletteClass to create individual plugins.
    PaletteClass:
    public class PaletteClass implements ItemListener{
          * PaletteClass
          * Superclass for the palettes in iKalk
          * @author Nathan Jarus
          * @version 0.1
         JFrame frame = new JFrame();//Window
         GridBagLayout layout = new GridBagLayout();
         GridBagConstraints constraints = new GridBagConstraints();
         JPanel main = new JPanel(layout);
         JToggleButton cmdTop = new JToggleButton("Stick to Top");
         //iKalk interface variables
         static String description = "Unnamed Plugin"; //Name of plugin
         ImageIcon icon = new ImageIcon();  //icon of plugin
         static boolean state = true; //is it visible?
         //static JToggleButton button = new JToggleButton(description, icon, state);
         static JToggleButton button;
         //static JToggleButton button = new JToggleButton(description, state);
         JCheckBoxMenuItem menu = new JCheckBoxMenuItem(description, icon, state);
         //boolean caret = false;//Used in determining when to clear the text box
         //boolean clear = false;
         //double tmp = 0;//Used in calculations
         //char op = ' ';//Used in calculations
         //Constructor
         PaletteClass(iKalk ikalk){
              setIcon("/images/generic.gif",ikalk,this);
              menu.addItemListener(this);
              //button.addItemListener(this);
              frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
              //frame.setLayout(new BorderLayout());
              try {
                   UIManager.setLookAndFeel(iKalk.getLF());
              } catch (UnsupportedLookAndFeelException e) {
                   JOptionPane.showMessageDialog(null,"How on earth did you get this message?  Check for a virus.  /n/nYour JRE has changed in the milliseconds that passed between the original loading of the program and this window loading!", "A message you should not be seeing", JOptionPane.ERROR_MESSAGE);
              constraints.fill = GridBagConstraints.BOTH;
              constraints.anchor = GridBagConstraints.CENTER;
              //Stick to Top button
              cmdTop.addItemListener(this);
              addComp(main, cmdTop, layout, constraints, 0, 0, 1, 1, 0, 100);
              //frame.add(main, BorderLayout.NORTH);
              //frame.setVisible(true);
              init();
              //updateGFX();
              //button = new JToggleButton(description, icon, state);
              //setIcon("/images/generic.gif",ikalk,this);
         public void init(){
              frame.setLayout(new BorderLayout());
              frame.add(main, BorderLayout.NORTH);
         //Item listener
         public void itemStateChanged(ItemEvent ie) {
              if(ie.getSource().equals(cmdTop)){
                   if (frame.isAlwaysOnTop()){
                        frame.setAlwaysOnTop(false);
                   else {
                        frame.setAlwaysOnTop(true);
              else if(ie.getSource().equals(button)){
                   if(button.isSelected()){
                        setVisible(true);
                   else{
                        setVisible(false);
              else if(ie.getSource().equals(menu)){
                   if(menu.isSelected()){
                        setVisible(true);
                   else{
                        setVisible(false);
         //Update the L&F
         public void updateGFX(){
              setVisible(false);
              SwingUtilities.updateComponentTreeUI(frame);
              SwingUtilities.updateComponentTreeUI(main);
              setVisible(true);
         //Decide whether or not the window is onscreen
         public boolean isShowing(){
              return frame.isVisible();
         public void setVisible(boolean v){
              frame.setVisible(v);
              state = isShowing();
         public void setVisible(){
              frame.setVisible(true);
              state = isShowing();
         /*Add a component to the gridbag layout
          *Args:
          *JPanel to                                   the JPanel to add the item to
          *Component what                         what to add
          *GridBagLayout layout                    the layout to add it to
          *GridBagConstraints constraints     the constraints to modify
          *int row                                   the row to add it to
          *int column                              the column to add it to
          *int numRows                              the number of rows the item crosses
          *int numCols                              the number of columns the item crosses
          *int weightX                              the x-weight of the item
          *int weightY                              the y-weight of the item
         public void addComp(JPanel to, Component what, GridBagLayout layout, GridBagConstraints constraints, int row, int column, int numRows, int numCols, int weightX, int weightY){
              //Set the constraint parameters
              constraints.gridx = column;
              constraints.gridy = row;
              constraints.gridwidth = numCols;
              constraints.gridheight = numRows;
              constraints.weightx = weightX;
              constraints.weighty = weightY;
              //Set these constraints in the layout
              layout.setConstraints(what, constraints);
              //Add the component
              to.add(what);
         public void setIcon(String path, iKalk ikalk, PaletteClass parent){
              parent.icon = new ImageIcon(ikalk.getClass().getResource(path));
    }This is one of the classes that I have trouble with:
    NumberPad:
    public class NumberPad extends PaletteClass implements ActionListener{
         //Set up the objects so that I can access them from another method
         public NumberPad(iKalk ikalk){
              super(ikalk);
    //Set the description
              description = "Number Pad";
              //setIcon("/images/NumberPad.gif", ikalk, this);
              button = new JToggleButton(description, icon, state);
    //Set up the frame
              try {
                   UIManager.setLookAndFeel(iKalk.getLF());
              } catch (UnsupportedLookAndFeelException e) {
                   //JOptionPane.showMessageDialog(null,"How on earth did you get this message?  Check for a virus.  /n/nYour JRE has changed in the milliseconds that passed between the original loading of the program and this window loading!", "A message you should not be seeing", JOptionPane.ERROR_MESSAGE);
              frame.setSize(155,160);
              frame.setLocation(500,500);
              frame.setTitle(description);
              updateGFX();
    //Set up the number entry pad
              JPanel panNumbers = new JPanel(new GridLayout(4,3));
              JButton cmd0 = new JButton("0");
              JButton cmd1 = new JButton("1");
              JButton cmd2 = new JButton("2");
              JButton cmd3 = new JButton("3");
              JButton cmd4 = new JButton("4");
              JButton cmd5 = new JButton("5");
              JButton cmd6 = new JButton("6");
              JButton cmd7 = new JButton("7");
              JButton cmd8 = new JButton("8");
              JButton cmd9 = new JButton("9");
              JButton cmdDec = new JButton(".");
              JButton cmdPM = new JButton("+/-");
              cmd0.addActionListener(this);
              cmd1.addActionListener(this);
              cmd2.addActionListener(this);
              cmd3.addActionListener(this);
              cmd4.addActionListener(this);
              cmd5.addActionListener(this);
              cmd6.addActionListener(this);
              cmd7.addActionListener(this);
              cmd8.addActionListener(this);
              cmd9.addActionListener(this);
              cmdDec.addActionListener(this);
              cmdPM.addActionListener(this);
              panNumbers.add(cmd7);
              panNumbers.add(cmd8);
              panNumbers.add(cmd9);
              panNumbers.add(cmd4);
              panNumbers.add(cmd5);
              panNumbers.add(cmd6);
              panNumbers.add(cmd1);
              panNumbers.add(cmd2);
              panNumbers.add(cmd3);
              panNumbers.add(cmd0);
              panNumbers.add(cmdDec);
              panNumbers.add(cmdPM);
              panNumbers.setVisible(true);
    //Final adding and init
              super.addComp(main, panNumbers, layout, constraints, 1, 0, 4, 1, 0, 0);
              //super.setVisible();
              setIcon("/images/NumberPad.gif", ikalk, this);
         public void actionPerformed(ActionEvent ae) {
              if(ae.getActionCommand().equals("1")){
                   Functions.addOne();
              else if(ae.getActionCommand().equals("2")){
                   Functions.addTwo();
              else if(ae.getActionCommand().equals("3")){
                   Functions.addThree();
              else if(ae.getActionCommand().equals("4")){
                   Functions.addFour();
              else if(ae.getActionCommand().equals("5")){
                   Functions.addFive();
              else if(ae.getActionCommand().equals("6")){
                   Functions.addSix();
              else if(ae.getActionCommand().equals("7")){
                   Functions.addSeven();
              else if(ae.getActionCommand().equals("8")){
                   Functions.addEight();
              else if(ae.getActionCommand().equals("9")){
                   Functions.addNine();
              else if(ae.getActionCommand().equals("0")){
                   Functions.addZero();
              else if(ae.getActionCommand().equals(".")){
                   Functions.addDec();
              else if(ae.getActionCommand().equals("+/-")){
                   Functions.PlusMins();
         /*public void init(){
         public void main(String [] args){
    }This is the code I use to load the plugins:
    void addPlugin(PaletteClass plugin){
              //pluginsVector.addElement(plugin);
              //plugin.setVisible();
              //toolMain.add(PaletteClass.button);
              pluginsVector.addElement(plugin);
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        toolMain.add(PaletteClass.button);
         }When I load this code, I get the following error (in Eclipse SDK):
    java.lang.reflect.InvocationTargetException
         at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
         at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
         at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
         at java.lang.reflect.Constructor.newInstance(Unknown Source)
         at iKalk.loadPlugin(iKalk.java:587)
         at iKalk.loadPlugins(iKalk.java:578)
         at iKalk.<init>(iKalk.java:466)
         at iKalk$4.run(iKalk.java:563)
         at java.awt.event.InvocationEvent.dispatch(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    Caused by: java.lang.NullPointerException
         at javax.swing.ImageIcon.<init>(Unknown Source)
         at PaletteClass.setIcon(PaletteClass.java:172)
         at NumberPad.<init>(NumberPad.java:82)
         ... 15 more
    If anyone knows what I am doing wrong, I'd like to know. I've tried several ways to fix it (as you can probably tell from the commented out code), but none of them worked.
    Sorry if my code isn't the cleanest; it's still in development =]
    PS: is it just me or does the code button in the post dialog still not work correctly?
    Thanks,
    LinuxMercedes

    Sorry for all the code. Here's a truncated version:
    PaletteClass:
    public class PaletteClass implements ItemListener{
         JFrame frame = new JFrame();//Window
         GridBagLayout layout = new GridBagLayout();
         GridBagConstraints constraints = new GridBagConstraints();
         JPanel main = new JPanel(layout);
         JToggleButton cmdTop = new JToggleButton("Stick to Top");
         static String description = "Unnamed Plugin"; //Name of plugin
         ImageIcon icon = new ImageIcon();  //icon of plugin
         static boolean state = true; //is it visible?
         static JToggleButton button;
         JCheckBoxMenuItem menu = new JCheckBoxMenuItem(description, icon, state);
         PaletteClass(iKalk ikalk){
              setIcon("/images/generic.gif",ikalk,this);
              init();
         public void init(){
              frame.setLayout(new BorderLayout());
              frame.add(main, BorderLayout.NORTH);
         public void setIcon(String path, iKalk ikalk, PaletteClass parent){
              parent.icon = new ImageIcon(ikalk.getClass().getResource(path));
    }NumberPad:
    public class NumberPad extends PaletteClass implements ActionListener{
         public NumberPad(iKalk ikalk){
              super(ikalk);
    //Set the description
              description = "Number Pad";
              button = new JToggleButton(description, icon, state);
              setIcon("/images/NumberPad.gif", ikalk, this);
    }Code I use to load Plugins:
    void addPlugin(PaletteClass plugin){
              pluginsVector.addElement(plugin);
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        toolMain.add(PaletteClass.button);
    }Oh yeah, and please don't go using this code in your projects without asking =]
    Thanks (and my apologies again),
    LinuxMercedes

  • How can I get an ImageIcon back from a JToggleButton...

    When I create a JToggleButton I have to create an ImageIcon and pass it to the constructor.
    e.g. JToggleButton toggleButtonA = new JToggleButton( new ImageIcon( "images/A.gif" ) );
    But when I want to get that ImageIcon back, all I can find in the documentation is getIcon(), which is much more limited in what I can do with it.
    How can I get my ImageIcon back?
    I've seen some people just paint the button on a new ImageIcon, but then it's not the same image, it has the button look around the original icon, not to mention since it's a toggle button you actually get the selectedIcon() instead.
    Please help. Thanks.

    All you basically have to do is use getIcon() and cast it to an ImageIcon... here's an example:
    import java.awt.*;
    import javax.swing.*;
    public class ImageIconGrab {
    public static void main(String[] args) {
    JFrame frame = new JFrame("ImageIcon Grabber");
    JToggleButton jtb = new JToggleButton(new ImageIcon("pregoico.gif"));
    ImageIcon ii = (ImageIcon) jtb.getIcon();
    JToggleButton jtb2 = new JToggleButton(ii);
    frame.getContentPane().add(jtb, BorderLayout.NORTH);
    frame.getContentPane().add(jtb2, BorderLayout.SOUTH);
    frame.pack();
    frame.setVisible(true);

  • Calling a method and setting an ImageIcon with source from anoth class

    I am trying to make a simple game, first I am trying to set up a game board, and make it possible to place units on the board. (This game will probably never be possible to play, I am just using it to try to understand Java, GUI, Swing, and using more than one class).
    So far I have 4 classes: Board (extends JFrame, sets up a gameboard, on which to place the pieces), Unit (a class from which the specific units types will inherit), Horse (my only type of unit, which extends the Unit class), and Game (which calls methods from the other classes).
    (These don't do much now.. this is what they will do, hopefully).
    All these classes are in a package called Gamev1.
    In the main method of Game, I do:
    ---code--
    public static void main (String[]args){
    new Board().show();
    Horse horseUnits[] = new Horse[1];
    horseUnits[0] = new Horse();
    horseUnits[0].moveUnit(squares[0]);
    end of code--
    when I debug it I get:
    myjava/FirstGraphics/Gamev1/Game.java [25:1] cannot resolve symbol
    symbol: variable squares
    location: class.myjava.FirstGraphics.Gamev1.Game
    horseUnits[0].moveUnitsquares[0]);
    1 error
    ---code----
    moveUnit(JLabel moveTo)
    is a method in Unit class:
    public void moveUnit(JLabel moveTo){
    target=moveTo;
    target.setIcon(this.image);
    if (this.position !=null)
    this.position.setIcon(noUnit);
    this.position=moveTo;
    ---end of code---------
    squares[] is an array of JLabels which is set up in the Board class, whenever a new Board is created:
    ---code---
    JLabel squares[] = new JLabel[100];
    for (int s=0; s<100; s++){
    squares[s] = new JLabel();
    ---end of code---
    I tried changing the reference from squares[0] to Board.squares[0] but I got the same error message in debug.
    Any idea what is wrong?
    I have another problem, which is probably similar.
    in the Board class I call:
    squares[s].setIcon(Unit.noUnit);
    and in the Unit class I have:
    static ImageIcon noUnit = new ImageIcon("images//none.gif");
    I don't get an error message mentioning it, but (without the attempt to place the horse on the board) the program compiles, but doesn't put this image on the labels. Any idea what is the porblem here?
    If I have not given enough information for anyone to help me, please tell me what further information I should give.
    Thanks to anyone who answers.

    I got it to work with
        Board board = new Board();
        horseUnits[0].moveUnit(board.squares[0]);To use Board.squares[0], squares would have to be static.
    The ImageIcon seemed to work okay. I noticed that your post had two slashes in the url [/] - that might throw things off . . .
    The code below has the icon call at the end of setLabeLProperties.
    I got carried away playing with the graphics so the squares don't work very well.
    import java.awt.*;
    import java.awt.geom.*;
    import javax.swing.*;
    public class HumaniBlue {
      public static void main(String[] args) {
        Board board = new Board();
        board.show();
        JLabel label5 = board.getLabel(5);
        //System.out.println("label5 name = " + label5.getText());
        Horse[] horseUnits = new Horse[1];
        horseUnits[0] = new Horse();
        horseUnits[0].moveUnit(board.squares[0]);
    class Unit {
      static ImageIcon noUnit = new ImageIcon("images/bclynx.jpg");
      public void moveUnit(JLabel square) {
    class Horse extends Unit {
      public Horse() {}
    class Board {
      JFrame f;
      JPanel gameBoard;
      int labelSize;
      JLabel[] squares = new JLabel[16];
      GridBagConstraints gbc = new GridBagConstraints();
      public Board() {
        gameBoard = new JPanel(new GridBagLayout()) {
          public void paintComponent(Graphics g) {
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            double width  = getSize().width;
            double height = getSize().height;
            g2.setPaint(Color.white);
            g2.fill(new Rectangle2D.Double(0, 0, width, height));
            g2.setPaint(Color.black);
            Shape line;
            double
              gridSize = (width < height ? width : height) * 0.8,
              gridUnit = (width < height ? width : height) / 5,
              x = (width  - gridSize) / 2,
              y = (height - gridSize) / 2;
            labelSize = (int)gridUnit;
            for(int j = 0; j < 5; j++) {
              line = new Line2D.Double(x, y, x, y + gridSize);      
              g2.draw(line);
              x += gridUnit;
            x = (width - gridSize) / 2;
            for(int j = 0; j < 5; j++) {
              line = new Line2D.Double(x, y, x + gridSize, y);
              g2.draw(line);
              y += gridUnit;
          //System.out.println("width = " + width + "\theight = " + height + "\n" +
          //                   "x = " + x + "\ty = " + y + "\n" +
          //                   "gridSize = " + gridSize + "\tgridUnit = " + gridUnit);
        f = new JFrame();
        f.getContentPane().add(gameBoard);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(400,400);
        f.setLocation(600,200);
        //f.setVisible(true);
        setLabelProperties();
      private void setLabelProperties() {   
        int
          r   = 30,
          g   = 30,
          b   = 0,
          inc = 55;
        //System.out.println("labelSize = " + labelSize);
        for(int j = 0; j < squares.length; j++) {
          squares[j] = new JLabel("Square " + j, JLabel.CENTER);
          squares[j].setOpaque(true);
          squares[j].setPreferredSize(new Dimension(73, 73));
        // add labels
        int index = 0;
        gbc.gridx = 0;
        gbc.gridy = 0;
        for(int y = 0; y < 4; y++) {
          for(int x = 0; x < 4; x++) {
            index = y * 4 + x;
            squares[index].setBackground(new Color(r,g,b,90));
            gameBoard.add(squares[index], gbc);
            gbc.gridx++;
            r += inc;
          gbc.gridy++;
          gbc.gridx = 0;
          r = 90;
          g += inc;
        squares[9].setIcon(Unit.noUnit);
      public void show() {
        f.setVisible(true);
      public JLabel getLabel(int index) {
        return squares[index];
    }

  • Is it possible to make an ImageIcon array?

    Hi, I have been having some strange problems with ImageIcon...
    Here is my code...
    ImageIcon tiles[][] = new ImageIcon[5][5];
    tiles[0][0] = "1.png";
    I know this is not right, but basically, I want to make a 2dimensional array of imageIcon's, and then use a loop to set the link to the image. This is tough because I have not had any luck with this code. It works on strings, int's, float's, etc. but not on ImageIcon's grrrrrrr
    thanks

    All I want to do, Is make an array of ImageIcon's and then use a 2dimensional loop to draw all the tiles.
    problem one: I want to use a loop to create each individual ImageIcon, and since there is no "setfile" kind of function i tried making my own in the post above. But im simply trying to make a loop which sets all of the tiles to appropriate file names. (all the file names are numbers and then .png)
    Thats all I want to do, and I want to pass a parameter to a function which tells it the filename to set, and the specific ImageIcon in the array to modify. Hence why I had 2 paramater strings in the previous post

Maybe you are looking for