[英]Difference between drawing on JPanel via paintComponent and Buffered Image
[英]Drawing to a buffered image inside a Jpanel
我當前正在嘗試制作一個畫布,可以將其繪制到畫布上並使其出現在JFrame中。
為此,我打算在JPanel組件內創建一個BufferedImage,paintComponent方法可以從中繪制。
理想地,從給定的JFrame中,我希望能夠引用此緩沖圖像,然后使用其Graphics2D向其繪制東西,paintComponent方法可以在使用緩沖圖像進行繪制時顯示該圖形。
我這樣做是為了避免直接使用paintcomponent方法,我希望能夠從程序中的任何地方引用此畫布,並在調用框架repaint()方法時對其進行繪制。
class MyPanel extends JPanel {
BufferedImage img = new BufferedImage(500, 500, BufferedImage.TYPE_INT_ARGB);
Graphics2D imgG2 = img.createGraphics();
public Graphics2D getGraphics() {
return imgG2;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
int w = img.getWidth();
int h = img.getHeight();
g2.drawImage(img, 0, 0, w, h, null);
}
}
class Main {
private static JFrame createAndShowGui() {
JFrame frame = new JFrame("droneFrame");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(new MyPanel());
frame.setSize(500, 500);
frame.setResizable(false);
frame.setVisible(true);
return frame;
}
public static void main(String args[]) {
JFrame frame = createAndShowGui();
//Something here to reference the inner Jpanels imgG2 field, and draw to it.
frame.repaint();
//Draw whatever is currently in the buffered image.
}
}
但是,我不知道該怎么做,因為frame.getComponent(0)僅返回一個Component,而不是特定類型的組件。
提前致謝。
剛剛設法弄清楚了這一點,您需要將JFrame的內容窗格設置為JPanel,然后引用緩沖圖像的圖形,您需要獲取JFrame的內容窗格,並將其向下轉換為特定的MyPanel類型。 。
現在,您具有正確格式的內容窗格,並且可以引用圖形,因為它現在具有該字段。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.