I've made a small program that draws black rectangles on a JPanel at random places. I would like to give the user the option to save this JPanel as a .gif file, but I'm not sure where to start. The function I need to write is SaveJPanelAsGIF below on line 36. Can anyone point me in the right direction please? Thanks.
// SaveAsGIF.java
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
public class SaveAsGIF extends JFrame
{
ButtonPanel buttonPanel;
CanvasPanel canvasPanel;
public static void main(String[] args)
{
SaveAsGIF sag = new SaveAsGIF();
}
public SaveAsGIF()
{
this.setTitle("Save JPanel As GIF");
this.setVisible(true);
this.setSize(600, 600);
this.setLayout(new BorderLayout());
canvasPanel = new CanvasPanel(this);
buttonPanel = new ButtonPanel(this, canvasPanel);
this.add(buttonPanel, BorderLayout.NORTH);
buttonPanel.setPreferredSize(new Dimension(600, 100));
this.add(buttonPanel, BorderLayout.NORTH);
this.add(canvasPanel, BorderLayout.SOUTH);
this.pack();
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void SaveJPanelAsGIF (JPanel jp)
{
// not sure what to do here.
}
}
// ButtonPanel.java
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
public class ButtonPanel extends JPanel implements ActionListener
{
JButton drawButton;
JButton saveButton;
CanvasPanel cp;
SaveAsGIF savegif;
public ButtonPanel(SaveAsGIF se, CanvasPanel canPanel)
{
savegif = se;
cp = canPanel;
this.setBackground(Color.RED);
this.setPreferredSize(new Dimension(600, 100));
LayoutManager lm = new GridLayout(1, 2);
drawButton = new JButton ("Draw New Rectangle");
saveButton = new JButton ("Save Canvas Panel as GIF");
drawButton.addActionListener(this);
saveButton.addActionListener(this);
this.setLayout(lm);
this.add(drawButton);
this.add(saveButton);
}
public void actionPerformed(ActionEvent e)
{
Object obj = e.getSource();
if (obj == drawButton)
cp.NewDrawing();
else if (obj == saveButton)
savegif.SaveJPanelAsGIF(cp);
}
}
// CanvasPanel.java
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import java.util.*;
class CanvasPanel extends JPanel
{
int x;
int y;
int length;
int width;
Random random;
SaveAsGIF savegif;
public CanvasPanel(SaveAsGIF se)
{
savegif = se;
x = 100;
y = 100;
length = 200;
width = 100;
random = new Random();
this.setBackground(Color.GREEN);
this.setPreferredSize(new Dimension(600, 500));
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillRect(x, y, width, length);
}
public void NewDrawing()
{
x = random.nextInt(100) + 50;
y = random.nextInt(100) + 50;
width = random.nextInt(100) + 50;
length = random.nextInt(100) + 150;
repaint();
}
}