选择元素或滚动时透明的 JList 涂抹

Transparent JList smears when selecting elements or scrolling

我在渐变 JPanel 之上有一个透明的 JList 和 JScrollPanel,每个代码如下所示:

JPanel midPanel = new JPanel() {
        protected void paintComponent(Graphics g) {
            Paint p = new GradientPaint(0.0f, 0.0f, new Color(233, 220, 0, 0),
             getWidth(), getHeight(), new Color(239, 129, 91, 255), true);
            Graphics2D g2d = (Graphics2D)g;
            g2d.setPaint(p);
            g2d.fillRect(0, 0, getWidth(), getHeight());
        }
    };

列表代码

    ArrayList<String> songs = new ArrayList<>(Arrays.asList(new String[] {elements...}));
    
    DefaultListModel<String> model = new DefaultListModel<>();
    model.addAll(songs);

    JList<String> songList = new JList<String>(model);

    songList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    songList.setLayoutOrientation(JList.VERTICAL);
    songList.setVisibleRowCount(-1);
    songList.setOpaque(false);
    songList.setCellRenderer(new TransparentListCellRenderer());

    JScrollPane scroller = new JScrollPane(songList);
    scroller.setPreferredSize(new Dimension(400, 250));
    scroller.setOpaque(false);
    scroller.getViewport().setOpaque(false);
    scroller.setBorder(BorderFactory.createEmptyBorder());

    midPanel.add(scroller);

在触摸任何东西之前,它看起来像这样:

在选择内容或滚动列表的元素后,所有内容都会涂抹并造成混乱:

有谁知道如何解决这个问题?如果我不得不猜测出了什么问题,那将是渐变的问题,因为 paintComponet() 方法被覆盖了,所以它没有被正确地重绘,但如果是这样的话,我不知道如何修复它。非常感谢任何帮助。

答案是将面板包裹在一种透明的容器中。

public class AlphaContainer extends JComponent {
    private JComponent component;

    public AlphaContainer(JComponent component) {
        this.component = component;
        setLayout( new BorderLayout() );
        setOpaque( false );
        component.setOpaque( false );
        add( component );
    }

    /**
     *  Paint the background using the background Color of the
     *  contained component
     */
    @Override
    public void paintComponent(Graphics g) {
        g.setColor( component.getBackground() );
        g.fillRect(0, 0, getWidth(), getHeight());
    }
}