【发布时间】:2014-09-03 18:41:10
【问题描述】:
我遇到了一个热门问题。我已经阅读了很多关于它的内容,但我仍然无法解决它。我正在编写类似 MSW Logo(Turtle 图形解释器)的代码,我想保存我的图像(绘制在扩展 JPanel 的类上)。问题是保存的图像是空白的(只有白色背景,仅此而已,没有形状)。
从 StackOverflow 上的帖子中我注意到,在 JPanel 上绘图是错误的,我应该在 BufferedImage 上绘图,但我不知道如何将此技巧应用于我的源代码。请帮助我离开地面。非常感谢! :)
我的类扩展 JPanel:
public class TurtlePanel extends JPanel {
public TurtlePanel() {
super();
this.setPreferredSize(new Dimension(481, 481));
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
}
}
创建面板:
public class PanelView {
private JPanel panel;
private MainWindowView mainView;
public PanelView(MainWindowView mainView) {
this.mainView = mainView;
createView();
}
private void createView() {
panel = new TurtlePanel();
panel.setBounds(280, 30, 481, 481);
panel.setBackground(Color.WHITE);
panel.setVisible(true);
mainView.mainWindow.add(panel);
}
public JPanel getPanel() {
return this.panel;
}
}
我绘制形状的方式(它有效,形状显示在我的面板上):
private void drawCircle(double radius) {
if(Math.signum(radius) == -1)
throw new NumberFormatException();
if(turtleModel.isShown()) {
Graphics2D g = ((Graphics2D) panelView.getPanel().getGraphics());
g.setColor(turtleModel.getPenColor());
g.draw(new Ellipse2D.Double(turtleModel.getPosX() - radius, turtleModel.getPosY() - radius, 2*radius, 2*radius));
}
}
我尝试保存图像的方式:
try {
BufferedImage image = new BufferedImage(panelView.getPanel().getWidth(), panelView.getPanel().getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics graphics = image.getGraphics();
panelView.getPanel().paint(graphics);
ImageIO.write(image, ext, new File(path));
}
catch(IOException exc) {
exc.printStackTrace();
}
再次感谢您的帮助!如果您需要更多信息,请告诉我。干杯!
【问题讨论】:
标签: java jpanel bufferedimage