ImageIcon problems

Hi!
I've problems with image icon. When I tried to scale or rotate it, "out of memory error" occours (mostly at larger pictures). Is there any solution to this problem?
I know the "java -Xmx120m" solution, but this not solves the problem, just delays it.
Any help would be usefull. THX!

I tried for some month brefore using JAI to solve the problem of visualizing very big image using BufferedImage but I didn't find any solution.
The only way i found were Tiling the original image in smallest image and read at each time only those visible.
I think the solution with java advanced image is at the moment the best I found
Stefano Madeddu

Similar Messages

  • A ImageIcon problem in Sun Java Studio Enterprise

    When I programmed with SJSE, I found a problem, let see a simple test:
        private void initComponents() {
            jButton1 = new javax.swing.JButton();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setResizable(false);
            jButton1.setIcon(new javax.swing.ImageIcon("D:\\Sun\\JavaProjects\\test\\src\\test\\next.gif"));
            jButton1.setText("jButton1");
            getContentPane().add(jButton1, java.awt.BorderLayout.CENTER);
            pack();
        }This is for to show a picture in a button with File Path(which means you should choose a specific file on your disk).
    But,
    if I change the code into:
    private void initComponents() {
            jButton1 = new javax.swing.JButton();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setResizable(false);
            jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/test/next.gif")));
            jButton1.setText("jButton1");
            getContentPane().add(jButton1, java.awt.BorderLayout.CENTER);
            pack();
        }The problem occurs. When I run this sample application, one exception throws:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at javax.swing.ImageIcon.<init>(ImageIcon.java:138)
    at test.NewJFrame.initComponents(NewJFrame.java:31)
    at test.NewJFrame.<init>(NewJFrame.java:17)
    at test.NewJFrame$2.run(NewJFrame.java:55)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:461)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
    Could someone help me?
    Message was edited by:
    linyinlu

    No, this code was generated automatically by JSE.
    "New"->"JFrame"->Modify the property for this button->in "Icon" section-> choose the "ClassPath" and specific the icon. But it is not work.
    Today I have unstall the whole thing: JDK, JSE 8, deleted all dierctories and files and reinstalled them. But the problem is also not solved.
    Message was edited by:
    Scott
    Message was edited by:
    linyinlu

  • JButton imageIcon problem

    hello ,
    i am facing a problem in changing the imageicon of jbutton in my application.
    i want to change imageicon for few seconds and than again change it to original imageicon....
    is it possible?????????????i have tried but after initializing button with one imageicon we are not able to change that icon again..
    so what should i do...it is compulsory to change take two image for button.....
    please help

    Set up a Timer. You use the setIcon(...) method to change the icon. Then you start a Timer to fire in a few seconds and use the setIcon(...) method to change the image back to its original value.

  • ImageIcon problem *Please HELP*

    Hello
    I am having problems adding an Image to this code I have tried everything I know but to no avail. Could u please give me some pointers as to what I am doing wrong.
    Thank you Michael
    The code:
    {color:#003300}package calculator;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class calculator extends JFrame {
    {color}
    {color:#003300}
    public calculator(){
    Container con = getContentPane();
    setSize(800, 600);
    con.setLayout(new GridLayout(5, 1));
    final JTextField value1, value2, sum;
    {color}
    {color:#003300}
    {color:#ff0000}ImageIcon img = new ImageIcon("images/calculator.jpg");
    JButton button = new JButton();
    button.setIcon(img);
    con.add(button);{color}
    value1 = new JTextField();
    value2 = new JTextField();
    sum = new JTextField();
    sum.setEditable(false);
    con.add(button);
    con.add(value1);
    con.add(value2);
    con.add(sum);
    JButton button1 = new JButton("Test 1");
    button1.setText("Equals");
    button1.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e)
    int val1 = Integer.parseInt(value1.getText());
    int val2 = Integer.parseInt(value2.getText());
    int val3 = val1 + val2;
    String val4 = Integer.toString(val3);
    sum.setText(val4);
    con.add(button1);
    pack();
    setVisible(true);
    }{color}

    Hello thank you for replying to my post I reposted the code in the correct way. I have tried running your code that you have provided but the image would still not show up on the screen. Is there any advice or problems that you can see with my code ? Any help is greatly appreciated.
    Thank you Michael
    /* Author Michael
    package calculator;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class calculator extends JFrame {
        private static final String CALC_IMAGE_STRING = "images/calculator.jpg";
        public calculator(){
        Container con = getContentPane();
        setSize(800, 600);
        con.setLayout(new GridLayout(5, 1));
        final JTextField value1, value2, sum;
        ImageIcon img = new ImageIcon(CALC_IMAGE_STRING);
        JButton button = new JButton(img);
        System.out.println("The File is located at " + CALC_IMAGE_STRING);
        System.out.println("image height: " + img.getIconHeight());
        con.add(button);
        value1 = new JTextField();
        value2 = new JTextField();
        sum = new JTextField();
        sum.setEditable(false);
        con.add(button);
        con.add(value1);
        con.add(value2);
        con.add(sum);
        JButton button1 = new JButton("Test 1");
        button1.setText("Equals");
        button1.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e)
            int val1 = Integer.parseInt(value1.getText());
            int val2 = Integer.parseInt(value2.getText());
            int val3 = val1 + val2;
            String val4 = Integer.toString(val3);
            sum.setText(val4);
        con.add(button1);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
        setVisible(true);
    }

  • Remove imageicon problem!!Please help!!

    Hi!I m trying to do this:When the delete button is pressed , remove the jlabels appeared by one, from the last one to the first one!!How can i do this?I tried to do it with icon.set(null) but they all dissapear!Thank you!
    package icons;
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Icons extends Applet {
      JButton jButton1 = new JButton("a");
      JButton jButton2 = new JButton("b");
      JButton jButton3 = new JButton("c");
      JButton jButton4 = new JButton("d");
      JButton jButton5 = new JButton("e");
      JButton jButton6 = new JButton("f");
      JButton jButton7 = new JButton("g");
      JButton jButton8 = new JButton("compare");
      JButton jButton9 = new JButton("delete");
      FlowLayout flowLayout1 = new FlowLayout();
      JLabel jLabel1 = new JLabel();
      JLabel jLabel2 = new JLabel();
      JLabel jLabel3 = new JLabel();
      JLabel jLabel4 = new JLabel();
      JLabel jLabel5 = new JLabel();
      JLabel jLabel6 = new JLabel();
      JLabel jLabel7 = new JLabel();
    String s=new String();
      int i =1;
      ImageIcon myIcon1 = new ImageIcon("eikones/image1.gif");
      ImageIcon myIcon2 = new ImageIcon("eikones/image2.gif");
      ImageIcon myIcon3= new ImageIcon("eikones/image3.gif");
      ImageIcon myIcon4= new ImageIcon("eikones/image4.gif");
      ImageIcon myIcon5  = new ImageIcon("eikones/image5.gif");
      ImageIcon myIcon6 = new ImageIcon("eikones/image6.gif");
      ImageIcon myIcon7 = new ImageIcon("eikones/image7.gif");
      public void init() {
        jButton1.setPreferredSize(new Dimension(150, 25));
        jButton1.setIcon(myIcon1);
        jButton1.addActionListener(new Icons_jButton1_actionAdapter(this));
         jButton2.setPreferredSize(new Dimension(150, 25));
        jButton2.setIcon(myIcon2);
        jButton2.addActionListener(new Icons_jButton2_actionAdapter(this));
        jButton3.setPreferredSize(new Dimension(150, 25));
        jButton3.setIcon(myIcon3);
        jButton3.addActionListener(new Icons_jButton3_actionAdapter(this));
        jButton4.addActionListener(new Icons_jButton4_actionAdapter(this));
        jButton4.setPreferredSize(new Dimension(150, 25));
        jButton4.setIcon(myIcon4);
        jButton5.addActionListener(new Icons_jButton5_actionAdapter(this));
        jButton5.setPreferredSize(new Dimension(150, 25));
        jButton5.setIcon(myIcon5);
        jButton6.setPreferredSize(new Dimension(150, 25));
        jButton6.setIcon(myIcon6);
        jButton6.addActionListener(new Icons_jButton6_actionAdapter(this));
        jButton7.setPreferredSize(new Dimension(150, 25));
        jButton7.setIcon(myIcon7);
        jButton7.addActionListener(new Icons_jButton7_actionAdapter(this));
        jButton8.setPreferredSize(new Dimension(150, 25));
        jButton8.addActionListener(new Icons_jButton8_actionAdapter(this));
        jButton9.setPreferredSize(new Dimension(150, 25));
        jButton9.addActionListener(new Icons_jButton9_actionAdapter(this));
        jLabel1.getIcon();
        jLabel2.getIcon();
        jLabel3.getIcon();
        jLabel4.getIcon();
        jLabel5.getIcon();
        jLabel6.getIcon();
        jLabel7.getIcon();
        add(jButton1);
        add(jButton2);
        add(jButton3);
        add(jButton4);
        add(jButton5);
        add(jButton6);
        add(jButton7);
        add(jButton8);
        add(jButton9);
        add(jLabel1);
        add(jLabel2);
        add(jLabel3);
        add(jLabel4);
        add(jLabel5);
        add(jLabel6);
        add(jLabel7);
          public Icons()
                    this.setLayout(new FlowLayout(FlowLayout.LEFT));
      void jButton1_actionPerformed(ActionEvent e) {
       if (i==1)
          jLabel1.setIcon(myIcon1);
            else if (i==2)
         jLabel2.setIcon(myIcon1);
       else if (i==3)
          jLabel3.setIcon(myIcon1);
        else if (i==4)
            jLabel4.setIcon(myIcon1);
          else if (i==5)
            jLabel5.setIcon(myIcon1);
           else if (i==6)
            jLabel6.setIcon(myIcon1);
         else if (i==7)
         jLabel7.setIcon(myIcon1);
          s=s+jButton1.getText();
          i++;
      void jButton2_actionPerformed(ActionEvent e) {
        if (i==1)
          jLabel1.setIcon(myIcon2);
       else if (i==2)
         jLabel2.setIcon(myIcon2);
        else if (i==3)
         jLabel3.setIcon(myIcon2);
      else if (i==4)
            jLabel4.setIcon(myIcon2);
          else if (i==5)
             jLabel5.setIcon(myIcon2);
            else if (i==6)
             jLabel6.setIcon(myIcon2);
          else if (i==7)
          jLabel7.setIcon(myIcon2);
            s=s+jButton2.getText();
          i++;
      void jButton3_actionPerformed(ActionEvent e) {
        if (i==1)
         jLabel1.setIcon(myIcon3);
        else if (i==2)
          jLabel2.setIcon(myIcon3);
        else if (i==3)
          jLabel3.setIcon(myIcon3);
       else if (i==4)
        jLabel4.setIcon(myIcon3);
         else if (i==5)
            jLabel5.setIcon(myIcon3);
           else if (i==6)
            jLabel6.setIcon(myIcon3);
         else if (i==7)
          jLabel7.setIcon(myIcon3);
            s=s+jButton3.getText();
        i++;
      void jButton4_actionPerformed(ActionEvent e) {
       if (i==1)
        jLabel1.setIcon(myIcon4);
       else if (i==2)
         jLabel2.setIcon(myIcon4);
       else if (i==3)
          jLabel3.setIcon(myIcon4);
        else if (i==4)
            jLabel4.setIcon(myIcon4);
          else if (i==5)
            jLabel5.setIcon(myIcon4);
           else if (i==6)
            jLabel6.setIcon(myIcon4);
         else if (i==7)
          jLabel7.setIcon(myIcon4);
            s=s+jButton4.getText();
          i++;
      void jButton5_actionPerformed(ActionEvent e) {
        if (i==1)
          jLabel1.setIcon(myIcon5);
       else if (i==2)
         jLabel2.setIcon(myIcon5);
        else if (i==3)
         jLabel3.setIcon(myIcon5);
      else if (i==4)
            jLabel4.setIcon(myIcon5);
          else if (i==5)
             jLabel5.setIcon(myIcon5);
            else if (i==6)
             jLabel6.setIcon(myIcon5);
          else if (i==7)
          jLabel7.setIcon(myIcon5);
            s=s+jButton5.getText();
          i++;
      void jButton6_actionPerformed(ActionEvent e) {
        if (i==1)
         jLabel1.setIcon(myIcon6);
        else if (i==2)
          jLabel2.setIcon(myIcon6);
        else if (i==3)
          jLabel3.setIcon(myIcon6);
       else if (i==4)
        jLabel4.setIcon(myIcon6);
         else if (i==5)
            jLabel5.setIcon(myIcon6);
           else if (i==6)
            jLabel6.setIcon(myIcon6);
         else if (i==7)
          jLabel7.setIcon(myIcon6);
         s=s+jButton6.getText();
        i++;
      void jButton7_actionPerformed(ActionEvent e) {
       if (i==1)
        jLabel1.setIcon(myIcon7);
       else if (i==2)
         jLabel2.setIcon(myIcon7);
       else if (i==3)
          jLabel3.setIcon(myIcon7);
        else if (i==4)
            jLabel4.setIcon(myIcon7);
          else if (i==5)
            jLabel5.setIcon(myIcon7);
           else if (i==6)
            jLabel6.setIcon(myIcon7);
         else if (i==7)
          jLabel7.setIcon(myIcon7);
           s=s+jButton7.getText();
          i++;
      void jButton8_actionPerformed(ActionEvent e) {
      void jButton9_actionPerformed(ActionEvent e) {
          s="";
      jLabel4.setText(null);
    i=1;
    class Icons_jButton1_actionAdapter implements java.awt.event.ActionListener {
      Icons adaptee;
      Icons_jButton1_actionAdapter(Icons adaptee) {
        this.adaptee = adaptee;
      public void actionPerformed(ActionEvent e) {
        adaptee.jButton1_actionPerformed(e);
    class Icons_jButton2_actionAdapter implements java.awt.event.ActionListener {
      Icons adaptee;
      Icons_jButton2_actionAdapter(Icons adaptee) {
        this.adaptee = adaptee;
      public void actionPerformed(ActionEvent e) {
        adaptee.jButton2_actionPerformed(e);
    class Icons_jButton3_actionAdapter implements java.awt.event.ActionListener {
      Icons adaptee;
      Icons_jButton3_actionAdapter(Icons adaptee) {
        this.adaptee = adaptee;
      public void actionPerformed(ActionEvent e) {
        adaptee.jButton3_actionPerformed(e);
    class Icons_jButton4_actionAdapter implements java.awt.event.ActionListener {
      Icons adaptee;
      Icons_jButton4_actionAdapter(Icons adaptee) {
        this.adaptee = adaptee;
      public void actionPerformed(ActionEvent e) {
        adaptee.jButton4_actionPerformed(e);
    class Icons_jButton5_actionAdapter implements java.awt.event.ActionListener {
      Icons adaptee;
      Icons_jButton5_actionAdapter(Icons adaptee) {
        this.adaptee = adaptee;
      public void actionPerformed(ActionEvent e) {
        adaptee.jButton5_actionPerformed(e);
    class Icons_jButton6_actionAdapter implements java.awt.event.ActionListener {
      Icons adaptee;
      Icons_jButton6_actionAdapter(Icons adaptee) {
        this.adaptee = adaptee;
      public void actionPerformed(ActionEvent e) {
        adaptee.jButton6_actionPerformed(e);
    class Icons_jButton7_actionAdapter implements java.awt.event.ActionListener {
      Icons adaptee;
      Icons_jButton7_actionAdapter(Icons adaptee) {
        this.adaptee = adaptee;
      public void actionPerformed(ActionEvent e) {
        adaptee.jButton7_actionPerformed(e);
    class Icons_jButton8_actionAdapter implements java.awt.event.ActionListener {
      Icons adaptee;
      Icons_jButton8_actionAdapter(Icons adaptee) {
        this.adaptee = adaptee;
      public void actionPerformed(ActionEvent e) {
        Graphics g = getGraphics();
        if(s.equals("a"+"b"+"b"+"e"))
           g.drawString("ok",350,300);
              else
           g.drawString("wrong",150,300);
        adaptee.jButton8_actionPerformed(e);
    class Icons_jButton9_actionAdapter implements java.awt.event.ActionListener {
      Icons adaptee;
      Icons_jButton9_actionAdapter(Icons adaptee) {
        this.adaptee = adaptee;
      public void actionPerformed(ActionEvent e) {
        adaptee.jButton9_actionPerformed(e);
    public void paint(Graphics g){
      g.setColor (back);
       g.fillRect (0,0,300,250);
       g.setColor (back1);
       g.fillRect (0,250,100,50);
      super.paint(g);
    }

    I don't really understand what you are trying to do but it is easier to write a single listener for all your buttons with code something like the following:
    ActionListener listener = new ActionListener()
        public void actionPerformed(ActionEvent e)
            JButton button = (JButton)e.getSource();
            String command = button.getActionCommand();
            if ("a".equals( command ))
                jLabel1.setIcon( null );
            else if ("b".equals( command ) )
                jLabel2.setIcon( null );
    };Another option would be to store you buttons and labels in an array. Then you would search the button array to find the index of the button clicked. Once you know this index then you can reset the label at the same index.

  • ImageIcon problem in a CellEditor

    Hello all,
    I'm really stacked with one anoying behavior. In my own CellEditor ImageCellEditor I wrote the following code.
    public Component getTableCellEditorComponent(
    JTable table,
    Object value,
    boolean isSelected,
    int row,
    int col) {
    if (value == null) {
    return editorComponent;
    ImageIcon imageIcon;
    if (value instanceof byte[]) {
    imageIcon = new ImageIcon((byte[])value);
    System.out.println("byte[]: " + imageIcon);
    else if (value instanceof String) {
    imageIcon = new ImageIcon(value.toString().getBytes());
    System.out.println("String: " + imageIcon);
    else {
    imageIcon = null;
    System.out.println("Null: " + imageIcon);
    ((JButton)editorComponent).setIcon(imageIcon);
    return editorComponent;
    The result of this code becomes strange, whererever message is thrown it prints "null", but the JButton editorComponent gets the image I want to show.
    Does anyone knows how it's possible? I supposed that if imageIcon is null and I set the icon of a JButton to this imageIcon, then it must be as if I had written ((JButton)editorComponent).setIcon(null);
    Please, help me to solve this "feature".

    Do you want to show your image in the table ? In this case, it is a CellRenderer you have to write...

  • ImageIcon problem

    Hi ,
    I creat a class extends Panel ( do I have to extend "JApplet"??). I try to use ClassLoader to get the source of the ImageIcon and put it as background of my JButton, but the ImageIcon doesn't display. I put multiple image file in the "images" folder , and this folder is under directory of my JAR file. Ans I also put this folder under the directory where the .class files is located.
    Here is my code:
    public class ButtonPanel extends Panel implements ActionListener {
    ButtonPanel() {
      setPanel();
    public void setPanel() {
    icon=new ImageIcon();
    icon=getMyIcon("images/theBtBacground.gif");
    MyButton = new JButton(icon);
    public ImageIcon getMyIcon(String source) {
        ImageIcon icon = null;
        URL iconURL = ClassLoader.getSystemResource(source);
        if (iconURL != null)
        icon = new ImageIcon(iconURL);
        return icon;
    }Also, I try another way to specify the image file
    public class ButtonPanel extends Panel implements ActionListener {
    ButtonPanel() {
      setPanel();
    public void setPanel() {
    URL iconURL=getURL("images/theBtBacground.gif");
    MyButton = new JButton(new ImageIcon(iconURL));
    public URL getURL(String filename) {
            URL codeBase =this.getCodeBase();
            URL url = null;
            try {
                url = new URL(codeBase, filename);
            } catch (java.net.MalformedURLException e) {
                System.err.println("Couldn't create image: badly specified URL");
                return null;
            return url;
    }but error message shows:
    "can not resovle symbol method getCodeBase()"
    I check the java. AWT.Panel library , the method getCodeBase() is there!
    Please help me. thanks.

    Here's how i accomplished a similar task. Holla back if it doesn't help !
             public ImageIcon createImageIcon(String path,String description)
                 java.net.URL imgURL = Client_2005_version1.class.getResource(path);
                 if (imgURL != null)
                     return new ImageIcon(imgURL, description);
                 else
                     System.err.println("Couldn't find file: " + path);
                     return null;
              class iconBoxClass extends JMenuItem
                   ImageIcon emoIcon = createImageIcon("cry_smile.gif",
                                                                  "emotion icon");
                   public iconBoxClass(ImageIcon eIcon)
                        eIcon = emoIcon;
              }

  • Gif file not found in JAR from Java Application

    Hello Forumers,
    Could some one please explain how to create a JAR file from where I can get a GIF file. I have tried a number of different ways but it allways fails. (I have tried to add the GIF files using the jar command and I have tried to add it using WinZip after the jar is created).
    To isolate the problem I created this very simple program, the program works very well when the gif file resides on the directory from where I run the Application, but when I remove it from the directory it fails. I have tried to put the GIF file in the JAR in a number of different ways but it allways fails. (I have also tried with and without slash before the name of the GIF). I guess the problem is the way I create the JAR file
    import java.io.*;
    public class GifTest
    { public static void main(String args[])
    { InputStream in = GifTest.class.getResourceAsStream("/open.gif");
    if (in==null)
    System.out.println("Null returned");
    else
    System.out.println("OK");
    Any Hints appreciated
    /Kjell

    Hi,
    here is a small application using my own class GetImageIcon.
    Normally I have this "help-class" in a utility-package to use it from all my projects without copying. For this example I copied the code in the test application. Feel free to use the code of the class like you want. For me it works fine.
    Do the following:
    1. Create a folder called /meta-inf under the folder where the class-files are. Use a text-editor and create a file saved as "manifest.mf".
    manifest.mf tells the jar-file which is the main-class from where the application will start when double-clicked.
    It only has to contain one line:
    Main-Class: GifTest
    2. Compile and create the jar file. I made a bat-file containing:
    javac -verbose GifTest.java
    %pause
    REM Create Jar-File
    jar cmf meta-inf/manifest.mf GifTest.jar *.class *.gif
    REM Show Table of Content of the Jar-File
    jar tf GifTest.jar
    %pause
    So you can see what's in the jar-file.
    3. When you double-click on the jar-file the application is executed. So it is easier to use for the users. They don't have to type in anything on the command-line. You can deploy this jar-file to any client and run it. The only thing you have to do, is to install the JRE on the clients.
    I develop with JDK 1.3.1 and JRE 1.3.1 is installed on the clients of the company I work for.
    //Begin of the code
    import java.io.*;
    import java.awt.*;
    import javax.swing.*;
    import java.util.jar.*;
    public class GifTest extends JFrame
            protected JLabel m_title;
            protected ImageIcon m_image;
            static File file;
            //You have to define the name of the jar-file
            static String jarFile = "GifTest.jar";
            //Instance of the class GetImageIcon
            protected GetImageIcon gii = new GetImageIcon();
            public GifTest()
                    super("GifTest");
                    setSize(400,200);
                    //the name of the image and the name of the jar-file the image resides in
                    m_image = gii.getImageIcon("orb.gif", "GifTest.jar");
                    m_title = new JLabel(null, m_image, SwingConstants.CENTER);
                    getContentPane().add(m_title, BorderLayout.NORTH);
            public static void main(String argv[]) {
                    GifTest frame = new GifTest();
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setVisible(true);
    public class GetImageIcon{
    * @param fileName the full qualified name of the file
    * from the root of your application. use a "/" before the
    * fileName, eg. /images/warning.gif
        public ImageIcon getImageIcon(String fileName, String jarName) {
            int counter, c, i = 0;
            byte buffer[];
            JarFile  jfile;
            JarEntry jentry;
            InputStream in;
            ImageIcon m_image;
            try{
                    // Create Jar-File object from JarFile
                    jfile = new JarFile(jarName);
            catch(Exception ex){
                    System.out.println("JarFile-Problem " + "\n" + ex);
                    return null;
            try{
                    // create Jar-Entry object from File-Name in JarFile
                    jentry = jfile.getJarEntry(fileName);
            catch(Exception ex){
                    System.out.println("JarEntry-Problem " + "\n" + ex);
                    return null;
            try{
                    // create InputStream from JarEntry
                    in = jfile.getInputStream(jentry);
            catch(Exception ex){
                    System.out.println("JarEntry-Problem " + "\n" + ex);
                    return null;
            try{
                    //get uncompressed size of entry data in Jar-File and create byte-array with this size
                    buffer = new byte[(int)jentry.getSize()];
                    //write int-value 'c' (casted to byte) with read() and while-loop in byte-Array
                    while((c = in.read()) != -1){
                            buffer[i] = (byte)c;
                            i++;
            catch(Exception ex){
                    System.out.println("in.read()-Problem " + "\n" + ex);
                    return null;
            try{
                    //create ImageIcon with byte-Array 'buffer'
                    m_image = new ImageIcon(buffer);
            catch(Exception ex){
                    System.out.println("ImageIcon-Problem " + "\n" + ex);
                    return null;
            // return the created ImageIcon
            return m_image;
    }

  • Loading JPEG/Gif images causes Out Of Memory Error

    Hello Java gurus, please shed some light on this.....
    I am not a java newbie, but I am a java newbie in the area of dealing with graphics. I am using JDK 1.4.2_01 on Win XP with 2.4ghz and 512 RAM. When I try to read in a (or a few) JPEG image into a JLabel using ImageIcon, I get an out of memory error everytime. This happens whether I am reading the image out of a jar file or out of a local directory. The JPEG's are 8.5" x 11", and range between 150kb to 900kb. I am trying to load approximately 10 images in a JTabbedPane using new JLabel(ImageIcon) on individual JPanels (one JPanel for each JPEG). Now I get the java.lang.outofmemory error whether I try to load 1 image or 10 images. Anyone got a clue as to what I am doing wrong? I actually do get one image loaded before the error gets thrown. So I do know that it is trying to load the right image. What is going on here? Is it an ImageIcon problem, or are there others who have run into this. It has brought this project to a grinding halt, and I had thought this would be the easier part!!!! Please help me out gurus! Thanks!

    What options/values are you suggesting that I set? Or do you mean something else? Thank you for any ideas that can help me solve this problem. I never had any issues dealing with using ImageIcon for toolbar button graphics (file sizes of 1-3kb), but now with dealing with full page graphics I have run into a brick wall with this out of memory error.

  • 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

  • Problem with an ImageIcon

    hi, i have a problem. i have two JButtons with image icon, and i want to superpose another JButton with imageIcon on the first button. i really have to make a music keyboard, and that is for the black keys. i have all the white keys, and when a draw the black keys.., it appears behind the white keys... how do i controll wich image will be shown on the front.. thanks for any help and excuseme for my poor english... thanks again.

    Don't do cross-posting.

  • Problem showing imageicon in cell using TableCellRenderer

    Hi all,
    I am using a tablecellrenderer to display an icon in a particular jtable column to reflect a value in the underlying model.
    When I do this, the column does not display the ImageIcon at all. My code for the CellRenderer is below.
    It should also be noted that I use another table cell renderer on the whole table to remove the line around the selection on the selected cell. This all works fine.
    public class StatusCellRenderer implements TableCellRenderer {
        private static ImageIcon blueIcon = new ImageIcon("images/blue.gif");
        private static ImageIcon redIcon = new ImageIcon("images/red.gif");
        private JLabel label = new JLabel();
        // Constructors
        public StatusCellRenderer() {
            label.setHorizontalAlignment(JLabel.CENTER);
            label.setVerticalAlignment(JLabel.CENTER);
        // TableCellRenderer interface implementation
        public Component getTableCellRendererComponent(JTable table,
        Object value,
        boolean isSelected,
        boolean hasFocus,
        int row,
        int column) {
            if (Integer.parseInt(value.toString()) > 0){
                label.setIcon(blueIcon);
                label.repaint();
                return label;
            else if (Integer.parseInt(value.toString()) == 0){
                label.setIcon(redIcon);
                label.repaint();
                return label;
            else
                return null;
    }

    First question: What do you see in the column where you expect the Icon?
    First suggestion: extend DefaultTableCellRenderer instead of implementing TableCellRenderer interface. Just a suggestion.
    second question: Have you set the renderer for the class of objects in target column to be the StatusCellRenderer?
    As camrickr says you need to post a little more code. Maybe a SMALL demo program illustrating your problem. Use code tags for legibility.
    Cheers
    DB

  • Parsing Problems? ImageIcon and BufferedImage

    Hi to everyone
    Could I ask if I will to send ImageIcon with BufferedImage as its arguement. Then what should I receieve from the server? ImageIcon only or ImageIcon with BufferedImage as its arugement?
    Any help will be appreciated. Thank You.

    I am sending ImageIcon over to the server, hence the server will receive as ImageIcon.
    However, when I want to pass the ImageIcon which being parse to Image, this step is ok. Lastly when I want to parse the Image to BufferedImage image, I am encountering parsing problems, hence could u advise me further.
    The error message "Receiving failed: java.lang.ClassCastException"
    Any help will be appreciated. Thank You.
         public void getImage()
              //Object input = null;
            Image images = null;
              try{
                   imgIcon = (ImageIcon)oin.readObject();
                   System.out.println("Icon Width: "+imgIcon.getIconWidth());
                   while((images = imgIcon.getImage()) != null)
                        System.out.println("Images Width: "+Image.getWidth(images));
                        BufferedImage bimage = (BufferedImage)images; // PROBLEM LIES HERE
                        System.out.println("Bimage Width: "+bimage.getWidth());
                        ImageServerConnection.writeImage(bimage, "happy.jpg");
                        //String fname = "joalicia";
                        //create an new folder to store those sent images.
                        //File f = new File ("c:\\Sweet", fname);
                        //create(f);
              }catch(Exception e){
                   System.err.println("Receiving failed: "+ e);
         }

  • Putting an image into a jtextpane / problems with ImageIcon and path

    So here is what I am trying to do. I would like to be able to allow the user to add images to a jtextpane which will also contain rtf text.
    My current plan is to have a drag event or some other event run the actual code to place the image in the jtextpane. So my first attempt was just to first write a test program to add an image to a textpane using a hard coded path. The problem is i cant seem to create an imageicon using a canonical path because the image icon constructor wants a relative path(from the docs).
    So i guess the best solution would be to convert the canonical path to a relative path. I have this forum and google many times and found many similar posts but none with a real solution (people just reply, why would you want to do that etc.).
    So i either need to convert the path or if any one has a better suggestion to allow users to add images to the jtextpane. Any suggestions?

    show the path you are trying to use.
    Edited by: JacobsB on Mar 13, 2008 1:11 PM
    and try this
    URL url = getClass().getResource(pathName);
    ImageIcon(url);

  • Having some problems with ImageIcons and JLabels

    I'm making a checkers game, and so far it's going pretty well.
    I've got the basic game down, and you can move pieces, jump, your turn ends when you can't jump anymore, etc...
    However, I've had three problems:
    1.) I'm using JLabels to display my board (8 x 8.. well actually 9 x 9 for an outer row labelled A,B,C,D.. 1,2,3,4...) Anyway, I create the JLabels using something that looks like \:
    JLabel square = new JLabel(new ImageIcon("pic.png"));
    Now, the picture loads properly, but it seems like the picture is being cropped, and the top and bottom are getting chopped off, so my 36 x 36 pixel *.gif appears to be 36 x 30.
    You can see how there is a gap created in:
    http://img235.imageshack.us/img235/7765/prob13ky.jpg
    Now the problem may be with the GridLayout I am using, but I set the distance between the components in the container to be 0, 0 so I don't think that GridLayout is chopping my icons. I've also tried setPreferredSize(new Dimension(36,36))
    for both my ImageIcons and JLabels and for my container (which I set to size 2000,2000, just to make sure there was room). If anyone can help me, it's be appreciated.
    2.) I used to be able to view my outside row/column of squares that said A,B,C,D.... and 1,2,3,4... with the square in the corner having a random pic. For some reason now (have no clue why) I now see only the pic in the corner, and then a little gray smudge diagonally under it.
    Pic:
    http://img347.imageshack.us/img347/8308/prob24im.jpg
    I don't know what's wrong. I'm pretty sure it's none of the new methods I've written, as those are all in my static void main (String[] ar) ...... and if I comment all the methods in my main except where I first make the JFrame and set it visible, it still turns out like that. repaint() doesn't help.
    3.) For some reason, when I move another window (AIM, the console window, etc...) over my Swing window, it "erases" (turns gray, just wipes clean) the part where I have my squares that have pieces.
    What's weird is that:
    The border pieces (err.. my one visible corner piece from my second problem) don't get wiped, and some debugging text and JLabels (in a different JPanel) are fine. I don't think the JPanel matters though; the border pieces and the playing squares (which get wiped) are in the same JPanel and same array of squares.
    repaint(); also erases ALL of my playing squares, whereas moving a window over them would only erase the part that the window covered.
    Also, I added a mouseListener so that whenever I move the mouse over a square, it changes the image (to a tinted version, so you know the mouse is over it) and when you move the mouse away, it returns to normal. However, if I wildly swing the mouse around the area, it seems to lock up and freeze for a few seconds. Is there anything I can do to prevent this??
    Thanks in advance.

    It is hard to tell what your problems are without any code at all (I saw your images, but that doesn't make it easy to see what is wrong in your code). If you do post code, please use code tags (see button above posting box).
    I've seen your MouseListener problem before--we had the exact same issue in our code at work. It would freeze up while it processed all of the mouse events (unbearably slow). I'm not at work right now, so I don't recall how it was fixed. Essentially, you need to only process the event periodically. You need to only update the image if the mouse switches squares. Or, only update the image if the distance from the last mouse event is more than some specified amount. We might also have checked the time difference between mouse events before processing a new one. I could look at the code at work tomorrow, if you are still having trouble.

Maybe you are looking for

  • Exporting WMF's to Microsoft Word and preserving anchors toggles

    I'm creating artwork (lineart) in Illustrator CS3, and would like to place the art into a Microsoft Word 2003 text document and when completed with the project save the word document as a pdf. So that in the end we can open the pdf and be able to edi

  • Payment Wizard SAP B1 2005 PL23 Issues

    Hey Friends, I asked about this issue twice already but I still don't have any solution yet. When I do the Payment runs, the payment wizard either: Randomly executes only some of the recomended payments or does not execute any of the recomended payme

  • Error parsing! Element "process" must have no character [children],

    hi, Please does any1 know how to fix this error ? when deploying the poroject i got : XML parsing failed because Element "process" must have no character [children], because the types content type is element-only......" when double clicking on the ab

  • Keystore

    hi how do I create keystore file when my default keystore file(jks) does not exist? regards neda

  • Functional location not reflected in connection object

    HI... I created a functional location in the plant maintanence module..however when i try to check this from the connection object SAP gives me an error sayin the Location does not belon to IS type C(connection Object). during FL creation i had speci