5
我正在創建一個矩形繪圖程序。只有當程序拖動到底部時才繪製正方形。 即使在另一個方向拖動,我想確保正確繪製正方形。 我該如何解決它? 請幫幫我。Java swing在鼠標拖放中繪製矩形
**DrawRect.java**
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DrawRect extends JPanel {
int x, y, w, h;
public static void main(String [] args) {
JFrame f = new JFrame("Draw Box Mouse 2");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setContentPane(new DrawRect());
f.setSize(300, 300); f.setVisible(true);
}
DrawRect() {
x = y = w = h = 0; //
MyMouseListener listener = new MyMouseListener();
addMouseListener(listener);
addMouseMotionListener(listener);
}
public void setStartPoint(int x, int y) {
this.x = x; this.y = y;
}
public void setEndPoint(int x, int y) {
w = Math.abs(this.x - x);
h = Math.abs(this.y - y);
}
class MyMouseListener extends MouseAdapter {
public void mousePressed(MouseEvent e) {
setStartPoint(e.getX(), e.getY());
}
public void mouseDragged(MouseEvent e) {
setEndPoint(e.getX(), e.getY()); repaint();
}
public void mouseReleased(MouseEvent e) {
setEndPoint(e.getX(), e.getY()); repaint();
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
Please help me.
g.drawRect(x, y, w, h);
}
}
我指它。謝謝 –
我們不能拿那個矩形嗎?每次我們按最後一次輸球? –