現在我正在研究一個程序,它引發了一堆單獨的(在運行時生成的)圖像,每個圖像都在它們自己的窗口中。要做到這一點,我已經試過這種方法:在沒有繼承的情況下繪製到JPanel
public void display(){
JFrame window = new JFrame("NetPart");
JPanel canvas = new JPanel();
window.getContentPane().add(canvas);
Graphics g = canvas.getGraphics();
Dimension d = getSize();
System.out.println(d);
draw(g,new Point(d.minX*50,d.maxY*50), 50);
window.setSize(d.size(50));
window.setResizable(false);
window.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
window.setVisible(true);
}
public void draw(Graphics g, Point startLoc, int scale){
// generate and draw the image
}
public Dimension getSize(){
//returns my own dimensions class
}
但是,這將引發NullPointerException異常的平局,聲稱圖形爲空。有沒有辦法從外部向外部繪製JPanel(不是從JPanel繼承並重寫PaintComponent)?任何幫助,將不勝感激。
但是,如何將BufferedImage繪製到JPanel? – 2012-03-27 17:46:23
要在JPanel上繪製BufferedImage,您需要繼承JPanel並在paintComponent方法內調用g.drawImage(myBufferedImage,x,y,...) – ControlAltDel 2012-03-27 19:28:20