开发者

Flickering when repainting a JPanel inside a JScrollPane

I'm having a problem with repainting a JPanel inside a JScrollPane.

Basically, I'm just trying to 'wrap' my existing EditPanel (it originally extended JPanel) into a JScrollPane.

It seems that the JPanel updates too often (mass flickering). How would I stop this from happening? I tried using the setIgnoreRepaint() but it didn't seem to do anything.

Will this current implementation work or would I need to create another inner class to fine-tune the JPanel I'm using to display graphics?

Skeleton code:

public class MyProgram extends JFrame{

    public MyProgram(){
        super();
        add(new EditPanel());
        pack();
    }
    private class EditPanel extends JScrollPane{

       开发者_运维问答 private JPanel graphicsPanel;

        public EditPanel(){
            ///EDIT, sorry, should have mentioned this was here before
            super();
            graphicsPanel = new JPanel();
            this.setViewportView(graphicsPanel);
            //END EDIT
        }

        public void paintComponent(Graphics g){
            graphicsPanel.revalidate(); //update the scrollpane to current panel size
            repaint();

            Graphics g2 = graphicsPanel.getGraphics();
            g2.drawImage(imageToDraw, 0, 0, null);
        }
    }
}


NEVER invoke revalidate() or repaint() inside a painting method. You are causing an infinite repaint loop.

There is no need to extend the JScrollPane at all. You should never extend the class just to add a component to it. That is what the setViewportView(...) method is for.

If you do have custom painting then you extend JPanel and overide the paintComponent() method of the panel.

Then if you ned to repaint the panel you simply invoke, panel.repaint().


Hmm. Why would you subclass JScrollPane? If I were doing this, I would either subclass JPanel or JTable, and wrap my class in a JScrollPane:

JTable table = new MySpecialJTable();
JScrollPane scrollPane = new JScrollPane(table);
Component container = /* scrollPane goes in here, set the size of scrollPane
       yourself or let a layout manager do that for you */
container.add(scrollPane);


If you're trying to implement a scrollable region, I suspect subclassing JScrollPane and overriding paintComponent() might be causing the issue. just to check, I assume you are aware that in order to add something to a scrollpane you can:

Scrollpane.getViewPort().add(JComponent);

If not, take a look at JScrollPane and how to use JScrollPane's. I've never seen anybody subclass the JScrollPane before.

I could be wrong of course. I will soon find out.

I personally find Swing always lags slightly on repaint when things get complicated, but never "mass flickering".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜