簡體   English   中英

paintComponent在JPanel上不起作用

[英]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);
}   

首先調用super.paintComponent

paintComponet的工作之一是讓我們用組件的背景色填充Graphics上下文,這樣做是為了確保“清理”掉以前繪制到Graphics上下文的內容

查看AWT和Swing中的繪畫以獲取更多詳細信息

覆蓋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.

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