如何在完全透明的JFrame上创建部分透明的JButton?

我能够使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); 

BTW:如你所见,我改变了字段名称以符合java命名约定:-)

编辑

arggghh ..错过了,对不起。 需要检查我们在SwingX中做什么,从头顶我会说你需要覆盖paintComponent并自己处理背景画,比如

  /** * @inherited 

*/ @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 fi通过显式支持alpha属性)

为了您的方便,这里是一个小型的可运行的错误/正确的背景并排

 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 

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

你尝试过半透明吗?

半透明和整形窗口API首次作为私有API添加到Java SE 6 Update 10发行版中。 此function已移至JDK 7发行版中的公共AWT包。

我认为以上链接可能会对您有所帮助。