Flickering on redrawing JPanel inside JScrollPane

I am having a problem with redrawing a JPanel inside a JScrollPane.

Basically, I'm just trying to β€œwrap” an existing EditPanel (it originally extended JPanel) in JScrollPane.

JPanel seems to refresh too often (mass flicker). How can i stop this? I tried using setIgnoreRepaint () but did nothing.

Will this current implementation work, or do I need to create another inner class to fine tune the JPanel that I use 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);
        }
    }
}
+3
source share
3 answers

NEVER call revalidate () or redraw () inside the paint method. You invoke an endless redraw loop.

JScrollPane . , . setViewportView (...) .

, JPanel paintComponent() .

, , , panel.repaint().

+3

. JScrollPane? , JPanel, JTable 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);
+1

, , JScrollPane paintComponent() . , , , , - scrollpane, :

Scrollpane.getViewPort().add(JComponent);

, JScrollPane JScrollPane. JScrollPane.

Of course I'm wrong. I will find out soon.

I personally think that Swing always makes it a little difficult to redraw when things get complicated, but it never flickers.

0
source

Source: https://habr.com/ru/post/1782958/


All Articles