Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6243045
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T12:03:53+00:00 2026-05-24T12:03:53+00:00

I am trying to draw a red square over a JScrollPane. The code I

  • 0

I am trying to draw a red square over a JScrollPane. The code I have below does an okay job of this, but sometimes when I scroll the viewport too fast, the red square jumps up or down.

enter image description here

This struck me as odd since the JScrollPane itself is stationary, so I assumed Swing would not try to move around the components painted within it. I’m guessing that what’s actually happening is that the the red square gets associated with viewport, which display graphics that do move.

Anyway, how do I prevent the red square from jumping around and successfully draw a red square over the list? Maybe I’m taking the wrong approach altogether.

package components;

import java.awt.*;
import java.util.Vector;

import javax.swing.*;
import javax.swing.event.*;

@SuppressWarnings("serial")
public class DialogWithScrollPane extends JFrame {

  public DialogWithScrollPane() {
    super();

    setResizable(false);
    Container pane = getContentPane();

    Vector<Object> listOfStuff = new Vector<Object>();
    for (int i = 0; i < 100; i++) {
      listOfStuff.add(Integer.toString(i));
    }

    final JScrollPane scrollPane = new JScrollPane() {

      public void paint(Graphics g) {
        System.out.println("JScrollPane.paint() called.");
        super.paint(g);

        g.setColor(Color.red);
        g.fillRect(20, 50, 100, 200);
      }
    };
    JList list = new JList(listOfStuff) {
      public void paint(Graphics g) {
        System.out.println("JList.paint() called.");
        super.paint(g);

        // Well, I could do this...
            //
        // scrollPane.repaint();
        //
        // ...and it would solve the problem, but it would also result in an
        // infinite recursion since JScrollPane.paint() would call this
        // function again.
      }
    };

    // Repaint the JScrollPane any time the viewport is moved or an item in the
    // list is selected.
    scrollPane.getViewport().addChangeListener(new ChangeListener() {
      public void stateChanged(ChangeEvent e) {
        scrollPane.repaint();
      }
    });
    list.addListSelectionListener(new ListSelectionListener() {
      public void valueChanged(ListSelectionEvent e) {
        scrollPane.repaint();
      }
    });

    scrollPane.setViewportView(list);

    pane.add(scrollPane);
    setMinimumSize(new Dimension(300, 300));
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLocation(500, 250);
    setVisible(true);
  }

  public static void main(String[] args) {
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        new DialogWithScrollPane();
      }
    });
  }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-24T12:03:54+00:00Added an answer on May 24, 2026 at 12:03 pm

    The JScrollPane should be painting behind the JViewport which should be painting behind the list. I’m guessing that this is only working because you’re overriding paint and not paintComponent and calling repaint on the JScrollPane all the time so that it paints itself again after its components are painted.

    Perhaps you want to use a JLayeredPane and have it hold the JScrollPane, and paint on it.

    edit: or the glasspane as I now see that mre suggests, but I’m afraid if you do that, and set the glasspane visible, you’ll lose the ability to interact with the underlying scrollpane.

    Edit 2
    For e.g.,

    import java.awt.*;
    import java.awt.event.ComponentAdapter;
    import java.awt.event.ComponentEvent;
    import java.util.Vector;
    import javax.swing.*;
    
    @SuppressWarnings("serial")
    public class DialogWithScrollPane2 extends JFrame {
    
       public DialogWithScrollPane2() {
          super();
    
          //setResizable(false);
          final JPanel pane = (JPanel) getContentPane();
    
          Vector<Object> listOfStuff = new Vector<Object>();
          for (int i = 0; i < 100; i++) {
             listOfStuff.add(Integer.toString(i));
          }
    
          final JScrollPane scrollPane = new JScrollPane();
          JList list = new JList(listOfStuff);
    
          scrollPane.setViewportView(list);
    
          final JPanel blueRectPanel = new JPanel() {
             @Override
             protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                g.setColor(Color.blue);
                g.fillRect(20, 50, 100, 200);
             }
          };
          blueRectPanel.setOpaque(false);
    
          final JLayeredPane layeredPane = new JLayeredPane();
          layeredPane.add(scrollPane, JLayeredPane.DEFAULT_LAYER);
          layeredPane.add(blueRectPanel, JLayeredPane.PALETTE_LAYER);
    
          layeredPane.addComponentListener(new ComponentAdapter() {
    
             private void resizeLayers() {
                final JViewport viewport = scrollPane.getViewport();
                scrollPane.setBounds(layeredPane.getBounds());
                blueRectPanel.setBounds(viewport.getBounds());
                SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                      blueRectPanel.setBounds(viewport.getBounds());
                   }
                });
             }
    
             @Override
             public void componentShown(ComponentEvent e) {
                resizeLayers();
             }
    
             @Override
             public void componentResized(ComponentEvent e) {
                resizeLayers();
             }
          });
    
          pane.add(layeredPane);
          setPreferredSize(new Dimension(300, 300));
          setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          pack();
          setLocation(500, 250);
          setVisible(true);
       }
    
       public static void main(String[] args) {
          javax.swing.SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                new DialogWithScrollPane2();
             }
          });
       }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have this picture, represented in red on the following image. I am trying
I am trying to draw a figure something like this: I need to have
I am trying to draw an isometric square with some custom code to build
I'm trying to draw a line (Red line in the image) over multiple panels,
I am trying to draw a series of rectangles using OpenGL but some of
I'm trying to draw a vertical scrollbar for my G15 applet, but am having
I'm trying to draw over the whole screen by using the desktop canvas and
The following is a snippet of code where I am trying to draw a
As title mentions. I'm trying to draw a gamma tone curve but i do
I'm trying to draw an image with a certain color. To get this effect,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.