BufferedImage in JFrame doesnt Show up

烂漫一生 提交于 2019-12-13 18:43:42

问题


trying to get an image to print into a window. Everything runs without errors, and it also works if I replace the drawImage with another graphics class. However, the window is missing the image, and i'm not sure why. Again, the JFrame stuff and Graphics work fine with drawing other graphics, but only doesn't draw the image here. Thanks.

import javax.swing.JApplet;
import javax.swing.JFrame;
import javax.imageio.*;
import javax.imageio.stream.*;
import java.awt.*;
import java.awt.image.*;
import java.io.*;

public class GraphicsMovement2 extends JApplet{
    BufferedImage image = null;

    public static void main(String args[]){
        BufferedImage image = null;
        try {
            File file = new File("C:\\Users/Jonheel/Google Drive/School/10th Grade/AP Computer Science/Junkbin/MegaLogo.png");
            ImageInputStream imgInpt = new FileImageInputStream(file);
            image = ImageIO.read(file);
        }
        catch(FileNotFoundException e) {
            System.out.println("x");
        }
        catch(IOException e) {
            System.out.println("y");
        }


        JApplet example = new GraphicsMovement2();
        JFrame frame = new JFrame("Movement");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(example);
        frame.setSize(new Dimension(1366,768));       //Sets the dimensions of panel to appear when run
        frame.setVisible(true);
    }
    public void paint (Graphics page){
    page.drawImage(image, 100, 100, 100, 100, Color.RED, this);
  }
}

回答1:


You've defined image twice...

BufferedImage image = null;

public static void main(String args[]){
    BufferedImage image = null;

This essentially means that by the time you get to the paint method, it is null as you haven't initialized the instance variable.

Another problem you will have is the fact that you are trying to load the image from a static reference but the image isn't declared as static. Better to move this logic into the constructor or instance method.

Don't use JApplet as your container when you're adding to a JFrame, you're better of using something like JPanel. It will help when it comes to adding things to the container.

YOU MUST CALL super.paint(g)...in fact, DON'T override the paint method of top level containers like JFrame or JApplet. Use something like JPanel and override the paintComponent method instead. Top level containers aren't double buffered.

The paint methods does a lot of important work and it's just easier to use JComponent#paintComponent ... but don't forget to call super.paintComponent

UPDATED

You need to define image within the context it is going to be used.

Because you declared the image as an instance field of GraphicsMovement2, you will require an instance of GraphicsMovement2 in order to reference it.

However, in you main method, which is static, you also declared a variable named image.

The paint method of GraphicsMovement2 can't see the variable you declared in main, only the instance field (which is null).

In order to fix the problem, you need to move the loading of the image into the context of a instance of GraphicsMovement2, this can be best achived (in your context), but moving the image loading into the constructor of GraphicsMovement2

public GraphicsMovement2() {
    try {
        File file = new File("C:\\Users/Jonheel/Google Drive/School/10th Grade/AP Computer Science/Junkbin/MegaLogo.png");
        ImageInputStream imgInpt = new FileImageInputStream(file);
        image = ImageIO.read(file);
    }
    catch(FileNotFoundException e) {
        System.out.println("x");
    }
    catch(IOException e) {
        System.out.println("y");
    }
}

The two examples below will produce the same result...

The Easy Way

public class TestPaintImage {

    public static void main(String[] args) {
        new TestPaintImage();
    }

    public TestPaintImage() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new ImagePane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class ImagePane extends JPanel {

        public ImagePane() {
            setLayout(new BorderLayout());
            ImageIcon icon = null;
            try {
                icon = new ImageIcon(ImageIO.read(new File("/path/to/your/image")));
            } catch (Exception e) {
                e.printStackTrace();
            }
            add(new JLabel(icon));
        }

    }
}

The Hard Way

public class TestPaintImage {

    public static void main(String[] args) {
        new TestPaintImage();
    }

    public TestPaintImage() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new ImagePane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class ImagePane extends JPanel {

        private BufferedImage background;

        public ImagePane() {
            try {
                background = ImageIO.read(new File("/path/to/your/image"));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public Dimension getPreferredSize() {
            return background == null ? super.getPreferredSize() : new Dimension(background.getWidth(), background.getHeight());
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (background != null) {
                int x = (getWidth() - background.getWidth()) / 2;
                int y = (getHeight() - background.getHeight()) / 2;
                g.drawImage(background, x, y, this);
            }
        }
    }
}

Take the time to read through the tutorials

  • Creating a GUI With JFC/Swing
  • Performing Custom Painting



回答2:


Your class shouldn't extend JApplet when you're not even using applets -- this makes no sense. Instead

  • Have your drawing class extend JPanel
  • Draw in the JPanel's paintComponent method
  • Add this JPanel to the JFrame's contentPane.
  • Read the Swing painting tutorials. You can't guess at this stuff and expect it to work, and the tutorials will show you how it's done correctly.



回答3:


Don't mix file deviders,

File file = new File("C:\\Users/Jonheel/Google Drive/School/10th Grade/AP Computer Science/Junkbin/MegaLogo.png");

should be replaced with:

File file = new File("C:/Users/Jonheel/Google Drive/School/10th Grade/AP Computer Science/Junkbin/MegaLogo.png");



来源:https://stackoverflow.com/questions/13188417/bufferedimage-in-jframe-doesnt-show-up

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!