我正在尝试将 JSlider 覆盖在 JProgressBar 之上。我正在使用 JLayeredPane 来保存这两个组件。我将 JProgressBar 添加到 JLayeredPane,然后添加 JSlider。到目前为止,我已经尝试通过将 opaque 设置为 false 并覆盖 paintComponent 方法来使 JSlider 透明。我最终得到的是滑块手柄是唯一在背景保持不透明时变得透明的部分。我可能没有正确使用 JLayeredPane,但我对 JLabels 的测试似乎有效。如何让 JSlider 的背景透明?
JSlider slider = new JSlider()
{
@Override
public void paintComponent(java.awt.Graphics g)
{
java.awt.Graphics2D g2 = (java.awt.Graphics2D) g;
g2.setComposite(AlphaComposite.getInstance(
AlphaComposite.SRC_OVER, (float) 0.5));
super.paintComponent(g2);
}
};
感谢大家的帮助。通过您的示例,我发现我的问题出在我正在使用的 JLayeredPane 上。我认识到可以使 JSlider 背景透明,但是,我仍然无法让下面图层上的组件显示出来。这是我的例子:
public class SliderTest extends JFrame
{
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
SliderTest frame = new SliderTest();
frame.setVisible(true);
} catch (Exception e)
{
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public SliderTest()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel panel = new JPanel();
contentPane.add(panel, BorderLayout.CENTER);
panel.setLayout(new BorderLayout(0, 0));
JLayeredPane layeredPane = new JLayeredPane();
panel.add(layeredPane, BorderLayout.CENTER);
layeredPane.setLayout(new BorderLayout(0, 0));
JProgressBar progressBar = new JProgressBar();
progressBar.setValue(50);
layeredPane.add(progressBar);
layeredPane.setLayer(progressBar, 0);
JSlider slider = new JSlider()
{
@Override
protected void paintComponent(Graphics g)
{
Graphics2D g2d = (Graphics2D) g.create();
g2d.setColor(getBackground());
g2d.setComposite(AlphaComposite.SrcOver.derive(0.5f));
g2d.fillRect(0, 0, getWidth(), getHeight());
g2d.dispose();
super.paintComponent(g);
}
};
layeredPane.setLayer(slider, 1);
slider.setOpaque(false);
// layeredPane.setLayer(slider, 1);
layeredPane.add(slider, BorderLayout.CENTER);
}
}