1

当框架出现时,JTextArea水平拉伸直到达到框架宽度大小,并且在调整框架大小时,JTextArea将再次拉伸以匹配框架的宽度。如果添加输入JTextArea,它将继续水平增长,而不是将文本换行到新行。

没有setLineWrap(true)andsetWrapStyleWord(true)JTextArea正确显示在框架上,但仍会JTextArea在第一行拉伸。

我该如何解决这个问题?

public class GridBagExample {

private JFrame frame;
private final JPanel panel;
private JLabel frontText, reverseText;
private JTextField frontTextField;
private final JTextArea reverseTextArea;
private GridBagLayout gridBagLayout;
private GridBagConstraints constraints;
private JButton submit, cancel;

public GridBagExample() {

    frame = new JFrame("Create new flashcard");
    gridBagLayout = new GridBagLayout();
    constraints = new GridBagConstraints();
    panel = new JPanel(gridBagLayout);
    panel.setSize(240,220);

    frontText = new JLabel("Front Text");
    constraints.ipadx = 1;
    constraints.ipady = 1;
    constraints.gridx = 0;
    constraints.gridy = 0;
    gridBagLayout.setConstraints(frontText, constraints);
    panel.add(frontText);

    frontTextField = new JTextField(15);
    constraints.ipadx = 1;
    constraints.ipady = 1;
    constraints.gridx = 2;
    constraints.gridy = 0;
    gridBagLayout.setConstraints(frontTextField, constraints);
    panel.add(frontTextField);

    reverseText = new JLabel("Reverse Text");
    constraints.ipadx = 1;
    constraints.ipady = 1;
    constraints.gridx = 0;
    constraints.gridy = 1;
    gridBagLayout.setConstraints(reverseText, constraints);
    panel.add(reverseText);

    reverseTextArea = new JTextArea(5,15);
    reverseTextArea.setWrapStyleWord(true);
    reverseTextArea.setLineWrap(true);
    constraints.ipadx = 1;
    constraints.ipady = 1;
    constraints.gridx = 2;
    constraints.gridy = 1;
    gridBagLayout.setConstraints(reverseTextArea, constraints);
    panel.add(reverseTextArea);


    submit = new JButton("Submit");
    constraints.ipadx = 1;
    constraints.ipady = 1;
    constraints.gridx = 2;
    constraints.gridy = 2;
    gridBagLayout.setConstraints(submit, constraints);
    panel.add(submit);

    frame.add(panel);
    frame.setSize(300, 300);
    frame.setVisible(true);
}

public static void main(String[] args) throws Exception {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            new GridBagExample();
        }
    });
}
}
4

1 回答 1

6

不要直接将文本区域添加到面板。将它放在 JScrollPane 中,并将滚动窗格添加到面板中,如教程中所述

于 2013-02-23T13:20:20.433 回答