I'm trying to draw a stationary rectangle on top of a JScrollPane. This would look similar to freezing the first row in Microsoft excel and scrolling down. I tried using a JLayer and LayerUI to achieve this however, I've been unable to make the rectangle stay fixed and not move when the user scrolls. Furthermore, I've also tried overriding the JScrollPane's JViewport's paint method. But this drew the rectangle below the JScrollPane's View.
The only solution that has come closest to solving this is adding the JScrollPane to the JLayer instead. However this causes the rectangle to also cover the vertical scroll bar which is not wanted.
public class MyFrame extends JFrame {
public MyFrame() {
super();
this.setSize(420, 420);
JPanel panel = new JPanel();
panel.setBackground(Color.GREEN);
panel.setPreferredSize(new Dimension(420, 1000));
LayerUI<JComponent> layerUI = new LayerUI<JComponent>(){
@Override
public void paint(Graphics g, JComponent c) {
super.paint(g, c);
g.setColor(Color.BLUE);
g.fillRect(0, 0, c.getWidth(), 25);
}
};
JLayer<JComponent> jLayer = new JLayer<>(panel, layerUI);
JScrollPane jScrollPane = new JScrollPane(jLayer, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
this.add(jScrollPane);
this.setVisible(true);
}
}