[英]Java Swing paintComponent() override
我想在一些JComponent
( JPanel
, JLayeredPane
,..)中將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);
}
}
謝謝。
由於JPanel
, JLayeredPane
等已經擴展了JComponent
,因此您的建議在邏輯上是不可能的。 您要做的是在層次結構中添加一個新步驟。 現在它是JImagePanel -->JPanel --> JComponent
等,你正試圖讓它成為JImagePanel --> JPanel --> JImageComponent --> JComponent
。 為此,您必須更改JPanel
類,以便它實際擴展JImageComponent
。
這是我的建議:不要在已經擴展組件的類上使用JImageComponent
。 如果您創建的新組件不擴展預先存在的組件,請讓它們直接擴展JImageComponent
或JComponent
。 如果JImageComponent
類的目的是為元素提供統一性,請考慮為要實現的所有元素創建一個接口。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.