package test;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.geom.Rectangle2D;
import java.awt.*;
import javax.swing.JComponent;
public class Mousedraw extends JComponent
{
/**
*
*/
private static final long serialVersionUID = 1L;
private static final int WIDTH = 600;
private static final int HEIGHT = 400;
private double beginX;
private double beginY;
private double width;
private double height;
public Mousedraw()
{
beginX = beginY = width = height = 0;
addMouseListener(new MouseHandler());
addMouseMotionListener(new MouseMotionHandler());
}
public void paintComponent(Graphics g)
{
var g2 = (Graphics2D)g;
var rect = new Rectangle2D.Double(beginX, beginY, width, height);
g2.draw(rect);
}
public Dimension getPreferredSize()
{
return new Dimension(WIDTH, HEIGHT);
}
private class MouseHandler extends MouseAdapter
{
public void mousePressed(MouseEvent event)
{
beginX = event.getX();
beginY = event.getY();
}
}
private class MouseMotionHandler extends MouseMotionAdapter
{
public void mouseDragged(MouseEvent event)
{
width = event.getX() - beginX;
height = event.getY() - beginY;
repaint();
}
}
}
建立测试类
package test;
import javax.swing.JFrame;
public class DrawText {
public static void main(String[] args)
{
var frame = new DrawFrame();
frame.setTitle("Draw");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class DrawFrame extends JFrame
{
/**
*
*/
private static final long serialVersionUID = 1L;
public DrawFrame()
{
add(new Mousedraw());
pack();
}
}