gpt4 book ai didi

java - JFrame - 只有一部分透明

转载 作者:搜寻专家 更新时间:2023-10-31 08:03:34 25 4
gpt4 key购买 nike

我想使 JFrame 的一部分透明。它看起来应该类似于 OneNote Screen Clipper。我基本上有一个部分透明的 JFrame 的全屏覆盖,然后在这个 JFrame 中我想通过拖动鼠标制作一些矩形并使这些矩形完全透明,如下所示:

---------------------------------------
| partially transparent |
| |
| ----------- |
| | fully | |
| | transp. | |
| ----------- |
----------------------------------------

我该怎么做?目前我有这个:

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();
}
}

但这不能正常工作,因为它会多次重绘背景,因此它变得更暗/透明度更低,而且速度非常慢......重绘需要很多时间并且非常明显。

最佳答案

作为快速修复,调用

repaint((int) selection.x,(int) selection.y,(int) selection.width,(int) selection.height);

代替 repaint()

不过,这不是最好的方法。

关于java - JFrame - 只有一部分透明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23541519/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com