0

I want to add a JScrollPane to a JPanel. I have added some more code to this old question of mine.

I have a Panel class as follows:

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

public class Panel extends JPanel
{
    public Panel()
    {
        super (true);
    }

    public void paintComponent (Graphics g)
    {
        super.paintComponent(g);
        setBackground(Color.WHITE);
        g.drawRect(250, 250, 10, 10);
    }
}

and a JScrollPaneTest class as follows:

import javax.swing.*;

public class JScrollPaneTest extends JFrame
{
    Panel panel = new Panel();
    public JScrollPaneTest ()
    {
        super("Test JScrollPane");
        add(new JScrollPane(panel, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS));
        setSize(300,300);
        setVisible(true);
    }

    public static void main (String[] args)
    {
        JScrollPaneTest test = new JScrollPaneTest();
        test.setDefaultCloseOperation(EXIT_ON_CLOSE);
    }
}

I have drawn a small rectangle in the lower right corner on the Panel; apparently the JScrollPane does not work because when resizing the rectangle disappears. Please let me know if you have any suggestions; thanks!

  • Possible duplicate of [how to add jscrollpane to jframe?](http://stackoverflow.com/questions/18481241/how-to-add-jscrollpane-to-jframe) – ItamarG3 Nov 17 '16 at 10:15
  • 2
    What doesn't work about it. What happens, and what do you expect to happen. You should start your program with a public static void main(String[] args) method. – matt Nov 17 '16 at 10:16
  • I expect the JPanel shows two JScrollBars, but it does not. This is just part of the code in my main class, which of course starts with public static void main (String[] args) – Alessandro Testori Nov 17 '16 at 11:15
  • The JScrollBars of a [JScrollPane](https://docs.oracle.com/javase/tutorial/uiswing/components/scrollpane.html), by default, will not show unless they are needed. If you insist on the scroll bars being visible at all times, you'll need to specify that. – Gilbert Le Blanc Nov 17 '16 at 12:26
  • The JScrollBars don't show up even when needed in this case. – Alessandro Testori Nov 17 '16 at 15:29

0 Answers0