Drawing an Image to a JPanel within a JFrame

后端 未结 3 719
忘了有多久
忘了有多久 2020-12-09 21:21

I am designing a program that contains two JPanels within a JFrame, one is for holding an image, the other for holding GUI components(Searchfields etc). I am wondering how d

相关标签:
3条回答
  • 2020-12-09 21:45

    I'd like to suggest a more simple way,

      image = ImageIO.read(new File(path));
      JLabel picLabel = new JLabel(new ImageIcon(image));
    

    Yayy! Now your image is a swing component ! add it to a frame or panel or anything like you usually do! Probably need a repainting too , like

      jpanel.add(picLabel);
      jpanel.repaint(); 
    
    0 讨论(0)
  • 2020-12-09 21:46

    You can use the JLabel.setIcon() to place an image on the JPanel as shown here.

    On the other hand, if you want to have a panel with a background, you can take a look at this tutorial.

    0 讨论(0)
  • 2020-12-09 21:52

    There is no need to manually invoke paintComponent() from a constructor. The problem is that you passing null for a Graphics object. Instead, override paintComponent() and you use the Graphics object passed in to the method you will be using for painting. Check this tutorial. Here is an example of JPanel with image:

    class MyImagePanel extends JPanel{ 
        BufferedImage image;
        public void paintComponent(Graphics g){
            super.paintComponent(g);
            if(image != null){
                g.drawImage(image, 0, 0, this);
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题