Home > Mobile >  How do I add a scrollbar to a JFrame with setLayout(null)?
How do I add a scrollbar to a JFrame with setLayout(null)?

Time:01-22

I have some components which I need to use setBounds() on, hence the reason why I'm using the setLayout(null).

But some of my components are out the window(below the Y-axis). I was wondering if there is a way to add a scrollbar to navigate down the window so as to see all the remaining components. A screenshot of my window is below.

Output of my window image:

CodePudding user response:

That GUI would be simple to produce using layouts. Put the component displaying the list (which looks well suited to being a JTable, given the two pieces of data per row / line) into a JScrollPane. Put the scroll pane into the CENTER of a BorderLayout. Put the red label into the PAGE_START of the border layout. Then .. oh wait, the job is done!

This is what it might look like (using a JTextArea instead of a table).

can u please post a copy of this code.

Try implementing it based on the instructions above. If there is a problem, post a minimal reproducible example of your attempt.

CodePudding user response:

Since you are refering to the items in the scrolling area as components, and not as texts in JTextArea, please have a look at the below.

import java.awt.*;
import javax.swing.*;
import java.util.Random;

public class Mainframe {
    private JFrame f;
    Box box;
    JScrollPane scrollPane;
    Random rand = new Random();

    public static void main(String[] args) {
        new Mainframe().go();
    }

    private void go() {
        box = new Box(BoxLayout.Y_AXIS);

        JLabel label = new JLabel("Possible Paths and Total Distances");
        label.setForeground(Color.RED);

        for (int i = 0; i < 200; i  ) {
            box.add(Box.createRigidArea(new Dimension(0, 2)));// creates space between the components
            box.add(new JLabel(i   " : "   rand.nextInt(10000)));
        }

        scrollPane = new JScrollPane(box);
        Dimension dim = new Dimension(box.getComponent(0).getPreferredSize());
        scrollPane.getVerticalScrollBar().setUnitIncrement(dim.height * 2); // adjusts scrolling speed
        scrollPane.getViewport().setBackground(Color.WHITE);

        f = new JFrame();
        f.getContentPane().add(label, BorderLayout.NORTH);
        f.getContentPane().add(scrollPane, BorderLayout.CENTER);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(640, 480);
        f.setLocationRelativeTo(null);
        f.setVisible(true);

    }
}
  •  Tags:  
  • Related