簡體   English   中英

PaintComponent無法用於繪制形狀

[英]PaintComponent not working for drawing shapes

我正在研究圖形,並嘗試使用PaintComponent繪制一些形狀,以下是代碼。 我正在嘗試一個小時,但仍然無法正常工作是沒有原因的。 這個簡單問題的解決方案是什么?

public class MyPainting  extends JPanel
{

    public void PaintComponent (Graphics g) 
    {
        super.paintComponent(g);
        g.setColor(Color.RED);
        g.drawRect(100, 100, 10, 20);
    }

    public  static void main (String [] args)
    {
        MyPainting p =  new MyPainting();
        JFrame f= new JFrame();
        f.setSize(300,300);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(p);       
        f.setVisible(true);
    }
}

當我運行程序時,有一個空的JFrame ,我確實嘗試過g.drawString, ImageIcon但是每次都看不到。

JPanel任何超類中都沒有定義PaintComponent方法。 您需要paintComponent

@Override
public void paintComponent (Graphics g) 

並添加@Override批注,以允許編譯器檢查正確的方法。

暫無
暫無

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

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