标题中指定了问题。我跑了,在这里和那里做几行。当我调整窗口大小或最小化窗口时,除了绘制的最后一行之外的所有内容都将从jframe窗口中删除。这是一个更大的相册计划的一部分。最终,我希望能够保存绘图并添加到相册中。我相信下面的代码就是问题所在。我这整个晚上一直在摸不着头脑。我想如果我创建了两个arraylists并遍历它们,repaint()会重新绘制所有内容,但事实并非如此。请帮忙!这是我的代码:
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Draw extends JPanel implements MouseListener, MouseMotionListener, ActionListener
{
private static final long serialVersionUID = 1L;
private ArrayList<ArrayList<Point>> lines;
private ArrayList<Point> points;
private Graphics g;
private Button clearButton;
public Draw()
{
clearButton = new Button("Clear slate");
g = getGraphics();
points = new ArrayList<Point>();
lines = new ArrayList<ArrayList<Point>>();
setPreferredSize(new Dimension(500, 500));
setBounds(0,0,500,500);
addMouseListener(this);
addMouseMotionListener(this);
clearButton.addActionListener(this);
this.add(clearButton, BorderLayout.SOUTH);
}
@Override
public void mouseClicked(MouseEvent e) {}
@Override
public void mouseDragged(MouseEvent e)
{
// TODO Auto-generated method stub
points.add(e.getPoint());
lines.add(points);
repaint();
}
public void paint(Graphics g)
{
super.paintComponents(g);
for(ArrayList<Point> p : lines)
{
for(int i = 0; i < points.size()-1; i++)
g.drawLine(points.get(i).x, points.get(i).y, points.get(i+1).x, points.get(i+1).y);
}
}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) {}
@Override
public void mousePressed(MouseEvent e)
{
points = new ArrayList<Point>();
points.add(e.getPoint());
repaint();
}
@Override
public void mouseReleased(MouseEvent e) {}
@Override
public void mouseMoved(MouseEvent e) {}
@Override
public void actionPerformed(ActionEvent evt)
{
if(evt.getSource()== clearButton)
{
lines.clear();
points.clear();
repaint();
}
}
}
主要方法:
import javax.swing.JFrame;
public class MainDriver
{
public static void main(String a[])
{
JFrame frame = new JFrame();
Draw d = new Draw();
frame.add(d);
frame.pack();
frame.setVisible(true);
}
}