将滚动条添加到JTextArea

时间:2018-02-03 23:41:51

标签: java swing jscrollpane jtextarea

我正在尝试将Vertical Scroll Bar添加到logConsole(这是一个JTextArea)。但是,在遵循了一些关于如何执行此操作的指南后,我仍然无法在我的GUI中显示滚动条。

请找到以下代码。

非常感谢任何帮助。

谢谢!

class GUIFrame extends JFrame {
    static JTextArea logConsole = new JTextArea();
    static JTextField gameConsole;
    private static JFrame frame = new JFrame("Game Text Console - Cluedo Client v0.1");
    private static JPanel panel = new JPanel();
    private static ButtonListener buttonListener = new ButtonListener();
    private static JTextArea instruction = new JTextArea();

    static void createFrame(){

        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        logConsole.setEditable(false);

        panel.setLayout(new FlowLayout());
        gameConsole = new JTextField(20); // LOG CONSOLE = Output uneditable
        JButton enterButton = new JButton("Enter");
        enterButton.setActionCommand("Enter");
        enterButton.addActionListener(buttonListener);
        gameConsole.setActionCommand("Enter");  //GAME CONSOLE = Input editable
        gameConsole.addActionListener(buttonListener);

        DefaultCaret caret = (DefaultCaret) logConsole.getCaret();  // set update constantly on for logConsole
        caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);

        logConsole.setPreferredSize(new Dimension(500, 100));
        panel.setPreferredSize(new Dimension( 1000,300));

        instruction.setOpaque(true);
        instruction.setText("Enter the commands here:");
        logConsole.setText("Previous events in Game: \n\n");

        JScrollPane jp = new JScrollPane(logConsole); //Add scrollbars.
        jp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

        panel.add(instruction);
        panel.add(gameConsole);
        panel.add(enterButton);
        panel.add(logConsole);
        //frame.add(jp);
        frame.getContentPane().add(BorderLayout.CENTER, panel);
        frame.pack();
        frame.setVisible(true);

        panel.requestFocus();

    }
}

1 个答案:

答案 0 :(得分:1)

开始

摆脱logConsole.setPreferredSize(new Dimension(500, 100));并将panel.add(logConsole);替换为panel.add(jp);

为什么?

setPreferredSize将修复文本区域的大小,防止文本区域在文本更改时增长(或缩小)。默认情况下,JTextArea会根据preferredSize属性计算text

如果您想影响“默认的可滚动视口大小”,那么您应该使用columnsrows属性,您可以通过JTextArea(rows, columns)构造函数轻松指定这些属性。这提供了一种独立于平台的方式来指定JTextArea

所需的可视区域

通过将logConsole添加到panel,您首先将其从JScrollPane中删除,这样就有点失败了

我建议花一些时间查看How to use scroll panes和可用的示例