Java的可视化绘制问题
发布网友
发布时间:2022-04-20 13:55
我来回答
共1个回答
热心网友
时间:2023-06-21 23:33
你要用数组或其他的来保存你画的东西,如下即可:
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MouseDrawPanel extends JFrame
{
private ArrayList<Rectangle> lines = new ArrayList<Rectangle> ();
private int x, y;
public MouseDrawPanel ()
{
setTitle ("Use Mouse Draw");
setLayout (new BorderLayout ());
setSize (500, 400);
setLocationRelativeTo (null);
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
JPanel container = new JPanel ()
{
@Override
public void paint ( Graphics g )
{
int size = lines.size ();
Graphics2D g2d = (Graphics2D) g;
g2d.setStroke (new BasicStroke (13));
g2d.setRenderingHint (RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
for ( int i = 0; i < size; i++ )
{
Rectangle p = lines.get (i);
if (p.width != -1)
{
g2d.drawLine (p.x, p.y, p.width, p.height);
}
else
{
g2d.drawLine (p.x, p.y, p.x, p.y);
}
}
}
};
container.addMouseMotionListener (new MouseAdapter ()
{
public void mouseDragged ( MouseEvent e )
{
lines.add (new Rectangle (x, y, e.getX (), e.getY ()));
x = e.getX ();
y = e.getY ();
repaint ();
};
});
container.addMouseListener (new MouseAdapter ()
{
@Override
public void mousePressed ( MouseEvent e )
{
lines.add (new Rectangle (e.getX (), e.getY (), -1, -1));
x = e.getX ();
y = e.getY ();
repaint ();
}
@Override
public void mouseReleased ( MouseEvent e )
{
repaint ();
}
});
add (container, BorderLayout.CENTER);
setVisible (true);
}
public static void main ( String[] args )
{
new MouseDrawPanel ();
}
}