这是我的代码:
package trialruns;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class TransparentFrame extends JFrame
{
JButton b1;
public TransparentFrame()
{
setTitle("Transparent Frame Demo");
setSize(400,400);
setLayout(new GridBagLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);
setUndecorated(true);
setVisible(true);
setResizable(true);
setOpacity(0.4f);
}
public static void main(String args[])
{
new TransparentFrame();
}
}
问题是如果我 setOpacity<1.0 我得到一个错误:
The frame is decorated at java.awt.Frame.setOpacity(Frame.java:960)
如果我执行 setUndecorated(true) 则我无法调整 Jframe 的大小
我需要能够调整透明 JFrame 的大小
我还需要能够访问透明框架下的文件夹 我的意思是,如果透明窗口位于桌面上,并且我想打开放置在窗口下方的特定文件夹,那么我应该能够在不最小化 jframe 的情况下这样做。
有什么办法吗??
我在网上搜索但没有找到合适的解决方案。
最佳答案
框架的大小调整由框架本身处理。当您删除边框装饰时,您将失去调整大小的功能。
因此,您需要自己管理框架的大小调整。查看Component Resizer对于一个允许您调整任何组件大小的类。
对您的代码所做的更改是:
//setResizable(true); // not needed as this is the default anyway
setOpacity(0.4f);
new ComponentResizer( this );
But is it possible to keep the border opaque
是的,但你只会得到 Swing 装饰边框,而不是平台边框和装饰:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class TransparentFrame2 extends JFrame
{
public TransparentFrame2()
{
setTitle("Transparent Frame Demo");
setUndecorated(true);
getRootPane().setWindowDecorationStyle(JRootPane.FRAME);
setBackground( new Color(0, 0, 0, 0) );
setSize(400,400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String args[])
{
new TransparentFrame2();
}
}
Also it is still not possible to access the content behind the frame
是的,但您需要完全透明。如果您不使用完全透明,则鼠标事件将传递给框架,而不是框架下方的组件。
如果你想要半透明,那么理论上你可以在框架中添加一个 MouseListener 来拦截 MouseEvent。然后你可以让你的框架不可见。然后您可以使用 Robot
生成一个新的 MouseEvent,该事件现在将被发送到屏幕。接下来您将使用框架 locationOnScreen(...) 方法从框架坐标转换鼠标点。我从未尝试过这种方法。
关于java - 如何使透明的 jframe 可调整大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30141423/