JScrollPane with transparent background and content

爷,独闯天下 提交于 2019-12-10 15:00:00

问题


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


来源:https://stackoverflow.com/questions/15422854/jscrollpane-with-transparent-background-and-content

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!