我想創建一個應用程序,在該應用程序中可以在畫布上繪製路徑。問題是我必須不斷更新此畫布。在Java Canvas中更新繪圖
目前我能夠做到這一點,但我必須每次重繪所有路徑,所以我必須將所有點存儲在內存中。我寧願簡單地通過添加一個新點來更新繪圖。
可能嗎?
目前我的代碼是:
public class MyCanvas extends Canvas{
private static final long serialVersionUID = 1L;
public MyCanvas(){}
public void paint(Graphics graphics){
super.paint(graphics);
graphics.setColor(Color.green);
// points is an ArrayList of Point2D
for (Iterator iterator = points.iterator(); iterator.hasNext();) {
Point2D point2d = (Point2D) iterator.next();
graphics.fillOval((int)((canvas.getWidth()/2.0) + point2d.getX()), (int)((canvas.getHeight()/2.0) + point2d.getY()), 5, 5);
}
}
}
謝謝!
EDIT
這是當前的解決方案:
PanelCanvas canvasPanel;
...
public void drawCircle(int x, int y){
Graphics2D g2d = bufferedImage.createGraphics();
g2d.setColor(Color.green);
g2d.setBackground(Color.white);
g2d.fillOval((int)((panelCanvas.getWidth()/2.0) + x/10.0), (int)((panelCanvas.getHeight()/2.0) + y/10.0), 5, 5);
panelCanvas.repaint();
}
public class CanvasPanel extends JPanel{
public void paintComponent(Graphics graphics){
super.paintComponents(graphics);
Graphics2D g2d = (Graphics2D)graphics;
g2d.setBackground(Color.white);
g2d.drawImage(bufferedImage, null, 0, 0);
}
}
爲什麼在這個千年中,您是使用AWT組件編碼的?大多數使用過它們的人已經忘記了如何。另外,如果它是純AWT,爲什麼添加[tag:swing]標籤?問題中的問題.. –
@AndrewThompson畫布嵌入在Swing GUI中。你有什麼建議替代AWT.Canvas?謝謝! – Maverik
請參閱編輯我的答案。 –