更改JTextArea的大小

时间:2014-07-13 21:10:03

标签: java swing jtextarea

我正在尝试创建一个简单的GUI,其中两个JTextAreas相互叠加。我已经能够做到这一点,但我希望底部的JTextArea大约是顶部的一半,并且无法弄清楚如何实现这一目标。我已经尝试更改JTextArea中的行数,但这没有用。这是我的代码:

public final class View extends JFrame implements ViewInterface {

/**
 * Controller object.
 */
private Controller controller;

/**
 * Constants
 */
private static final int LINES_IN_TOP_TEXT = 4,
        LINE_LENGTHS_IN_TOP_TEXT = 8, LINES_IN_BOTTOM_TEXT = 1,
        LINE_LENGTHS_IN_BOTTOM_TEXT = 8, ROWS_IN_THIS_GRID = 2,
        COLUMNS_IN_THIS_GRID = 1;

/**
 * Text areas.
 */
private final JTextArea topText;

private final JTextArea bottomText;

/**
 * Default constructor.
 */
public View() {

    /*
     * Call JFrame superclass with title
     */
    super("Two JTextAreas");

    /*
     * Create widgets
     */
    this.topText = new JTextArea("", LINES_IN_TOP_TEXT,
            LINE_LENGTHS_IN_TOP_TEXT);

    this.bottomText = new JTextArea("", LINES_IN_BOTTOM_TEXT,
            LINE_LENGTHS_IN_BOTTOM_TEXT);

    /*
     * Customize font of top text
     */
    Font topFont = new Font("TimeRoman", Font.BOLD, 30);
    this.topText.setFont(topFont);
    this.topText.setForeground(Color.WHITE);
    this.topText.setBackground(Color.RED);

    /*
     * Customize font of bottom text
     */
    Font bottomFont = new Font("TimeRoman", Font.BOLD, 12);
    this.bottomText.setFont(bottomFont);
    this.bottomText.setForeground(Color.WHITE);
    this.bottomText.setBackground(Color.RED);

    /*
     * Text areas should wrap lines, and outputText should be read-only
     */
    this.topText.setEditable(false);
    this.topText.setLineWrap(true);
    this.topText.setWrapStyleWord(true);
    this.bottomText.setEditable(false);
    this.bottomText.setLineWrap(true);
    this.bottomText.setWrapStyleWord(true);

    /*
     * Create scroll panes for the text areas
     */
    JScrollPane topTextScrollPane = new JScrollPane(this.topText);
    JScrollPane bottomTextScrollPane = new JScrollPane(this.bottomText);

    /*
     * Organize main window using grid layout
     */
    this.setLayout(new GridLayout(ROWS_IN_THIS_GRID, COLUMNS_IN_THIS_GRID));

    /*
     * Add scroll panes and button panel to main window
     */
    this.add(topTextScrollPane);
    this.add(bottomTextScrollPane);

    /*
     * Start the main application window
     */
    this.pack();
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setVisible(true);
}
}

任何人都知道如何解决这个问题?谢谢!

2 个答案:

答案 0 :(得分:3)

将JTextArea行或列设置为所需的首选大小。如果一个人的身高与另一个身高相同,那就要给它一半的行数。

此外,您的布局GridLayout将忽略行计数,而是使所有组件保持相同的大小,基本上是容纳所有组件的最大大小。而是使用更好的布局管理器,例如BoxLayout。如,

  // this.setLayout(new GridLayout(ROWS_IN_THIS_GRID, COLUMNS_IN_THIS_GRID));
  setLayout(new BoxLayout(this.getContentPane(), BoxLayout.PAGE_AXIS));

答案 1 :(得分:2)

您可以使用Java Layout Manager

或者使用setSize和setPreferedSize