public void NewMessage(){
JPanel panel = new JPanel();
JLabel label = new JLabel("Enter message:");
JTextArea msgBodyContainer = new JTextArea(10,20);
msgBodyContainer.setAutoscrolls(true);
panel.add(label);
panel.add(msgBodyContainer);
String[] options = new String[]{"OK", "Cancel"};
int option = JOptionPane.showOptionDialog(null, panel, "Message "+searchedProfileFirstName,
JOptionPane.NO_OPTION, JOptionPane.PLAIN_MESSAGE,
null, options, options[1]);
if(option == 0) // pressing OK button
{
}
}
这是我在我定义的方法NewMessage()中使用的代码。 我的问题是我想防止这种情况发生: Picture of problem
1 - 可见,文本区域自动放大,并且在面板边界后不可见 2 - 标签“输入消息”向下移动到垂直居中与文本区域对齐
答案 0 :(得分:1)
JPanel
默认使用FlowLayout
JTextArea
这样的文字组件确实应该包含在JScrollPane
中,以允许它们变得比可用空间更大GridBagLayout
代替,它可以让您更好地控制布局JScrollPane
打包JTextArea
例如......
JPanel panel = new JPanel(new GridBagLayout());
JLabel label = new JLabel("Enter message:");
JTextArea msgBodyContainer = new JTextArea(10, 20);
msgBodyContainer.setAutoscrolls(true);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(4, 4, 4, 4);
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.fill = GridBagConstraints.HORIZONTAL;
panel.add(label, gbc);
gbc.gridx++;
gbc.fill = GridBagConstraints.BOTH;
gbc.anchor = GridBagConstraints.NORTHWEST;
panel.add(new JScrollPane(msgBodyContainer), gbc);
String[] options = new String[]{"OK", "Cancel"};
int option = JOptionPane.showOptionDialog(null, panel, "Message ",
JOptionPane.NO_OPTION, JOptionPane.PLAIN_MESSAGE,
null, options, options[1]);
请参阅:
了解更多详情