如何设置 JScrollPane 的大小和位置?

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

我正在尝试在 JFrame 中设置 JScrollPane 的大小和位置,而 JViewportJTextArea

以下是我使用的代码:

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

}

我还应该做什么才能调整此 JScrollPane 的大小和位置?我在这里使用的是最佳方法吗?

注意:scrollPane.setLayout(null)什么都不做,frame.pack()不是我想要的。

ScrollPane 添加到 JFrame 的内容窗格中,默认情况下具有 BorderLayout。 BorderLayout 忽略组件的位置和大小。

您应该使用另一个 LayoutManager(或者您可以对内容窗格使用空布局,但这不是好方法)。