Open image in Swing Application

Hi,
I'm having trouble getting an image to open into my swing application and I cant figure out whats wrong. In response to selecting the "Open" button or menu item a JFileChooser opens up and i select an image but the image doesn't actually load. If anyone could help i'd really appreciate it.
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.swing.border.*;
import javax.imageio.*;
class PhotoEditor extends JPanel implements ActionListener {
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
    JMenu imageMenu, effectsMenu;
    JFileChooser fc = new JFileChooser();
    BufferedImage img = null;
       public JMenuBar createMenuBar() {     
     JMenuBar menuBar = new JMenuBar();
    /* Build the first menu: */
    JMenu fileMenu = new JMenu("File");
    menuBar.add(fileMenu);
    fileMenu.setMnemonic(KeyEvent.VK_F);
    //a group of JMenuItems under the File option:
        String[] menuItems1 = {"Open", "Save","Save As..", "Close"};
    String[] menuIcons1 = {"Open.gif", "Save.gif", "", ""};
    for (int i = 0; i<menuItems1.length; i++)
              JMenuItem fileMI = new JMenuItem(menuItems1, new ImageIcon(menuIcons1[i]));
          fileMI.addActionListener(this);
          fileMenu.add(fileMI);
//adding a separator to the drop down menu list
fileMenu.addSeparator();
JMenuItem exitMI = new JMenuItem("Exit", new ImageIcon("Exit.gif"));
exitMI.addActionListener(this);
fileMenu.add(exitMI);
/* Code which builds all the menu here */
return menuBar;
     public JToolBar createToolBar() {     
     JToolBar toolB = new JToolBar(FlowLayout.LEFT);
toolB.setLayout(new FlowLayout());
// contentPane.add(toolB, "North");
JButton newButton = new JButton(new ImageIcon("new24.gif"));
newButton.addActionListener(this);
toolB.add(newButton);
newButton.setToolTipText("New");
newButton.setActionCommand("New");
//adding a separator to the drop down menu list
toolB.addSeparator();
JButton openButton = new JButton(new ImageIcon("open24.gif"));
openButton.addActionListener(this);
toolB.add(openButton);
openButton.setToolTipText("Open");
     openButton.setActionCommand("Open");
/* More code building the toolbar*/
return toolB;
     public void actionPerformed(ActionEvent e) {
Object eventSource = e.getSource();
if ((eventSource instanceof JMenuItem) || (eventSource instanceof JButton));{
String label = (String) e.getActionCommand();
//Sets up the Action Listeners
if (label.equals("Exit")) {
System.exit(0);
// Closes application
else if (label.equals("Open")) {
     openImage();
/* More codes for each button or menu item */
protected void openImage() {
          int returnVal = fc.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
     try {
               img = ImageIO.read(file);
                    catch (IOException e1) {
public void paintComponent(Graphics g) {
     super.paintComponent(g);
g.drawImage(img, 500, 500, null);
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("Photo Editor");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create a main label to put in the content pane.
JLabel main = new JLabel();
// main.setOpaque(true);
// main.setBackground(new Color(128, 128, 128));
main.setPreferredSize(new Dimension(800, 600));
//Set the menu bar and add the label to the content pane.
PhotoEditor mainmenu = new PhotoEditor();
frame.setJMenuBar(mainmenu.createMenuBar());
     frame.getContentPane().add(mainmenu.createToolBar(), BorderLayout.PAGE_START);
frame.getContentPane().add(main, BorderLayout.CENTER);
//Display the window.
frame.pack();
frame.setVisible(true);
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();

Your PhotoEditor class extends JPanel. In that class you override paintComponent(). But you never add the panel to the GUI, so that method is never invoked.
Personally I would have the PhotoEditor class extend JFrame. Then in the constructor you build all the components for the frame
a) build the menu
b) build the toolbar
Then I would create a PhotoPanel class that you extend and override the paintComponent(). Then you add this panel to the GUI as your main panel.
For a simple example of drawing a background image on a panel search the forum for my BackgroundImage example.

Similar Messages

  • Open PDF in Swing Application

    Hi Java GURUS
    Firts of all, I would like to start with my introduction. My self Prashant Kadam. Right now i am developing a small system in java for my organization. This application is realted with art. And here we are dealing with PDF files. So application needs to open a PDF file within the frame / applet.
    I have tried my level best to creack this problem. But still i am unable to solve it. I will be thank full to you, if i get solution from your end. I have also tried with some APIS. but they don't allow me to draw on this.
    Thanks in adavnce
    Waiting for a reply
    Regards
    Prashant Kadam

    Hello,
    The following should help:
    http://sourceforge.net/projects/itext/
    http://www.oreillynet.com/pub/d/1305
    http://sourceforge.net/projects/gnujpdf/
    http://sourceforge.net/projects/pdfbox/
    Best regards,
    Bert Szoghy
    Quadmore Software Services
    http://www.quadmore.com
    "Home of Java Rollout for Windows"

  • Problem in Opening HTML Page in Internet Explorer from my Swing Application

    Hi,
    I am opening a HTML file in Internet Explorer from my swing application.I am using the code given below
    private final static String WIN_FLAG = "url.dll,FileProtocolHandler";
    private final static String WIN_PATH = "rundll32";
    String cmd = WIN_PATH + " " + WIN_FLAG + " " + url;
    // url is HTML file Path
    Process p = Runtime.getRuntime().exec( cmd );
    Here there are two things i need to address ...
    1)The HTML file is opening up,but it always opens behind the swing application,that makes me every time to maximize the HTML file after it being opened up.I want to open it in front of the Swing Application.I need to implement "Always On Top" functionality for the html page.
    2)Whenever i trigger action to open different HTML page,it opens in new Internet Explorer window.
    I need to open it in same IE window.
    how to solve out these problems ??? any help would be greatly appreciated .Thanks in advance.
    - Manikandan

    any idea about this ????

  • Help Needed in opening a HTML File from swing application

    Hi,
    I am opening a HTML file in Internet Explorer from my swing application.
    I am using the code given below
    private final static String WIN_FLAG = "url.dll,FileProtocolHandler";
    private final static String WIN_PATH = "rundll32";
    String cmd = WIN_PATH + " " + WIN_FLAG + " " + url;
    // url is HTML file Path
    Process p = Runtime.getRuntime().exec( cmd );
    The HTML file is opening up,but it always opens behind the swing application,that makes me every time to maximize the HTML file after it being opened up.
    I want to open it in front of the Swing Application.
    Any Help Please ?
    - Manikandan

    Check your Application's JFrame properties (may be ur Frame is set to be in top position ,always),and also check running your application in some other OS.

  • Image resize problem in Swing Application

    Hi All
    I need a help on resizing and adjustment of Image in Swing application.
    I am developing a Swing Application. There I am displaying a image on header.
    I am finding it difficult to manage the image, as I want the image to perfectly fit horizontal bounds(Even on window resize).
    The current code given below is unable to do so.. Even it's not able to fit the horizontal bounds by default.
    ========================================
    //code for image starts
            BufferedImage myPicture;
            JLabel picLabel = null;
            try {
                 myPicture = ImageIO.read(new File("artes_header.png"));
                    picLabel = new JLabel(new ImageIcon(myPicture));
              } catch (Exception e) {
            GridBagLayout gLayout = new GridBagLayout();
            getContentPane().setLayout(gLayout);
            GridBagConstraints c = new GridBagConstraints();
            c.gridx = 1;
            c.gridy = 1;
            c.weightx = 1;
            c.fill = GridBagConstraints.BOTH;
            c.insets = new Insets(0, 0, 0, 0);
            panelTop.setBackground(Color.white);
            getContentPane().add(picLabel, c);
            c.gridx = 1;
            c.gridy = 2;
            c.weightx = 1;
            c.weighty = 1;
            getContentPane().add(tabPane, c);========================================
    Kindly anyone help me solve the same issue.
    Many thanks in advance.
    Regards,
    Gaurav
    Edited by: user7668872 on Jul 31, 2011 6:25 AM
    Edited by: user7668872 on Aug 4, 2011 3:56 AM

    Your questions doesnt make a whole lot of sence so not sure if this is what you want...
    This is a class to display an image on a jpanel. You can then use layout managers to make sure it is centrally alligned
    import java.awt.*;
    import javax.swing.*;
    import java.awt.image.BufferedImage;
    import javax.imageio.ImageIO;
    import java.io.*;
    class testImagePanel{
        public static void main(String[] args){
            BufferedImage image = null;
            ImagePanel imagePanel = null;
            try{
                image = ImageIO.read(new File("image.jpg"));
                imagePanel = new ImagePanel(image);
                imagePanel.setLayout(new BorderLayout());
            }catch(IOException  e){
                 System.err.println("Error trying to read in image "+e);
            JFrame frame = new JFrame("Example");
            frame.add(imagePanel);
            frame.pack();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);               
    public class ImagePanel extends JPanel {
        private BufferedImage image;
        private Dimension size;
        public ImagePanel(BufferedImage image) {
            this.image = image;
            this.size = new Dimension();
            size.setSize(image.getWidth(), image.getHeight());
            this.setBackground(Color.WHITE);
        @Override
        protected void paintComponent(Graphics g) {
            // Center image in this component.
            int x = (getWidth() - size.width)/2;
            int y = (getHeight() - size.height)/2;
            g.drawImage(image, x, y, this);
        @Override
        public Dimension getPreferredSize() { return size; }
    }

  • Swing application w/images

    Hello,
    Java Image I/O provides ways to load and save images into swing applications. Does anyone know of other APIs? We're using Spring/RMI with a Swing client. The images would be stored on the server by index or something. Whats the best approach to write such an application? something that will provide the most flexibility (multiple image formats... viewing, saving, printing etc.) . thanks

    Thanks for the response. Can i incorporate the ability to view TurboCad sketches (.tcw files) using this API?

  • Keyboard shortcut for cycling through open images

    hi guys, i am working in a PC Photoshop now. Which is the Keyboard Shortcut for cycling through open images? Where i can change it if i want it? I mean clying through open images and not applications which is Control+TAB.
    Thanks for any info!
    S

    Actually Ctrl+Tab is the photoshop windows keyboard shortcut for cycling through open images.
    Does that not work for you?
    MTSTUNER

  • Launching Browser From Swing Application - Help Needed

    Hi,
    I am opening a HTML file in Internet Explorer from my swing application.
    I am using the code given below
    private final static String WIN_FLAG = "url.dll,FileProtocolHandler";
    private final static String WIN_PATH = "rundll32";
    String cmd = WIN_PATH + " " + WIN_FLAG + " " + url;
    // url is HTML file Path
    Process p = Runtime.getRuntime().exec( cmd );
    The HTML file is opening up,but it always opens behind the swing application,that makes me every time to maximize the HTML file after it being opened up.
    I want to open it in front of the Swing Application.
    Any Help Please ?
    - Manikandan

    Browser Utility - Class to launch a URL in a web browser in
    a platform independent manner. Includes an optional swing
    GUI allowing user customization. [Open Source - GPL]
    http://ostermiller.org/utils/Browser.html
    BrowserLauncher - Open the system web browser with
    particular attention paid to various Macintosh systems.
    (Freeware)
    http://browserlauncher.sourceforge.net/
    Java World - With a little platform-specific Java code, you
    can easily use your system's default browser to display any
    URL in Windows or Unix.
    http://www.javaworld.com/javaworld/javatips/jw-javatip66.html
    JConfig - Class Libraries that allow a URL to be launched in
    a browser on Windows, Unix, or Macintosh. [Commercial]
    http://www.tolstoy.com/samizdat/jconfig.html
    Apple - MRJFileUtils.openURL() not implemented in Mac OS X.
    http://developer.apple.com/techpubs/macosx/ReleaseNotes/JavaGMWebReleaseNotes.html#MRJToolkit
    Apple - How one would open a URL in a web browser on a
    Macintosh.
    http://developer.apple.com/qa/java/java12.html

  • Is there any Open source Reporting Toll for using in swing application ?

    Is there any reporting system like crystal report or any thing for report generation. Using JTable class it is so time taking job. I have downloaded Eclipse with crystal report embedded, and have created a report but can not integrate the report with JFrame with any menu item action. All the code i got releted to JSP. and few code get that are using
    //Crystal Java Reporting Component (JRC) imports.
    import com.crystaldecisions.reports.sdk.*;
    import com.crystaldecisions.sdk.occa.report.lib.*;
    //Java Imports.
    import javax.swing.*;
    public class JRCViewReport {
         private static final String REPORT_NAME = "JRCViewReport.rpt";
         public static void launchApplication() {
              try {
                   //Open report.
                   ReportClientDocument reportClientDoc = new ReportClientDocument();
                   reportClientDoc.open(REPORT_NAME, 0);
                   //Launch JFrame that contains the report viewer.
                   new ReportViewerFrame(reportClientDoc);          
              catch(ReportSDKException ex) {     
                   System.out.println(ex);
              catch(Exception ex) {
                   System.out.println(ex);               
         public static void main(String [] args) {
              //Event-dispatching thread to run Swing GUI.  This is good practice for Swing applications
              //to help ensure that events are dispatched in a predicatable order.
              //For more information on using this method, refer to the SUN site below for more details:
              //http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        //Hand-off to worker function to start application.
                        launchApplication();                    
    }Also there is one file ReportViewerFrame.java
    but the error is "*com.crystaldecisions.reports.sdk*" not found
    Please help ..........................................................

    I have already use Jasper Report. Thakns a lot for your suggestion. Now I think i have solved your problem...... View the code.. this code will not open the JasperViewer but from the background it will be printed and after calling the printing function you can save a data in the database ------------------------
    JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
            Connection con = Database.getConnection(); // your database connection
            jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, con);
            for(int i=0;;i++) { //print all pages
                try{
                    JRPrinterAWT.printPages(jasperPrint,i,i,false);
                }catch(Exception e) {
                    break;
            }

  • Error 1003 occurred at Open VI Reference in Dist Copy Non-VI Files.vi- Dist Build LLB Image.vi- Dist Build App Image.vi- Build Application.vi

    When trying to build  an application using labview 7.1 and windows XP,  I get the error
    Error 1003 occurred at Open VI Reference in Dist Copy Non-VI Files.vi->Dist Build LLB Image.vi->Dist Build App Image.vi->Build Application.vi
    I've tried the crtl-shift-run as well as  a mass compile and I still get the error.
    Any ideas?
    Thanks,
    Mike

    Hopefully this thread, or this KB article might help.
    It seems like this could come from a lot of things, but there's suggestions in those which might lead you in the right direction
    Message Edited by Day on 09-22-2006 02:07 PM

  • How can I use the open in " My application" option to open image attachments.?

    How can I use the open in " My application" option to open image attachments.?
    I am trying to use the uti's given in the apple docs but just unable to do it however its working perfect for pdf and rtf files.
    please help needed urgent.   

    Perhaps you should Contact the iTunes Store Customer Service:
    Apple - Support - iTunes Store - Contact Us

  • Opening a PDF file from a swing application in MAC

    HI everyone,
    Actually I am developing a swing application which should be executable in both windows and Mac (even other) platformes. In my panel I have an icon which leads to a pdf file. I saw in the following thread:
    http://forum.java.sun.com/thread.jspa?forumID=17&threadID=617767
    that we can use
    Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + file);to open what ever file in windows. I want to know what should I do if this application is running on Mac or Linux! I have never worked with these OS so I do not have any idea how to resolve the problem.
    Can anyone help me with this matter?? That would be really nice of you to reply :)
    Thanx and have a great day.

    Thank you for replaying so soon..
    Well you are right by using a widget and etc.. but the problem is that I have been told that this application should open a PDF file that has bookmarks to each chapter of the text and one can make a search on this text by using pdf search.. So I do not have any other choice than opening a pdf :D and my time is unfortunately limit.
    For solving the problem that the user may not have PDF reader.. well I have been told that user should install the pdf reader, so in my application package I am putting the installation file of PDF.
    But going back to my problem.. I guess is someway I have to get the OS type of the user and I have to do a SWITCH or something on the OS type and then change the content of the Runtime.exec(). But the question is how can I get the OS type and what should I change in Runtime.exec().
    So now any idea? any solution??

  • Displaying image on the swings application

    Hi All,
    I want to display images onto my swing application. I was using ImageIcon and Class to getResource(filename). It can only provide me images that i have placed in my package not outside my package.
    Please help me, how to to do?
    Thanks in advance.

    [url http://java.sun.com/docs/books/tutorial/uiswing/components/icon.html]How to Use Icons

  • Including images in JAR for Swing Application

    I am using a couple of images in a Swing application. When I create the JAR file I include all the images. The JAR executes fine but the images are missing. When I put the images in the same directory as the JAR file the images are properly displayed.
    The code I use to display the images is:
    JLabel label = new JLabel(new ImageIcon("pleaseWait.gif"));
    Can anyone let me know what I need to do to get the image from the JAR? Do I need to look at ResourseBundle's?
    Thanks for any help..

    Does anybody know what is the reason of my problem??
    I created a package called test in my eclipse env. and in that package I placed folder named graph in which there is a file Help.png.
    Here is all the code I run in eclipse and it runs properly. When I create a jar file (using eclipse wizard) to execute without eclipse it can not execute and shows nothing (process starts and I have to kill it by myself in OS). Maybe there is some mistake with making jar... I do not know
    So let someone try tu run my class or build jar file and try to execute and share his observations (solutions) ??
    package test;
    import java.awt.Toolkit;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.UIManager;
    public class TestWindow extends JFrame {
         private JButton jButton1 = new JButton(new JARImage().getImage("Help.png"));
         public TestWindow() {
              this.getContentPane().add(jButton1);
              this.validate();
              this.setVisible(true);
         private class JARImage {
              protected ImageIcon getImage(String imageName) {
                   ImageIcon image = new ImageIcon();
                   try {
                        image.setImage((Toolkit.getDefaultToolkit().getImage(getClass()
                                  .getResource("graph/" + imageName))));
                   } catch (Exception ex) {
                        System.out.println("Image Error: " + ex);
                        ex.printStackTrace();
                   return image;
         public static void main(String[] args) {
              try {
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              } catch (Exception e) {
                   e.printStackTrace();
              new TestWindow();
    }

  • Run Swing application without opening DOS prompt window

    is it possible to run a Swing application without opening a command interface window in MS Windows?
    thanks

    Don't know if you mean that, but if you try to call javaw.exe instead of java.exe there pops no prompt up.

Maybe you are looking for