简体   繁体   中英

Java Swing paintComponent() override

I want to set an Image as background in some JComponent ( JPanel , JLayeredPane ,..). To do that I created the class JImagePanel that extends JPanel and overrides the method. Same thing for the other components. I now have 3 classes that differ only for what they extend. I wanted to create a unique class JImageComponent that extends JComponent , and then all the others will extend it, but I can't since the classes I created already extend a class ( JImagePanel extends JPanel ). Is there any other way I can do that?

This is the code of one of the classes I created:

public class JImagePanel extends JPanel {

  private static final int DEFAULTX = 0;
  private static final int DEFAULTY = 0;
  private static final int DEFAULTWIDTH = 1100;
  private static final int DEFAULTHEIGHT = 700;

  private BufferedImage img;
  private int imagex;
  private int imagey;
  private int imagewidth;
  private int imageheight;
  private static final long serialVersionUID = 1L;

  public JImagePanel(String path){
        super();
        this.imagex=JImagePanel.DEFAULTX;
        this.imagey=JImagePanel.DEFAULTY;
        this.imagewidth=JImagePanel.DEFAULTWIDTH;
        this.imageheight=JImagePanel.DEFAULTHEIGHT;
        img = loadImage(path);
  }

  public JImagePanel(String path,int x,int y, int width, int height){
        super();
        this.imagex=x;
        this.imagey=y;
        this.imagewidth=width;
        this.imageheight=height;
        img = loadImage(path);
  }

  @Override
  protected void paintComponent(Graphics graphics) {
        super.paintComponent(graphics);

       setOpaque(false);
       graphics.drawImage(img, imagex, imagey,imagewidth,imageheight, null);
  }
}

Thank you.

What you are suggesting isn't logically possible since JPanel , JLayeredPane , etc. already extend JComponent . What you're trying to do is add a new step in the hierarchy. Right now it goes JImagePanel -->JPanel --> JComponent , etc. and you're trying to make it JImagePanel --> JPanel --> JImageComponent --> JComponent . To do this, you would have to change the JPanel class so it actually extends JImageComponent .

Here's my suggestion: Don't use JImageComponent on the classes that already extend components. If you make new components that don't extend pre-existing components, have them extend JImageComponent , or JComponent directly. If the purpose of your JImageComponent class was to provide unity to your elements, consider making an interface for all your elements to implement.

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