Add an Background image to a Panel

不羁岁月 提交于 2019-11-26 02:03:06

问题


I have a JPanel, and i want to add an image as its background. How can i do that ?

frame = new JFrame(\"Some frame\");
panel1 = new JPanel();
panel1.setBorder(new EmptyBorder(5, 5, 5, 5));
// NEED TO ADD AN IMAGE TO THIS PANEL

panel1.setLayout(cardlayout);
frame.getContentPane().add(panel1);

frame.setLocationByPlatform(true);
frame.setVisible(true);

I need to add an image to the panel and how can i do it ?

UPDATE 1

    panel1 = new JPanel()
    {
    private static final long serialVersionUID = 1L;

    @Override
    public void paintComponent(Graphics g)
    {

        g.drawImage(Toolkit.getDefaultToolkit().createImage(\"1.jpg\"), 0, 0, null);
    }
};

回答1:


You need to override the method paintComponent(Graphics g) of JPanel and use drawImage() on the Graphics object g as in this example.


Also, check these two examples by @trashgod:

  1. example.
  2. example.



回答2:


You have a resource location problem.

Toolkit#createImage may return an empty image if the resource can not be found.

I suggest you use the ImageIO API instead, it supports a wider range of image formats, but will also throw an exception if the image is not found or can not be loaded.

How you load the image will also depend on where the image is.

If the image exists on the file system, you can simply use a File object reference, if the image is an embedded resource (within you application), you will need to use Class#getResource to obtain a URL to it.

public class TestGraphics {

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

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

                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setContentPane(new PaintTest());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class PaintTest extends JPanel {

        private BufferedImage image;

        public PaintTest() {

            setLayout(new BorderLayout());
            try {
                // Use this if the image exists within the file system
                image = ImageIO.read(new File("/path/to/image/imageName.png"));
                // Use this if the image is an embedded resource
//                image = ImageIO.read(getClass().getResource("/path/to/resource/imageName.png"));
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

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

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

    }

}


来源:https://stackoverflow.com/questions/13791984/add-an-background-image-to-a-panel

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