即使使用setLineWrap(true)& amp; JTextArea width也会随输入延伸。 setWrapStyleWord(真)

时间:2013-02-23 13:15:36

标签: java swing jpanel jscrollpane jtextarea

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

如果没有setLineWrap(true)setWrapStyleWord(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();
        }
    });
}
}

1 个答案:

答案 0 :(得分:6)

不要直接将文本区域添加到面板。将其放在JScrollPane中,然后将滚动窗格添加到面板中,如the tutorial中所述。