我有一个半工作的绘画/turtle 图形程序,但我遇到了一些问题。 我需要保存在某个时刻绘制的图像 - 我知道我需要使用 BufferedImage 但我该如何处理呢?我在下面附上了一些代码。
简而言之,我有一个带有文本字段的 JFrame,其下方有一个白色的 JPanel。当用户输入命令时,线将通过另一个类绘制并显示在 JPanel 上。我知道我无法将它们从 JPanel 保存到图像中,但不了解如何实现缓冲图像以及我需要/不需要更改什么。
请客气,我是编程新手,尚未完成代码的某些部分。
提前致谢
public class Turtle2 extends JFrame implements ActionListener, KeyListener{
JMenuBar menuBar;
JMenu help, file;
JPanel panel, panel2;
JMenuItem newO, load, save, exitO, about;
JTextField text;
int savecounter = 0, newcounter = 1, part2I = 0;
int x1 = 0, x2 = 0, y1 = 0, y2 = 0;
int trigger = 1, turnleftconstant = 0, turnrightconstant =0, direction =0;
int col = 0;
public Turtle2() {
setLayout(new FlowLayout());
setSize(1000, 1000);
setTitle("Graphic");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//menu bar
//sets up general look of window
panel = new JPanel();
panel.setBackground(Color.darkGray);
//implements box layout
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
//sets up drawing area
panel2 = new JPanel();
panel2.setPreferredSize(new Dimension(500, 500));;
panel2.setBackground(Color.WHITE);
panel2.setBorder(BorderFactory.createLineBorder(Color.darkGray, 3));
//starting point on drawing area co-ordinates
x1 = 15; x2 = 15; y1 = 230; y2 =230;
//starting point implemented
LinePen first = new LinePen(x1, y1, x2, y2, col);
panel2.add(first);
//sets up user input text box
text = new JTextField(30);
//add action listener to text box - ready for input and details responses
text.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//retrieves user input
String actions = text.getText();
first.setVisible(true);
//commands from text
//add the command line textfeild to the interface
panel.add(text);
//uses border layout to set the layout of the interface
getContentPane().add(BorderLayout.NORTH, panel);
getContentPane().add(BorderLayout.CENTER, panel2);
//set the size of the interface
setSize(600,600);
//ensure the interface is visible
setVisible(true);
}
最佳答案
我将保留所有线条的数组,然后迭代它们,然后使用 img.createGraphics()
绘制线条和其他图形。
关于java - 如何将 JPanel 变成 BufferedImage Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43514079/