我想创建一个半透明的JPanel.我通过简单地使用颜色构造函数的RGBA值来完成它,但问题是当我使用事件处理不正确地唤醒时.我的要求是一个半透明的Jpanel,当鼠标进入它的边框,这个面板变得可见,如果鼠标退出边框不可见.我已经通过以下代码做到这一点,但问题是它不能正常工作的透明背景(RGBA),但它可以正常工作的RGB颜色.
import javax.swing.*; import javax.swing.border.*; import java.awt.*; import java.awt.event.*; public class MDCW extends JFrame { private JPanel contentPane; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { MDCW frame = new MDCW(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public MDCW() { setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE); setBounds(100,100,1013,551); contentPane = new JPanel(); contentPane.setBackground(new Color(0,139,139)); contentPane.setBorder(new EmptyBorder(5,5,5)); setContentPane(contentPane); contentPane.setLayout(null); final JPanel panel = new JPanel(); panel.setBackground(new Color(0,50)); panel.addMouseListener(new MouseAdapter() { @Override public void mouseEntered(MouseEvent e) { panel.setBorder(new LineBorder(new Color(255,255,255),5)); } @Override public void mouseExited(MouseEvent e) { panel.setBorder(null); } }); panel.setBounds(360,155,215,215); contentPane.add(panel); final JPanel panel_1 = new JPanel(); panel_1.setBackground(new Color(0,0)); panel_1.addMouseListener(new MouseAdapter() { @Override public void mouseEntered(MouseEvent e) { panel_1.setBorder(new LineBorder(new Color(255,5)); } @Override public void mouseExited(MouseEvent e) { panel_1.setBorder(null); } }); panel_1.setBounds(84,215); contentPane.add(panel_1); } }
解决方法
JPanel不支持半透明背景.需要两个步骤来处理这个问题:
>首先,要使任何正常运行的透明度,你必须在面板上设置不透明(false);否则你会有毛刺,因为假设一个不透明的面板完全覆盖了它的界限下面.
>但是,当opaque为false时,面板也不会绘制其背景(!),所以您必须在paintComponent中绘制背景.
这是一个下拉替换类,它将处理这两个步骤.
private class TransparentPanel extends JPanel { { setOpaque(false); } public void paintComponent(Graphics g) { g.setColor(getBackground()); Rectangle r = g.getClipBounds(); g.fillRect(r.x,r.y,r.width,r.height); super.paintComponent(g); } }
如果我将第一个面板创建更改为:
final JPanel panel = new TransparentPanel();