Home > other >  How to set a ScrollBar at the top of a JPanel
How to set a ScrollBar at the top of a JPanel

Time:01-16

I am trying to insert a JScrollPane in a JPanel. By default, when I open the panel, the scrollbar is set at the bottom. What I want is the opposite, to set it at the top of the pannel. I have tried the commands scrollBar.getVerticalScrollBar().setValue(0) and JPanel.add(scrollBar, BorderLayout.NORTH), but thet do not work.


The code I have is:

JPanel panel=new JPanel();
texto = new ReportPanel();
texto.setEditable(false);
panel.add(texto, BorderLayout.NORTH);
JScrollPane scrollBar=new JScrollPane(panel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
this.add(scrollBar);

CodePudding user response:

The code I have is:

    JPanel panel=new JPanel();
    texto = new ReportPanel();
    texto.setEditable(false);
    panel.add(texto, BorderLayout.NORTH);
    JScrollPane scrollBar=new JScrollPane(panel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    this.add(scrollBar);

CodePudding user response:

One way to set the vertical scrollbar of a JScrollPane to the top of a JPanel is to use the setViewportView() method of the JScrollPane and pass in a JViewport with the desired vertical position. Here is an example:

JPanel panel = new JPanel();
JScrollPane scrollPane = new JScrollPane(panel);
JViewport viewport = scrollPane.getViewport();
viewport.setViewPosition(new Point(0, 0));

This sets the viewport of the JScrollPane to the top of the JPanel, which in turn sets the scrollbar to the top. Alternatively, you can use the setValue() method on the JScrollBar, after you have added the JScrollPane to your JPanel:

JPanel panel = new JPanel();
JScrollPane scrollPane = new JScrollPane(panel);
panel.add(scrollPane);
JScrollBar vertical = scrollPane.getVerticalScrollBar();
vertical.setValue(0);

This code snippet will set the vertical scrollbar of the JScrollPane to the top of the JPanel.

  • Related