现在我正在开发一个程序,它会抛出一堆单独的(在运行时生成的)图像,每个图像都在自己的窗口中。为此,我尝试了这种方法:
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
}
但是,这会在 draw 中抛出 NullPointerException,声称图形为空。有什么方法可以从外部绘制到 JPanel(不是从 JPanel 继承并覆盖 PaintComponent)?任何帮助,将不胜感激。
最佳答案
如果您在运行时绘制图像,您应该使用 BufferedImage。
创建一个 BufferedImage,对其调用 getGraphics() 以获取其 Graphics 对象,使用 Graphics(2D) api 对其进行绘制,然后调用 Graphics.dispose()(并非绝对必要,但这是一个好习惯)海报建议用它创建一个 ImageIcon 并使用 setIcon() 或子类 JPanel/JComponent 放入 JLabel 并在 paintComponent 中绘制
关于java - 在没有继承的情况下绘制到 JPanel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9894539/