Swing中依據滑鼠拖拽來畫出矩形的實現方法
阿新 • • 發佈:2020-01-07
畫了好久,草要麼就是畫了,沒插掉原先線條,要麼就是畫第二個的時候第一個也被擦掉,但其實只要呼叫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) { } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。