1

I have a class that extends JComponent called Canvas. Even when it's bigger than my JScrollPane's JViewport, the knobs will not appear on the scroll bars and I cannot scroll down on the Canvas. The code for my scroll pane is here:

    final JFrame frame = new JFrame("SketchPad");
    frame.setLayout(new BorderLayout());

    frame.setExtendedState(JFrame.MAXIMIZED_BOTH);

    JScrollPane scrollPane = new JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    JViewport vp = scrollPane.getViewport();
    vp.setLayout(null);
    vp.setBackground(Color.BLUE);
    frame.getContentPane().add(scrollPane, BorderLayout.CENTER);

    canvas = new Canvas();

    canvas.setBounds(0, 0, w, h);

    vp.add(canvas);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);

Am I doing something wrong with the JScrollPane, or is it something else?

Noodly_Doodly
  • 69
  • 2
  • 11
  • 1
    1) For better help sooner, post an [MCVE](http://stackoverflow.com/help/mcve) (Minimal Complete Verifiable Example) or [SSCCE](http://www.sscce.org/) (Short, Self Contained, Correct Example). 2) Java GUIs have to work on different OS', screen size, screen resolution etc. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). – Andrew Thompson Feb 15 '15 at 02:08

1 Answers1

4
vp.setLayout(null);

Don't set a null layout on the viewport. The scrollbars will appear automatically when the preferred size of the component added to the viewport of the scrollpane is greater than the size of the scrollpane.

The layout manager us used to determine the preferred size (as a general rule you should never use a null layout).

Also, don't use a Canvas, that is an AWT components. Use a JPanel when using Swing. Or, if it is a custom class then it should have a more descriptive name to avoid confusion.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • I still have another question: when I use `add()` to add the custom class Canvas to the scroll pane's viewport, it is there yet scrolling doesn't scroll the canvas. When I use `new JScrollPane(canvas)`, the canvas doesn't appear at all. – Noodly_Doodly Feb 15 '15 at 14:34
  • The scrollbars are based on the preferred size of the Canvas. Make sure your Canvas class uses layout managers or if you are doing custom painting then you need to override the `getPreferredSize()` method of the class to return the appropriate size of the class. – camickr Feb 15 '15 at 15:26