JScrollBar Doesn't Do Anything

。_饼干妹妹 提交于 2020-01-05 07:08:17

问题


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);
}

回答1:


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.




回答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).



来源:https://stackoverflow.com/questions/12123476/jscrollbar-doesnt-do-anything

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!