如何自动滚动文本区域而不增加其大小

时间:2017-04-30 05:38:25

标签: java netbeans textarea panel jdialog

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 - 标签“输入消息”向下移动到垂直居中与文本区域对齐

1 个答案:

答案 0 :(得分:1)

  1. JPanel默认使用FlowLayout
  2. JTextArea这样的文字组件确实应该包含在JScrollPane中,以允许它们变得比可用空间更大
  3. Recomendation

    • 使用GridBagLayout代替,它可以让您更好地控制布局
    • 使用JScrollPane打包JTextArea

    例如......

    Example

        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]);
    

    请参阅:

    了解更多详情

相关问题