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 PhotoEditorextends JPanelimplements 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[i],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;

}

publicvoid actionPerformed(ActionEvent e){

Object eventSource = e.getSource();

if ((eventSourceinstanceof JMenuItem) || (eventSourceinstanceof JButton));{

String label = (String) e.getActionCommand();

//Sets up the Action Listeners

if (label.equals("Exit")){

System.exit(0);

}

// Closes application

elseif (label.equals("Open")){

openImage();

}

/* More codes for each button or menu item */

}

}

protectedvoid openImage(){

int returnVal = fc.showOpenDialog(this);

if (returnVal == JFileChooser.APPROVE_OPTION){

File file = fc.getSelectedFile();

try{

img = ImageIO.read(file);

}

catch (IOException e1){

};

}

}

publicvoid paintComponent(Graphics g){

super.paintComponent(g);

g.drawImage(img, 500, 500,null);

}

privatestaticvoid 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);

}

publicstaticvoid main(String[] args){

//Schedule a job for the event-dispatching thread:

//creating and showing this application's GUI.

javax.swing.SwingUtilities.invokeLater(new Runnable(){

publicvoid run(){

createAndShowGUI();

}

});

}

}

>

[8952 byte] By [maz4pja] at [2007-11-26 17:55:47]
# 1

Is this line really necessary?

if ((eventSource instanceof JMenuItem) || (eventSource instanceof JButton)); {

If it is, remove the extra ";" after the parentheses. Remember to repaint() the frame to update the image after it is loaded.

Jukka

duckbilla at 2007-7-9 5:08:57 > top of Java-index,Desktop,Core GUI APIs...
# 2
You have to call repaint after you read the image, else paintComponent will not be called.
Rodney_McKaya at 2007-7-9 5:08:57 > top of Java-index,Desktop,Core GUI APIs...
# 3
where exactly in the code would i need to repaint()? Is the actual paint code okay? Code examples would be very much appreciated.
maz4pja at 2007-7-9 5:08:57 > top of Java-index,Desktop,Core GUI APIs...
# 4
Right after img = ImageIO.read(file);Also g.drawImage(img, 500, 500, null) will draw your image from offset (500, 500) in the panel coordinates.Is this what you wanted?
Rodney_McKaya at 2007-7-9 5:08:57 > top of Java-index,Desktop,Core GUI APIs...
# 5
Yeah thats what I wanted.I tried adding repaint after that but still nothing. I havent got something to do with threads mixed up have i? Or its not recognising the panel its supposed to draw on?
maz4pja at 2007-7-9 5:08:57 > top of Java-index,Desktop,Core GUI APIs...
# 6
The code you posted isn't compileable or executable so we can't see how you program works. From a quick glancea) I don't see where you add the PhotoEditor panel to the GUI, so of course nothing will paintb) the PhotoEditor panel doesn't have a preferred size.
camickra at 2007-7-9 5:08:57 > top of Java-index,Desktop,Core GUI APIs...
# 7

Here's my java file (http://www.foolish-hearts.com/project/PhotoEditor.java) which should compile and execute.

So have i not set my panel up properly? I created a JFrame which was my window, and then a JLabel called main which is basically my main work area and i set the size of that. I have a feeling something is wrong/missing there but I'm not sure.

maz4pja at 2007-7-9 5:08:57 > top of Java-index,Desktop,Core GUI APIs...
# 8

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.

camickra at 2007-7-9 5:08:57 > top of Java-index,Desktop,Core GUI APIs...
# 9
Thanks so much. Thats what it was! It loads now. :DAlso if i wanted to have the image load in the center of the panel instead of at the 500, 500 ofset i have it right now is there a way to specify that?
maz4pja at 2007-7-9 5:08:57 > top of Java-index,Desktop,Core GUI APIs...
# 10
> Also if i wanted to have the image load in the center of the panel instead You are in control of the x, y coordinates, so you need to calculate the values based on the size of the panel and the size of the image. I'll let you figure out the math.
camickra at 2007-7-9 5:08:57 > top of Java-index,Desktop,Core GUI APIs...