1

I'm trying to put a vertical JScrollBar on top of a JPanel. I can add the scoll bar easily enough, but when I run the program, my scroll bar doesn't have any effect. I can drag it up and down, but the contents of the JPanel don't move. I've read all what I can find about how to do this, and it seems very straightforward, but I'm obviously missing something.

Please note that my JPanel layout is set to NULL. Here is the relevant code. Thanks!

public JDlgResults(ArrayList<AnsweredProblem> probList) {
    initComponents();
    pnlResults.setLayout(null); //allows free form placing of JLabels

    /* Iterate over the ArrayList and add each problem to the results table */
    Iterator iter = probList.iterator();
    int row = 1;

    while(iter.hasNext()) {
        addRow(row, iter.next());
        row++;
    }

    JScrollBar jScrollResults = new javax.swing.JScrollBar();
    pnlResults.add(jScrollResults);
    jScrollResults.setBounds(590, 0, 17, 196);
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
AndroidDev
  • 20,466
  • 42
  • 148
  • 239
  • 1
    more guidance could be provided if you were to provide the relevant code from `initComponents()`. – akf Aug 25 '12 at 16:17
  • For better help sooner, post an [SSCCE](http://sscce.org/). – Andrew Thompson Aug 26 '12 at 00:02
  • 1) *"my JPanel layout is set to NULL."* If not the cause of this problem, then the cause of others. ***Use Layouts!*** 2) Please learn common [Java naming conventions](http://java.sun.com/docs/books/jls/second_edition/html/names.doc.html#73307) (specifically the case used for the names) for class, method & attribute names & use it consistently. – Andrew Thompson Aug 26 '12 at 00:04

2 Answers2

2

That's by design. It would be kind of bad if the scroll bar magically tried to pick up panels in its vicinity and started scrolling them.

On a low level, you can add listeners to the scroll bar and implement scrolling yourself. You would also have to tell the scroll bar how much there is to scroll.

However, this is not what you want. You want a JScrollPane that you wrap around your panel. In that way, you never instantiate the scroll bars directly and do not have to deal with the low-level mechanics of scrolling (which is quite complicated).

Ingo Kegel
  • 46,523
  • 10
  • 71
  • 102
2

I assume that your initComponents() method sets up a bunch of components and adds them to your contentPane and establishes your dialog (whether it be dialog or a frame).

Simply adding your JScrollPane to that panel wont do the trick.

Instead, add your pnlResults to the JScrollPane instance and make that your contentPane.

akf
  • 38,619
  • 8
  • 86
  • 96