マウスを使用して長方形セレクターを作成していますが、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());
}
}
私が間違っていることはありますか?