I want to make a part of a transparent JFrame. It should look just like OneNote Screen Clipper. I basically have a fullscreen overlay of a partially transparent JFrame, and then inside that JFrame. I want to make some rectangles by dragging the mouse and making these rectangles completely transparent, for example:
--------------------------------------- | partially transparent | | | | ----------- | | | fully | | | | transp. | | | ----------- | ----------------------------------------
How can I do it? I currently have this:
public class Overlay extends JFrame implements MouseMotionListener, MouseListener { private Rectangle2D.Double selection; private Point start; private Point end; public Overlay() { addMouseMotionListener(this); addMouseListener(this); setSize(Toolkit.getDefaultToolkit().getScreenSize()); setAlwaysOnTop(true); setUndecorated(true); setOpacity(0.2f); setVisible(true); setDefaultCloseOperation(EXIT_ON_CLOSE); } @Override public void paint(Graphics g) { Graphics2D g2d = (Graphics2D) g; g2d.clearRect(0, 0, getWidth(), getHeight()); if (selection != null) { Area outside = new Area(new Rectangle2D.Double(0, 0, getWidth(), getHeight())); outside.subtract(new Area(selection)); g2d.setClip(outside); g2d.setColor(new Color(0.5f,0.5f,0.5f, 0.5f)); g2d.fillRect(0, 0, getWidth(), getHeight()); } @Override public void mousePressed(MouseEvent e) { start = e.getLocationOnScreen(); } @Override public void mouseDragged(MouseEvent e) { end = e.getLocationOnScreen(); selection = new Rectangle2D.Double(start.x, start.y, end.x - start.x, end.y - start.y); repaint(); } }
But this does not work correctly, because it redraws the background many times, and therefore it becomes darker / less transparent, and also slow, like hell ... relayings take a lot of time and are very noticeable.
source share