2

I am having problems displaying an image I obtain from a file chooser I created. Could you give me suggestions? The image is created as a buffered image.

Here is my code:

public void actionPerformed(ActionEvent e)
{
    if (e.getSource().getClass().getName().contains("JMenuItem")) 
    {
        if (e.paramString().contains("Load")) {
            JFileChooser fc = new JFileChooser();
            fc.setCurrentDirectory(new File("."));
            int retVal = fc.showOpenDialog(null);
            if (retVal == 0) 
            {
                File file = fc.getSelectedFile();
                try {
                image = ImageIO.read(file);
            } catch (IOException e1) {
                // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }
}

Here is the code for display:

public void paint(Graphics g){  
    super.paintComponents(g);
    g.drawImage(getIconImage(), 0, 0, control);
    g.drawImage( image, 0, 0,null);
    repaint();
}
Patrick D'Souza
  • 3,491
  • 2
  • 22
  • 39
user938295
  • 21
  • 1
  • 3
  • What problems exactly are you having? – Mat Sep 10 '11 at 15:15
  • 1
    what errors do you get? why are you calling drawImage twice? could you post the whole code or an SSCCE or at least the stacktrace reporting the error? – Heisenbug Sep 10 '11 at 15:17
  • the think is the image does not show on my gui. I want to display the image i obtain from the file chooser to my gui. Do you want to see the code for my gui? – user938295 Sep 10 '11 at 15:19
  • http://stackoverflow.com/questions/5638988/problem-with-loading-image-in-java-with-filechooser this question has similar problem, look thru it! give yourself at least 1 hour than you will not forgot how to do this in your entire life :) – TeaCupApp Sep 10 '11 at 15:29
  • the display code doesn't look like Swing ... in case you are mixing awt and swing - dont! – kleopatra Sep 10 '11 at 16:07
  • repaint() in a paint method? Just don't do it! Myself, I like mKorbel's solution (+1) – Hovercraft Full Of Eels Sep 10 '11 at 17:01

1 Answers1

5

Why bothering with 2D Graphics for display picture(s), put Image/ImageIcon to the JLabel, example about JFileChooser + Image + paintCompoent(),

public void paint(Graphics g){// paintComponent not paint 
   super.paintComponents(g);  // paintComponent not paintComponents
.....

Could be for Swing JComponents

public void paintComponent(Graphics g){  
   super.paintComponent(g);
......
Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • +1 There's a nice scaling example [here](http://stackoverflow.com/questions/6916693/jmenuitem-imageicon-too-big). – trashgod Sep 10 '11 at 17:32