【问题标题】:How can I get the JTextArea to appear above the JTextField?如何让 JTextArea 出现在 JTextField 上方?
【发布时间】:2021-05-08 14:41:00
【问题描述】:

当我使用BorderLayout 将它们都添加到SOUTH 时,只会出现JTextArea。我使用文本字段作为输入,然后在文本区域中显示为它上面的输出以及其他一些文本。

如果我将文本区域设置为NORTH,它可以工作,但它看起来不太好。

JPanel cmdPanel = new JPanel(new BorderLayout());

field = new JTextField(20);
cmdPanel.add(field, BorderLayout.SOUTH);

JTextArea output=new JTextArea();
output.setEditable(false);
output.setLineWrap(true);
cmdPanel.add(output, BorderLayout.SOUTH);

此图像显示了 TextArea 设置为 NORTH 时的外观。 我只是想让它出现在 TextField 上并向上移动 添加输出时的屏幕。

【问题讨论】:

标签: java swing layout-manager border-layout


【解决方案1】:

您尚未提供minimal, reproducible example,但从正在运行的应用程序的屏幕截图来看,您似乎在明确设置JFrame 的大小。而不是这样做,您应该调用方法pack。请注意,您应该在将JTextFieldJTextArea 添加到cmdPanel 以及在将cmdPanel 添加到JFrame 之后 调用该方法。此外,您应该在调用方法pack() 之后在JFrame 上调用方法setVisible

在将JTextArea 添加到cmdPanel 之前,您还应该确保它具有首选大小。一种方法是调用constructor,它采用行数和列数参数。

也许还可以将JTextArea 包装在JScrollPane 中,并使其成为cmdPanel 的“中心”组件?

JPanel cmdPanel = new JPanel(new BorderLayout());

field = new JTextField(20);
cmdPanel.add(field, BorderLayout.SOUTH);

JTextArea output=new JTextArea(10, 20);
output.setEditable(false);
output.setLineWrap(true);
JScrollPane scrollPane = new JScrollPane(output);
cmdPanel.add(scrollPane, BorderLayout.CENTER);

【讨论】:

    【解决方案2】:

    不能在同一位置添加两个组件(即 BorderLayout.PAGE_END)。要在同一位置添加更多组件,您应该创建一个 JPanel,在其上添加组件,然后将 JPanel 添加到所需位置(即 BorderLayout.PAGE_END)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-13
      • 1970-01-01
      • 2012-06-01
      • 1970-01-01
      • 2017-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多