JTextArea滚动无法正常工作

时间:2014-11-18 05:12:36

标签: java swing jscrollpane

我正在尝试使JTextArea可以垂直滚动。我做了一些研究,我非常确定我使用的是LayoutManager,而不是直接将JTextArea添加到父面板,并且正在设置JTextArea和JScrollPane的首选大小。不确定我在这里缺少什么...这里是代码:

public class ConsolePane extends JDialog {
    private static final long serialVersionUID = -5034705087218383053L;

    public static final Dimension CONSOLE_DIALOG_SIZE = new Dimension(400, 445);
    public static final Dimension CONSOLE_LOG_SIZE = new Dimension(400, 400);
    public static final Dimension CONSOLE_INPUT_SIZE = new Dimension(400, 25);

    private static ConsolePane instance = new ConsolePane();

    public static ConsolePane getInstance() {
        return instance;
    }

    private JTextArea taLog;
    private JTextField tfInput;

    public ConsolePane() {
        this.setTitle("Console");
        JPanel contentPane = new JPanel();
        this.setContentPane(contentPane);
        contentPane.setLayout(new BorderLayout());
        contentPane.add(createConsoleLog(), BorderLayout.CENTER);
        contentPane.add(createConsoleInput(), BorderLayout.SOUTH);
        contentPane.setPreferredSize(CONSOLE_DIALOG_SIZE);
    }

    private JComponent createConsoleLog() {
        taLog = new JTextArea();
        taLog.setLineWrap(true);
        taLog.setPreferredSize(CONSOLE_LOG_SIZE);

        ((DefaultCaret) taLog.getCaret())
                .setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);

        JScrollPane container = new JScrollPane(taLog);
        container
                .setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        container
                .setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        container.setPreferredSize(CONSOLE_LOG_SIZE);
        return container;
    }

    private JComponent createConsoleInput() {
        tfInput = new JTextField();
        tfInput.setPreferredSize(CONSOLE_INPUT_SIZE);
        tfInput.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                taLog.append(tfInput.getText() + "\r\n");
                tfInput.setText("");
            }
        });
        tfInput.requestFocus();
        return tfInput;
    }

    public static void main(String[] args) {
        ConsolePane.getInstance().pack();
        ConsolePane.getInstance().setVisible(true);
    }
}
提前谢谢!

2 个答案:

答案 0 :(得分:0)

请尝试以下代码,它可能会对您有所帮助

JTextArea txt=new JTextArea();
JScrollPane pane=new JScrollPane(txt,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

答案 1 :(得分:0)

自己想出来。 taLog.setPreferredSize()阻止了滚动。删除了,一切正常。大家帮忙。