我正在使用鼠标制作一个矩形选择器,并且我drawRect
周围有一个普通的矩形。当宽度或高度变为负数时,矩形被填充。有没有什么办法解决这一问题?
这是我的代码:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class Pie extends JPanel{
public boolean running = true;
public Rectangle mouseRect;
public Rectangle rectBounds;
public int x1,y1,x2,y2;
public boolean showRect = false;
public Pie(){
setFocusable(true);
MAdapter mama = new MAdapter();
setDoubleBuffered(true);
this.addMouseListener(new MAdapter());
this.addMouseMotionListener(mama);
setBackground(Color.black);
Thread update = new Thread(){
public void run(){
while(running){
repaint();
try{Thread.sleep(2);}catch(InterruptedException e){}
}
}
};
update.start();
}
public void paintComponent(Graphics g){
super.paintComponent(g);
//if(y2 < y1) y2 = y1;
if(showRect){
g.setColor(new Color(0,250,0,50));
g.fillRect(x1,y1,x2 - x1,y2 - y1);
g.setColor(new Color(0,255,0));
g.drawRect(x1 - 1,y1 - 1,x2 - x1 + 1,y2 - y1 + 1);
}
}
class MAdapter extends MouseAdapter{
public void mousePressed(MouseEvent e){
showRect = true;
x1 = e.getX();
y1 = e.getY();
x2 = e.getX();
y2 = e.getY();
}
public void mouseDragged(MouseEvent e){
x2 = e.getX();
y2 = e.getY();
rectBounds = new Rectangle(x1,y1,x2 - x1, y2 - y1);
}
public void mouseReleased(MouseEvent e){
showRect = false;
rectBounds = new Rectangle(x1,y1,x2 - x1, y2 - y1);
x1 = 0;
y1 = 0;
x2 = 0;
y2 = 0;
}
}
public static void main(String[] args){
JFrame f = new JFrame("Aber");
f.setSize(500,500);
f.setResizable(true);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocationRelativeTo(null);
f.add(new Pie());
}
}
有什么我做错了吗?