【问题标题】:how to auto scroll a text area without increasing its size如何在不增加其大小的情况下自动滚动文本区域
【发布时间】:2017-04-30 05:38:24
【问题描述】:
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-标签“输入消息”向下移动到垂直居中与文本区域对齐

【问题讨论】:

  • JTextArea 放入JScrollPane
  • 我试过这样做,然后说 panel.addScrollpane 和 scrollpane.addtextarea 东西滚动窗格本身最终没有显示

标签: java netbeans textarea panel jdialog


【解决方案1】:
  1. JPanel 默认使用FlowLayout
  2. JTextArea 这样的文本组件确实应该被包裹在JScrollPane 中,以允许它们变得比可用空间更大

推荐

  • 改用GridBagLayout,它可以让您更好地控制布局
  • 使用JScrollPaneJTextArea 包裹在

例如...

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

见:

更多详情

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多