public class ZiehPanel extends JPanel
{
private int x1 = 0;
private int y1 = 0;
private int x2 = 0;
private int y2 = 0;
private boolean isDragging = false;
private Color dragFillColor = new Color(255, 255, 160, 128);
private Color dragBorderColor = new Color(0, 0, 0, 128);
private JFrame parent;
private Vector rects = new Vector(1, 1);
public ZiehPanel(JFrame f)
{
parent = f;
setOpaque(false);
addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent evt)
{
isDragging = true;
x1 = evt.getX();
y1 = evt.getY();
x2 = evt.getX();
y2 = evt.getY();
repaint();
}
public void mouseReleased(MouseEvent evt)
{
isDragging = false;
rects.add(new Rectangle(x1 > x2 ? x2 : x1, y1 > y2 ? y2 : y1, x1 > x2 ? x1 - x2 : x2 - x1, y1 > y2 ? y1 - y2 : y2 - y1));
x1 = 0;
y1 = 0;
x2 = 0;
y2 = 0;
repaint();
}
});
addMouseMotionListener(new MouseMotionAdapter()
{
public void mouseDragged(MouseEvent evt)
{
x2 = evt.getX();
y2 = evt.getY();
repaint();
}
});
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
for(int i = 0; i < rects.size(); i++)
{
g.setColor(dragFillColor);
Rectangle r = (Rectangle)rects.get(i);
g.fillRect(r.x, r.y, r.width, r.height);
g.setColor(dragBorderColor);
g.drawRect(r.x, r.y, r.width, r.height);
}
g.setColor(dragFillColor);
g.fillRect(x1 > x2 ? x2 : x1, y1 > y2 ? y2 : y1, x1 > x2 ? x1 - x2 : x2 - x1, y1 > y2 ? y1 - y2 : y2 - y1);
g.setColor(dragBorderColor);
g.drawRect(x1 > x2 ? x2 : x1, y1 > y2 ? y2 : y1, x1 > x2 ? x1 - x2 : x2 - x1, y1 > y2 ? y1 - y2 : y2 - y1);
}
}