Solved

How to display image in Java?

Posted on 2003-11-19
12
913 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
Comment Utility
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
Comment Utility
0
 
LVL 3

Expert Comment

by:InNoCenT_Ch1ld
Comment Utility
how bout calling the JPanel paintComponent method?? can it work?
0
 
LVL 15

Expert Comment

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

Author Comment

by:lotus03
Comment Utility
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
Comment Utility
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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 15

Expert Comment

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

Author Comment

by:lotus03
Comment Utility
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
Comment Utility
>> 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
Comment Utility
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
Comment Utility
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
Comment Utility
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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

771 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now