簡體   English   中英

用Java繪制形狀

[英]Drawing shapes in Java

我想要一種方法,該方法將繪制一個矩形,另一個方法將繪制一個橢圓形,另一個用於線條,圖像等。

我嘗試了多種在網上找到的技術,但都沒有用。 這是唯一不會崩潰的文件,而我現在擁有的文件是:

    @Override
public void paintComponent(Graphics g){
    super.paintComponents(g);
}

public void DrawRect(int x, int y, int width, int height, Color color){
    Graphics2D g2D = image.createGraphics();
    g2D.setColor(Color.RED);
    g2D.fillRect(x, y, width, height);
    //g2D.dispose();
    //g2D=null;
}

但是它並沒有真正顯示任何內容。

但是它並沒有真正顯示任何東西

很自然,您沒有將圖形上下文鏈接到繪圖功能。 解決方法:

@Override
public void paintComponent(Graphics g){
    super.paintComponents(g);
    DrawRect(g, 10, 10, 20, 20, Color.blue);
}

private void DrawRect(Graphics g, int x, int y,
     int width, int height, Color color){
    Graphics2D g2D = (Graphics2D) g;
    g2D.setColor(Color.RED);
    g2D.fillRect(x, y, width, height);
    //g2D.dispose();
    //g2D=null;
}

或者,等效地,您可以創建自己的上下文myDrawingPanel.createGraphics(); 並手動調用該函數(刪除graphics參數)

要在按下按鈕時進行繪制:

1)放置一個JPanel。

2)從新類中MyPanel extends JPanel JPanel對象MyPanel extends JPanel ,並覆蓋了paint方法。 (或使用匿名類myPanel = new JPanel() { @Override ... } )。 提示(如果使用的是NetBeans,則可以在設計器on variable created code編輯on variable created code上的屬性)

3)單擊按鈕時,只需調用myPanel.repaint(); 重畫

暫無
暫無

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

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