Make a Java JScrollpane only scroll vertically

2019-04-07 20:22发布

I would like my entire JFrame to vertically scroll.

I have added the following code, but it only creates a horizontal scrollbar.

frame.setContentPane(new JScrollPane(new GradeQuickResource())); 

I want to do the opposite. I ONLY want a vertical scrollbar and NO horizontal scrollbar.

I have seen the horizontal policy code, but it doesn't seem to work. I do not know what to name it. This code looks something like this:

setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

Thanks!

2条回答
萌系小妹纸
2楼-- · 2019-04-07 20:47

Try this:

public class AddScrollBarToJFrame {

    public static void main(String[] args) {
        JPanel panel = new JPanel();
        JScrollPane scrollBar = new JScrollPane(panel,
            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
            JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        JFrame frame = new JFrame("AddScrollBarToJFrame");
        frame.add(scrollBar);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);
        frame.setVisible(true);
    }
}

Also, you can have a look at How to use a ScrollBar in both vertical and horizontal direction.

查看更多
Animai°情兽
3楼-- · 2019-04-07 21:01

AFIK: JScrollPane scrollableTa=new JScrollPane(targetComp); scrollableTa.setHorizontalScrollBar(null); works

查看更多
登录 后发表回答