简体   繁体   中英

JComponent not drawing inside JPanel

Simple problem for Swing regular costumers.

The idea is to load an image and use it as a background of a JPanel through a JComponent object. It seems to load just fine as the image information from toString() method is loading properly and the paintComponent() method is running, but for some reason it is not rendering correctly inside the JFrame leading to an empty frame. Here's the code:

RicochetFrame.java

public class RicochetFrame extends JFrame {
  RicochetStartPanel startPanel;

  public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                RicochetFrame window = new RicochetFrame();
                window.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
   }

  public RicochetFrame() throws IOException {
    startPanel = new RicochetStartPanel();

    this.getContentPane().add(startPanel);

    this.setBounds(0, 0, 500, 500);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //this.pack();
    this.setVisible(true);
  }

}

RicochetStartPanel.java

public class RicochetStartPanel extends JPanel {
  RicochetStartPanel() throws IOException {
    BufferedImage myImage = ImageIO.read(new File("frame_bg.jpg"));
    this.add(new RicochetImagePanel(myImage));

    this.setVisible(true);

    this.validate();
    this.repaint();
  }

}

RicochetImagePanel.Java

public class RicochetImagePanel extends JComponent {
  private Image image;

  public RicochetImagePanel(Image image) {
    this.setVisible(true);

    this.image = image;
  }
  @Override
  protected void paintComponent(Graphics g) {  
    super.paintComponent(g);
    g.drawImage(image, 0, 0, this);
  }
}

Your RicochetImagePanel is sizing itself to its preferred size => [0, 0]. Override its getPreferredSize() to return the dimensions of the image (if not null). Better still, why not simply display the image as an ImageIcon in a JLabel?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM