Swing中依据鼠标拖拽来画出矩形的实现方法
画了好久,草要么就是画了,没插掉原先线条,要么就是画第二个的时候第一个也被擦掉,但其实只要调用repaint方法就好了…
import javax.swing.*; import java.awt.*; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; class Rect extends JFrame{ public static void main(String[] args) { Rect r=new Rect(); } Draw draw=new Draw(); public Rect() { this.add(draw); this.addMouseListener(draw); this.setSize(500,500); this.setLocation(400,400); this.setVisible(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } class Draw extends JPanel implements MouseListener { int x1 = 0; int y1 = 0; int x2 = 0; int y2 = 0; public void paint(Graphics g) { // super.paint(g); g.setColor(Color.BLUE); g.drawRect(x1, y1, x2 - x1, y2 - y1); } @Override public void mouseClicked(MouseEvent e) { } @Override public void mousePressed(MouseEvent e) { x1 = e.getX(); y1 = e.getY(); } @Override public void mouseReleased(MouseEvent e) { x2 = e.getX(); y2 = e.getY(); this.repaint(); } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
赞 (0)