我有一個流行的問題。我已經閱讀了很多,但我仍然無法解決它。我正在編寫像MSW Logo(龜圖形解釋器)的東西,我想保存我的圖像(繪製在擴展JPanel的類上)。問題是保存的圖像是空白的(只有白色背景,沒有更多,沒有形狀)。Java - 將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();
}
再次感謝您的幫助!如果您需要更多信息,請告訴我。乾杯!
非常感謝!現在我可能知道如何修復我的繪圖。 – bargro 2014-09-03 19:15:12