将滚动条添加到 JTextArea



我正在尝试将垂直滚动条添加到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: nn");
        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();
    }
}

开始于

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

为什么?

setPreferredSize将固定文本区域的大小,防止它随着文本的变化而增大(或缩小(。 默认情况下,JTextArea将根据 text 属性计算其preferredSize

如果要影响"默认可滚动视口大小",则应使用 columnsrows 属性,这些属性可以通过 JTextArea(rows, columns) 构造函数轻松指定。这提供了一种独立于平台的方式来指定所需的JTextArea可视区域

通过将logConsole添加到panel,您首先将其从JScrollPane中删除,因此它有点违背了目的

我建议花一些时间查看如何使用滚动窗格和可用示例

最新更新