簡體   English   中英

Java Swing paintComponent()覆蓋

[英]Java Swing paintComponent() override

我想在一些JComponentJPanelJLayeredPane ,..)中將Image設置為背景。 為此,我創建了JImagePanel類,它擴展了JPanel並覆蓋了該方法。 其他組件也是如此。 我現在有3個類只是因為它們的擴展而有所不同。 我想創建一個擴展JComponent的唯一類JImageComponent ,然后所有其他人都會擴展它,但我不能,因為我創建的類已經擴展了一個類( JImagePanel擴展了JPanel )。 有沒有其他方法可以做到這一點?

這是我創建的其中一個類的代碼:

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);
  }
}

謝謝。

由於JPanelJLayeredPane等已經擴展了JComponent ,因此您的建議在邏輯上是不可能的。 您要做的是在層次結構中添加一個新步驟。 現在它是JImagePanel -->JPanel --> JComponent等,你正試圖讓它成為JImagePanel --> JPanel --> JImageComponent --> JComponent 為此,您必須更改JPanel類,以便它實際擴展JImageComponent

這是我的建議:不要在已經擴展組件的類上使用JImageComponent 如果您創建的新組件不擴展預先存在的組件,請讓它們直接擴展JImageComponentJComponent 如果JImageComponent類的目的是為元素提供統一性,請考慮為要實現的所有元素創建一個接口。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM