Solved

How to display image in Java?

Posted on 2003-11-19
12
924 Views
Last Modified: 2012-06-27
I would like to build a program in Java that can choose image file from folder and display it in the pane..how to do this?
thank u.
0
Comment
Question by:lotus03
12 Comments
 
LVL 2

Expert Comment

by:Tols
ID: 9785121
This is sample code:


.....
ImageIcon image = new ImageIcon("someimage.gif");
JLabel label = new JLabel();
label.setIcon(image);
.....


:)
0
 
LVL 15

Assisted Solution

by:Javatm
Javatm earned 60 total points
ID: 9785135
0
 
LVL 3

Expert Comment

by:InNoCenT_Ch1ld
ID: 9785259
how bout calling the JPanel paintComponent method?? can it work?
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 15

Expert Comment

by:jimmack
ID: 9787230
To choose your file, use a JFileChooser (in the javax.swing package)
0
 

Author Comment

by:lotus03
ID: 9787364
thanks Javatm..
I have implement it in my program... but why the image can't be inserted?
When I try to insert Image, it will pop out a dialog box .. after I chosed the selected image file.. and click Open.. it seems like nothing happen.. coz the image still haven't being inserted.. why?
Anything wrong with my code? Thanks.

Below is my code:
============================
package Editor1;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

import java.io.*;
import java.util.*;

import javax.swing.text.*;
import javax.swing.event.*;
import javax.swing.border.*;
import javax.swing.text.html.*;

public class UI1 extends JFrame {
  public static final String APP_NAME = "JSP Editor";
  protected JTextPane m_editor;
  protected StyleSheet m_context;
  protected HTMLDocument m_doc;
  protected HTMLEditorKit m_kit;
 // protected SimpleFilter m_htmlFilter;
  protected JToolBar m_toolBar;

  protected JFileChooser m_chooser;
  protected File  m_currentFile;
  protected boolean m_textChanged = false;


  public UI1() {
    super(APP_NAME);
    m_editor = new JTextPane();
    m_kit = new HTMLEditorKit();
    m_editor.setEditorKit(m_kit);

    JScrollPane ps = new JScrollPane(m_editor);
    getContentPane().add(ps, BorderLayout.CENTER);



    try {
      jbInit();
    }
    catch(Exception e) {
      e.printStackTrace();
    }
    JMenu fileMenu = new JMenu( "File" );
    fileMenu.setMnemonic( 'F' );

    //JMenuItem newItem = new JMenuItem("New");
  //  newItem.setMnemonic('n');
    //fileMenu.add(newItem);

    ImageIcon iconNew = new ImageIcon("New16.gif");
                Action actionNew = new AbstractAction("New", iconNew) {
                        public void actionPerformed(ActionEvent e) {
                                if (!promptToSave())
                                        return;
                                newDocument();
                        }
                };
                JMenuItem newItem = new JMenuItem(actionNew);
               newItem.setMnemonic('n');
                newItem.setAccelerator(KeyStroke.getKeyStroke(
                        KeyEvent.VK_N, InputEvent.CTRL_MASK));
                fileMenu.add(newItem);

JMenuItem openItem = new JMenuItem("Open");
    openItem.setMnemonic('O');
    fileMenu.add(openItem);
    JMenuItem closeItem = new JMenuItem("Close");
    closeItem.setMnemonic('L');
    fileMenu.add(closeItem);
    fileMenu.addSeparator();

    JMenuItem saveItem = new JMenuItem("Save");
    saveItem.setMnemonic('S');
    fileMenu.add(saveItem);
    JMenuItem saveAsItem = new JMenuItem("Save As");
    saveAsItem.setMnemonic('A');
    fileMenu.add(saveAsItem);
    fileMenu.addSeparator();

    JMenuItem printCodeItem = new JMenuItem("Print Code");
    printCodeItem.setMnemonic('P');
    fileMenu.add(printCodeItem);
    JMenuItem previewItem = new JMenuItem("Preview");
    previewItem.setMnemonic('R');
    fileMenu.add(previewItem);
    fileMenu.addSeparator();

    JMenuItem exitItem = new JMenuItem("Exit");
    exitItem.setMnemonic('T');
    fileMenu.add(exitItem);

    JMenuBar bar = new JMenuBar();
    setJMenuBar(bar);
    bar.add(fileMenu);

    JMenu editMenu = new JMenu( "Edit" );
    editMenu.setMnemonic( 'E' );

    JMenuItem cutItem = new JMenuItem("Cut");
    cutItem.setMnemonic('X');
    editMenu.add(cutItem);
    JMenuItem copyItem = new JMenuItem("Copy");
    copyItem.setMnemonic('C');
    editMenu.add(copyItem);
    JMenuItem pasteItem = new JMenuItem("Paste");
    pasteItem.setMnemonic('V');
    editMenu.add(pasteItem);

    bar.add(editMenu);

    JMenu viewMenu = new JMenu( "View" );
    viewMenu.setMnemonic( 'I' );

    JMenuItem codeItem = new JMenuItem("Code");
    viewMenu.add(codeItem);
    JMenuItem designItem = new JMenuItem("Design");
    viewMenu.add(designItem);

    bar.add(viewMenu);

    JMenu insertMenu = new JMenu( "Insert" );

    JMenuItem imageItem = new JMenuItem("Image");
    insertMenu.add(imageItem);
    imageItem.addActionListener(new ActionListener() {
      public void actionPerformed (ActionEvent e) {
        doInsertImageCommand();
      }
    });
   bar.add(insertMenu);
 }

 public void doInsertImageCommand() {
   JFileChooser chooser = new JFileChooser();
   int status = chooser.showOpenDialog(this);
   if (status == JFileChooser.APPROVE_OPTION) {
     File file = chooser.getSelectedFile();
     Icon icon = new ImageIcon (file.getAbsolutePath());
     m_editor.insertIcon (icon);
   }
 }

 protected void newDocument() {
                m_doc = (HTMLDocument)m_kit.createDefaultDocument();
                m_context = m_doc.getStyleSheet();

                m_editor.setDocument(m_doc);
                m_currentFile = null;
                setTitle(APP_NAME+" ["+getDocumentName()+"]");

                SwingUtilities.invokeLater(new Runnable() {
                        public void run() {
                                m_editor.scrollRectToVisible(new Rectangle(0,0,1,1));
                                m_doc.addDocumentListener(new UpdateListener());
                                m_textChanged = false;
                        }
                });
        }
        protected void openDocument() {
                    if (m_chooser.showOpenDialog(UI1.this) !=
                            JFileChooser.APPROVE_OPTION)
                            return;
                    File f = m_chooser.getSelectedFile();
                    if (f == null || !f.isFile())
                            return;
                    m_currentFile = f;
                    setTitle(APP_NAME+" ["+getDocumentName()+"]");

                    UI1.this.setCursor(
                            Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
                    // Can't do this in thread - Pavel
                    try {
                            InputStream in = new FileInputStream(m_currentFile);
                            m_doc = (HTMLDocument)m_kit.createDefaultDocument();
                            m_kit.read(in, m_doc, 0);
                            m_context = m_doc.getStyleSheet();
                            m_editor.setDocument(m_doc);
                            in.close();
                    }
                    catch (Exception ex) {
                            showError(ex, "Error reading file "+m_currentFile);
                    }
                    UI1.this.setCursor(Cursor.getPredefinedCursor(
                            Cursor.DEFAULT_CURSOR));

                    SwingUtilities.invokeLater(new Runnable() {
                            public void run() {
                                    m_editor.setCaretPosition(1);
                                    m_editor.scrollRectToVisible(new Rectangle(0,0,1,1));
                                    m_doc.addDocumentListener(new UpdateListener());
                                    m_textChanged = false;
                            }
                    });
            }

            class UpdateListener implements DocumentListener {

                public void insertUpdate(DocumentEvent e) {
                        m_textChanged = true;
                }

                public void removeUpdate(DocumentEvent e) {
                        m_textChanged = true;
                }

                public void changedUpdate(DocumentEvent e) {
                        m_textChanged = true;
                }
        }


            protected boolean promptToSave() {
                         if (!m_textChanged)
                                 return true;
                         /*int result = JOptionPane.showConfirmDialog(this,
                                 "Save changes to "+getDocumentName()+"?",
                                 APP_NAME, JOptionPane.YES_NO_CANCEL_OPTION,
                                 JOptionPane.INFORMATION_MESSAGE);
                         switch (result) {
                         case JOptionPane.YES_OPTION:
                                 if (!saveFile(false))
                                         return false;
                                 return true;
                         case JOptionPane.NO_OPTION:
                                 return true;
                         case JOptionPane.CANCEL_OPTION:
                                 return false;
                         }    */
                         return true;
                 }


  protected String getDocumentName() {
                               return m_currentFile==null ? "Untitled" :
                                       m_currentFile.getName();
                       }

public void showError(Exception ex, String message) {
                                       ex.printStackTrace();
                                       JOptionPane.showMessageDialog(this,
                                               message, APP_NAME,
                                               JOptionPane.WARNING_MESSAGE);
                               }


   public static void main(String[] args) {
    // UI1 frame1 = new UI1();
    // frame1.show();


   JFrame.setDefaultLookAndFeelDecorated(true);
   JDialog.setDefaultLookAndFeelDecorated(true);

   UI1 frame1 = new UI1();
   frame1.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
   frame1.setVisible(true);

   }



   private void jbInit() throws Exception {
      setSize(new Dimension(800, 600));
      setVisible(true);
      this.setResizable(false);
      this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
      show();
  }
}
=================================================
0
 
LVL 15

Expert Comment

by:Javatm
ID: 9791048
Try to implement this 1st w/o package ok :)
Also try different kind of image format like .jpg .gif & other format.
Checked on what version of jdk do you use.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
import java.io.*;
import java.util.*;

public class Formatter extends JFrame {
  final static int WIDTH = 400;
  final static int HEIGHT = 300;
  StyledDocument doc;
  JTextPane pane;
  JLabel statusInfo;

  public Formatter(String lab) {
    super (lab);

    // Get ContentPane
    Container c = getContentPane();

    // Setup Status Message Area
    statusInfo = new JLabel();
    c.add (statusInfo, BorderLayout.SOUTH);

    // Setup Text Pane
    doc = new DefaultStyledDocument();
    pane = new JTextPane (doc);

    // Place in JScrollPane
    JScrollPane sp = new JScrollPane (pane);
    c.add(sp, BorderLayout.CENTER);

    // Setup Menus
    JMenuBar menuBar = new JMenuBar();
    setJMenuBar (menuBar);

    // Setup File Menu
    JMenu file = new JMenu ("File");
    JMenuItem item;
    file.add (item = new JMenuItem ("New"));
    item.addActionListener (new ActionListener() {
      public void actionPerformed (ActionEvent e) {
        doNewCommand();
      }
    });
    file.add (item = new JMenuItem ("Open"));
    item.addActionListener (new ActionListener() {
      public void actionPerformed (ActionEvent e) {
        doOpenCommand();
      }
    });
    file.add (item = new JMenuItem ("Load Text"));
    item.addActionListener (new ActionListener() {
      public void actionPerformed (ActionEvent e) {
        doLoadCommand();
      }
    });
    file.add (item = new JMenuItem ("Save"));
    item.addActionListener (new ActionListener() {
      public void actionPerformed (ActionEvent e) {
        doSaveCommand();
      }
    });
    file.addSeparator();
    file.add (item = new JMenuItem ("Close"));
    item.addActionListener (new ActionListener() {
      public void actionPerformed (ActionEvent e) {
        doCloseCommand();
      }
    });
    menuBar.add (file);

    // Setup Color Menu
    JMenu color = new JMenu("Color");
    color.add (item = new JMenuItem ("Red"));
    item.setIcon (new ColoredBox(Color.red));
    item.addActionListener (new
      StyledEditorKit.ForegroundAction (
        "set-foreground-red", Color.red));
    color.add (item = new JMenuItem ("Orange"));
    item.setIcon (new ColoredBox(Color.orange));
    item.addActionListener (new
      StyledEditorKit.ForegroundAction (
        "set-foreground-orange", Color.orange));
    color.add (item = new JMenuItem ("Yellow"));
    item.setIcon (new ColoredBox(Color.yellow));
    item.addActionListener (new
      StyledEditorKit.ForegroundAction (
        "set-foreground-yellow", Color.yellow));
    color.add (item = new JMenuItem ("Green"));
    item.setIcon (new ColoredBox(Color.green));
    item.addActionListener (new
      StyledEditorKit.ForegroundAction (
        "set-foreground-green", Color.green));
    color.add (item = new JMenuItem ("Blue"));
    item.setIcon (new ColoredBox(Color.blue));
    item.addActionListener (new
      StyledEditorKit.ForegroundAction (
        "set-foreground-blue", Color.blue));
    color.add (item = new JMenuItem ("Magenta"));
    item.setIcon (new ColoredBox(Color.magenta));
    item.addActionListener (new
      StyledEditorKit.ForegroundAction (
        "set-foreground-magenta", Color.magenta));
    color.add (item = new JMenuItem ("Custom Color"));
    item.addActionListener (new ActionListener() {
      public void actionPerformed (ActionEvent e) {
        doColorCommand();
      }
    });

    menuBar.add (color);

    // Setup Font Menu
    JMenu font = new JMenu("Font");
    font.add (item = new JMenuItem ("12"));
    item.addActionListener (new
      StyledEditorKit.FontSizeAction (
        "font-size-12", 12));
    font.add (item = new JMenuItem ("24"));
    item.addActionListener (new
      StyledEditorKit.FontSizeAction (
        "font-size-24", 24));
    font.add (item = new JMenuItem ("36"));
    item.addActionListener (new
      StyledEditorKit.FontSizeAction (
        "font-size-36", 36));
    font.addSeparator();
    font.add (item = new JMenuItem ("Serif"));
    item.setFont (new Font ("Serif", Font.PLAIN, 12));
    item.addActionListener (new
      StyledEditorKit.FontFamilyAction (
        "font-family-Serif", "Serif"));
    font.add (item = new JMenuItem ("SansSerif"));
    item.setFont (new Font ("SansSerif", Font.PLAIN, 12));
    item.addActionListener (new
      StyledEditorKit.FontFamilyAction (
        "font-family-SansSerif", "SansSerif"));
    font.add (item = new JMenuItem ("Monospaced"));
    item.setFont (new Font ("Monospaced", Font.PLAIN, 12));
    item.addActionListener (new
      StyledEditorKit.FontFamilyAction (
        "font-family-Monospaced", "Monospaced"));
    font.addSeparator();
    font.add (item = new JMenuItem ("Bold"));
    item.setFont (new Font ("Serif", Font.BOLD, 12));
    item.addActionListener (
      new StyledEditorKit.BoldAction ());
    font.add (item = new JMenuItem ("Italic"));
    item.setFont (new Font ("Serif", Font.ITALIC, 12));
    item.addActionListener (
      new StyledEditorKit.ItalicAction ());
/* Add once FontChooser is available
    font.addSeparator();
    font.add (item = new JMenuItem ("Custom Font"));
    item.addActionListener (new ActionListener() {
      public void actionPerformed (ActionEvent e) {
        doFontCommand();
      }
    });
*/
    menuBar.add (font);

    // Setup Insert Menu
    JMenu insert = new JMenu("Insert");
    insert.add (item = new JMenuItem ("Image File"));
    item.addActionListener (new ActionListener() {
      public void actionPerformed (ActionEvent e) {
        doInsertImageCommand();
      }
    });
    menuBar.add (insert);
  }

  public static void main (String args[]) {
    Formatter frame = new Formatter("Mini Text Editor");
    frame.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {System.exit(0);}
    });
    frame.setSize(WIDTH, HEIGHT);
    frame.setVisible(true);
  }

  public void doNewCommand() {
    pane.setStyledDocument (doc = new DefaultStyledDocument());
  }

  public void doCloseCommand() {
    System.exit (0);
  }

  public void doOpenCommand() {
    try {
      FileInputStream fis = new FileInputStream ("doc.ser");
      ObjectInputStream ois = new ObjectInputStream (fis);
      doc = (StyledDocument)ois.readObject();
      ois.close();
      pane.setStyledDocument (doc);
      validate();
      statusInfo.setText ("Reloaded from disk");
    } catch (Exception e) {
      statusInfo.setText ("Unable to reload");
      e.printStackTrace();
    }
  }

  public void doSaveCommand() {
    try {
      FileOutputStream fos = new FileOutputStream ("doc.ser");
      ObjectOutputStream oos = new ObjectOutputStream (fos);
      oos.writeObject (doc);
      oos.flush();
      oos.close();
      statusInfo.setText ("Saved to disk");
    } catch (IOException e) {
      statusInfo.setText ("Unable to save");
      e.printStackTrace();
    }
  }

  public void doLoadCommand() {
    String msg;
    JFileChooser chooser = new JFileChooser();
    int status = chooser.showOpenDialog(this);
    if (status == JFileChooser.APPROVE_OPTION) {
      char data[];
      final Runnable doWaitCursor = new Runnable() {
        public void run() {
          setCursor (Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        }
      };
      Thread appThread = new Thread() {
        public void run() {
          try {
             SwingUtilities.invokeAndWait(doWaitCursor);
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      };
      appThread.start();
      File f = chooser.getSelectedFile();
      try {
        // Clear out current document
        pane.setStyledDocument (doc = new DefaultStyledDocument());
        // Read in text file
        FileReader fin = new FileReader (f);
        BufferedReader br = new BufferedReader (fin);
        char buffer[] = new char[4096];
        int len;
        while ((len = br.read (buffer, 0, buffer.length)) != -1) {
          // Insert into pane
          doc.insertString(doc.getLength(),
            new String (buffer, 0, len), null);
        }
        statusInfo.setText ("Loaded: " + f.getName());
      } catch (BadLocationException exc) {
        statusInfo.setText ("Error loading: " + f.getName());
      } catch (FileNotFoundException exc) {
        statusInfo.setText ("File Not Found: " + f.getName());
      } catch (IOException exc) {
        statusInfo.setText ("IOException: " + f.getName());
      }
      final Runnable undoWaitCursor = new Runnable() {
        public void run() {
        setCursor (Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
        }
      };
      appThread = new Thread() {
        public void run() {
          try {
             SwingUtilities.invokeAndWait(undoWaitCursor);
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      };
      appThread.start();
    }
  }

/*
  public void doFontCommand() {
    Font font = FontChooser.ask (
      this, "Change font", getFont(), null);
    if (font != null) {
      MutableAttributeSet attr = new SimpleAttributeSet();
      StyleConstants.setFontFamily (attr, font.getFamily());
      StyleConstants.setFontSize (attr, font.getSize());
      StyleConstants.setBold (attr, font.isBold());
      StyleConstants.setItalic (attr, font.isItalic());
      pane.setCharacterAttributes(attr, false);
    }
  }
*/

  public void doColorCommand() {
    Color color = JColorChooser.showDialog(
      this, "Color Chooser", Color.cyan);
    if (color != null) {
      MutableAttributeSet attr = new SimpleAttributeSet();
      StyleConstants.setForeground(attr, color);
      pane.setCharacterAttributes(attr, false);
    }
  }

  public void doInsertImageCommand() {
    JFileChooser chooser = new JFileChooser();
    int status = chooser.showOpenDialog(this);
    if (status == JFileChooser.APPROVE_OPTION) {
      File file = chooser.getSelectedFile();
      Icon icon = new ImageIcon (file.getAbsolutePath());
      pane.insertIcon (icon);
    }
  }

  class ColoredBox implements Icon {
    Color color;
    public ColoredBox (Color c) {
      color = c;
    }
    public void paintIcon (Component c, Graphics g, int x, int y) {
      g.setColor(color);
      g.fillRect (x, y, getIconWidth(), getIconHeight());
    }
    public int getIconWidth() {
      return 10;
    }
    public int getIconHeight() {
      return 10;
    }
  }
}
0
 
LVL 15

Expert Comment

by:Javatm
ID: 9791079
" Sometimes debuging codes can be hard but the one who always give dedication wins. " 
  Javatm
0
 

Author Comment

by:lotus03
ID: 9793103
I have try the one withot package, is ok.. I mean it's can insert image..
But then after I try to implement in my package.. and inserting the same image .. it can't.. why?
thanks..
0
 
LVL 15

Expert Comment

by:Javatm
ID: 9794108
>> how to do this?
     I just gave you a sample :)
     fixing the codes is a seperate question
     hope you understand
0
 
LVL 16

Accepted Solution

by:
gnoon earned 20 total points
ID: 9794163
iam not sure what happened but after i comment the command m_editor.setEditorKit(m_kit);, it works fine.

public UI1() {
    super(APP_NAME);
    m_editor = new JTextPane();
    e_kit = m_editor.getEditorKit();
    m_kit = new HTMLEditorKit();
    //m_editor.setEditorKit(m_kit); <--- comment this

i think it's better to use the default EditorKit of JTextPane than HTMLEditorKit.
0
 

Author Comment

by:lotus03
ID: 9794870
Thanks everyone!!
Actually the credits should go to evryone since you all really have gave me a big help on it..
but since this question should based on "How to insert image.." so, Javatm get most of the point.. but Can gnoon drop a message in my next question , that is "What's wrong with my Java code..", so that I could give u the other points.. Thank you!!
0
 

Author Comment

by:lotus03
ID: 9794924
gnoon, pls go here and drop a comment there and get extra points for your help.. Thanks a lot..
http://www.experts-exchange.com/Programming/Programming_Languages/Java/Q_20804725.html
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
arguments to jar 5 39
Adding multiple JVM environments to RedHat 6 7 69
Bot application - advice 3 58
running on tomcat not jboss eap 7.0 3 28
INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

685 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question