Search code examples
javaswingresizejscrollpane

How do I set the size and location of a JScrollPane?


I'm trying to set the size and location of a JScrollPane in a JFrame, and it's JViewport is a JTextArea.

The following is the code I am using:

private static JFrame frame = new JFrame();

public static void main(String... args) {
    frame.setTitle("Friend App");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(800, 600);
    JTextArea textArea = new JTextArea();
    JScrollPane scrollPane = new JScrollPane(textArea);
    scrollPane.setLayout(null);
    scrollPane.setLocation(30, 30);
    scrollPane.setSize(new Dimension(100, 100));
    frame.add(scrollPane);
    textArea.append("test");
    frame.setVisible(true);

}

What else am I supposed to do so I can resize and set the location of this JScrollPane? Am I using the best approach here?

Note: scrollPane.setLayout(null) does nothing, frame.pack() is not what I want.


Solution

  • The scrollPane is added to JFrame's content pane which has BorderLayout by default. The BorderLayout ignores location and size of component.

    You should use another LayoutManager (alternatively you can use null layout for the content pane but it's not good way).