0

I created a JLabel as a picture and added it to JScrollPane and then to my JFrame. Next thing I overriden paint() method in my JFrame and used drawLine() method to draw 4 lines (they look like a frame).

Now when I'm scrolling, my lines disappear and they don't repaint(). Only when I made action such as minimalize, maximalize etc i can see them.

How to force to repaint() after using ScrollPane?

il_raffa
  • 5,090
  • 129
  • 31
  • 36
iboan
  • 15
  • 4
  • Implement your custom painting in `paintComponent()`, not `paint()`. See [here](https://docs.oracle.com/javase/tutorial/uiswing/painting/closer.html). – Frecklefoot Jun 03 '16 at 14:43
  • and if that doesn't work - put a breakpoint in the paintComponent method to see if it's actually getting called. In direct answer to your question, see the second answer to this question: http://stackoverflow.com/questions/6561246/scroll-event-of-a-jscrollpane. Put a ChangeListener on the Viewport of your scrollpane. – Jeutnarg Jun 03 '16 at 14:48

1 Answers1

0

You need to add a change listener to the viewport of the scroll pane. See this example:

import javax.swing.*;
import java.awt.*;

public class Example extends JFrame {

    public Example() {

        PaintedComponent paintedComponent = new PaintedComponent();
        paintedComponent.setPreferredSize(new Dimension(500, 500));

        JScrollPane scrollPane = new JScrollPane(paintedComponent);
        scrollPane.getViewport().addChangeListener(e -> paintedComponent.repaint());

        setContentPane(scrollPane);
        setMaximumSize(new Dimension(300, 300));
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
    }

    public static void main(String[] args) {
        new Example();
    }
}

class PaintedComponent extends JComponent {
    @Override
    public void paintComponent(Graphics g) {
        // Do your painting here
        System.out.println("Repainted");
    }
}
explv
  • 2,709
  • 10
  • 17