我能够使 JFrame 完全透明,而 JButton 部分透明,直到我将鼠标移到按钮上(不要单击)并将鼠标从按钮上移开(通过 MouseListener 调用 MouseExited)。发生的情况是再次绘制 JButton 的背景,因此在按钮上和按钮上移动几次鼠标后,按钮完全不透明。
public class ButtonExample extends JWindow
{
public ButtonExample( )
{
JButton But = new JButton( "Testing" );
But.setBackground( new Color( 0, 0, 0, 200 ) );
But.setForeground( new Color( 70, 155, 255 ) );
this.add( But );
this.setBackground( new Color( 0, 0, 0, 0 ) );
this.setMinimumSize( new Dimension( 200,100 ) );
this.setVisible( true );
}
public static void main( String[ ] Args )
{
new ButtonExample( );
}
}
最佳答案
问题是按钮报告完全不透明,而实际上它不是(由于部分透明的颜色)
but.setOpaque(false);
顺便说一句:如您所见,我更改了字段名称以符合 java 命名约定:-)
编辑
arggghh .. 错过了,抱歉。需要检查我们在 SwingX 中做了什么,从我的头顶我会说你需要覆盖 paintComponent 并自己处理背景绘画,比如
/**
* @inherited <p>
*/
@Override
protected void paintComponent(Graphics g) {
if (!isOpaque() && getBackground().getAlpha() < 255) {
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
}
super.paintComponent(g);
}
虽然没有尝试,但这样做可能会再次出现“变得更加不透明”......明天会回来
编辑2
好的,已检查 - 编辑后的代码工作正常。所以总结一下:具有半透明背景的组件
- 必须报告它们不是不透明的,以免混淆默认的绘制机制
- 必须接管背景绘画并自己用背景颜色填充它(SwingX JXPanel f.i. 通过对 alpha 属性的显式支持来实现)
为了您的方便,这里有一个小的runnable,并排显示不正确/正确的背景
public class TransparentButton {
public TransparentButton() {
JWindow incorrectOpaque = createWindow("incorrect opaque", true);
incorrectOpaque.setLocation(600, 600);
incorrectOpaque.setVisible(true);
JWindow correctOpaque = createWindow("correct opaque", false);
correctOpaque.setLocation(800, 600);
correctOpaque.setVisible(true);
}
private JButton createButton(final boolean opaque) {
JButton but = new JButton("Testing") {
/**
* @inherited <p>
* Overridden to take over background painting with
* transparent color.
*/
@Override
protected void paintComponent(Graphics g) {
if (!isOpaque() && getBackground().getAlpha() < 255) {
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
}
super.paintComponent(g);
}
};
but.setBackground(new Color(0, 0, 0, 100));
but.setForeground(new Color(70, 155, 255));
but.setOpaque(opaque);
return but;
}
private JWindow createWindow(String text, boolean opaque) {
JWindow window = new JWindow();
JButton but = createButton(opaque);
window.add(but);
window.add(new JLabel(""), BorderLayout.SOUTH);
window.setOpacity(0.5f);
window.setBackground(new Color(0, 0, 0, 0));
window.setSize(new Dimension(200, 100));
return window;
}
public static void main(String[] Args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new TransparentButton();
}
});
}
@SuppressWarnings("unused")
private static final Logger LOG = Logger.getLogger(TransparentButton.class
.getName());
}
关于java - 如何在完全透明的 JFrame 上创建部分透明的 JButton?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7373345/