JScrollPane with transparent background and conten

2019-02-23 12:34发布

问题:

In my app, I show a popup dialog to show a large list of cards. I display them as images in many JLabel components in a JPanel subclass. I then put that object in a JScrollPane to allow for horizontal scrolling through the cards.

I want the unused space to be transparent with a dark background to show that what's behind it is disabled. I used setBackground(new Color(50, 50, 50, 200)) to achieve the look I want, but the content behind it does not redraw, so I get artifacting.

Here's what it looks like:

How would I go about fixing this? How do I get the content behind it to redraw when I scroll?

Thanks in advance.

回答1:

Taking the window out of the equation for the momement.

The JScrollPane contains a JViewport which then contains you content. So you need to set your content pane to transparent, the viewport to transparent and then the scroll pane to transparent.

You can achieve this by using setOpaque(false) on each of these containers.

This will ensure that the repaint manager will now paint through the background.

The next problem is, Swing doesn't actually support "semi-transparent" components (that is, either it's opaque or transparent).

You can implement this by overriding the paintComponent method of the main component (the one on the viewport is probably sufficient)



回答2:

Try the following...might give you some relief during scrolling. You likely also have a problem when the main frame is maximized or restored. You will need a listener for those events and a similar fix.

    jScrollPane.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() {
        @Override
        public void adjustmentValueChanged(final AdjustmentEvent e) {
            sevenWondersframe.repaint();
        }
    });
    jScrollPane.getHorizontalScrollBar().addAdjustmentListener(new AdjustmentListener() {
        @Override
        public void adjustmentValueChanged(final AdjustmentEvent e) {
            sevenWondersframe.repaint();
        }
    });