Re: Display image selected from JFileChooser

In article
jimmy <jimmy.cullen@xxxxxxxxx> wrote:

I have attached my new code. I would be most grateful if someone could
identify the problem and indicate how I could resolve it.

Again, Lew is more assiduous than I, and ilAn's advice will serve you
better in the long run; but I will make a few observations:

0) Don't invoke pack() until you've added the components.

1) Again, extend Component? I don't see a reason.

2) Again, Swing components should be constructed in the EDT; I've
implemented Runnable as another example of doing so.

3) Invoking super.paintComponent(g) is unnecessary when you paint the
entire content.

4) If you make MyAction a separate class, its constructor needs to know
who gets the selected image. Similarly, MyImage needs a method,
setImgage(), to set the new image for later painting.

5) As an example, I've added the same action to a menu bar.

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class MyImageApp implements Runnable {

public static void main(String[] args) {
EventQueue.invokeLater(new MyImageApp());

public void run() {
JFrame myFrame = new JFrame();
myFrame.setTitle("Here's my Frame");
MyImage core = new MyImage(myFrame);
Action myAction = new MyAction(core);
JButton myButton = new JButton(myAction);
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("File");
menu.add(new JMenuItem(myAction));
myFrame.add(core, BorderLayout.CENTER);
myFrame.add(myButton, BorderLayout.SOUTH);

class MyAction extends AbstractAction {

MyImage panel;

public MyAction(MyImage panel) {
this.panel = panel;

public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
int returnVal = fileChooser.showOpenDialog(fileChooser);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
System.out.println("Image selected: " + file.getPath());
try {
BufferedImage image =;
System.out.println("Image loaded to buffer.");
} catch (IOException ex) {
} else {
System.out.println("File access cancelled by user.");

class MyImage extends JPanel {

private final Window parent;
BufferedImage image;

public MyImage(JFrame parent) {
this.parent = parent;
this.setPreferredSize(new Dimension(200, 200));

public void paintComponent(Graphics g) {
g.drawImage(image, 0, 0, null);

public void setImgage(BufferedImage image) {
this.image = image;
setPreferredSize(new Dimension(
image.getWidth(), image.getHeight()));

John B. Matthews
trashgod at gmail dot com