[英]paintComponent does not work on JPanel
因此,我有一個擴展JPanel的Board類,並編寫了方法,該方法在調用時會保存一些坐標並調用repaint。 但是,重新繪制的效果不會顯示在屏幕上。 當我嘗試向顯示的面板中添加具有redbackground的JLabel時,即顯示該面板,只是重新繪制不起作用。
public int x, y;
public JPanel panel = new JPanel();
private int xx,yy;
private Color c;
public Board(int x, int y, int wolfNumber, int hareNumber){
this.x=x;
this.y=y;
wolvesCoords = new int[wolfNumber][2];
haresCoords = new int[hareNumber][2];
setLayout(new GridLayout());
add(panel);
}
public synchronized void write(int xx, int yy, Color c){
this.xx = xx;
this.yy = yy;
this.c = c;
repaint();
}
@Override
protected void paintComponent(Graphics g) {
int width=panel.getWidth()/x;
int height=panel.getHeight()/y;
g.setColor(c);
g.drawRect(xx*width, yy*height, width, height);
g.fillRect(xx*width, yy*height, width, height);
super.paintComponent(g);
}
覆蓋paintComponent
作為實例成員panel
而不是Board JPanel
類本身。
panel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
...// your code here
}
};
為什么Board
類擴展了JPanel
?
嘗試使用設計模式,例如“ 優先繼承”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.