2014-09-03 67 views
-2

我有一個流行的問題。我已經閱讀了很多,但我仍然無法解決它。我正在編寫像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(); 
} 

再次感謝您的幫助!如果您需要更多信息,請告訴我。乾杯!

回答

0

調用油漆(圖形)不會複製當前面板的內容。 這並不是它應該工作的方式。

通常情況下,你擺添加組件,一個JPanel,並調用paintComponents()將調用paint()方法包含在你的JPanel每個組件

您不應該直接繪製圖形,而是可以修改TurtlePanel,使其擁有他必須對Graphics對象執行的操作列表,並覆蓋它的paint()方法,以便始終可以從新鮮新的圖形對象。

顯然,對於一個專業的架構,你可能會想到一個更好的方法。

+0

非常感謝!現在我可能知道如何修復我的繪圖。 – bargro 2014-09-03 19:15:12

0

在JPanel上繪圖是非常好的。如果經常重畫,並且重繪的內容會繪製相同的內容,那麼您可能需要將圖形緩存在BufferedImage中。

我不確定你的當前渲染是如何完成的,因爲它似乎在一個Graphics對象上運行,它可能是一個實例變量,這很奇怪,因爲你不想保存這些Graphics對象。有一個非標準的(可能是破碎的)繪製圖形的方法是最可能給你帶來麻煩的。

解決此問題的簡單方法是創建一個更抽象的方法,該方法繪製要在傳入的Graphics對象上呈現的內容。然後,JPanel的paintComponent方法(使用Graphics對象)和有關保存圖像(圖像中的圖形對象)的代碼都可以使用相同的方法調用共享。

+0

謝謝!你說得對 - 我的繪畫方式被打破了。 – bargro 2014-09-03 19:17:52