当框架出现时,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();
}
});
}
}