java - 使 JTextArea 在 Swing 中可滚动

标签 java swing

如何才能使我的 JTextArea 可以滚动。我想让 keysDisplay 有一个滚动条,可用于滚动文本区域。我跳过了 jFramePrint() 中一些无关的代码。

public class ApplicationViewer extends JFrame {

    private JTabbedPane tabs = new JTabbedPane();
    private JTextArea keyGenDisplay = new JTextArea();
    private JTextArea keysDisplay = new JTextArea();

    private JPanel controlPanel = new JPanel();
    private JButton addNumber = new JButton("Add Number");
    private JButton addLetter = new JButton("Add Letter");
    private JButton addHyphen = new JButton("Add Hyphen");
    private JButton calculateButton = new JButton("Calculate Key");

    private JTextField amountField = new JTextField("", 6);
    private JLabel amountLabel = new JLabel("  Amount of Keys :   ");
    private JScrollPane scroll = new JScrollPane(keysDisplay);

    public void jFramePrint() {

        this.setLayout(new BorderLayout());
        this.add(controlPanel, BorderLayout.SOUTH);


        controlPanel.add(addNumber);
        controlPanel.add(addLetter);
        controlPanel.add(addHyphen);
        controlPanel.add(amountLabel);
        controlPanel.add(amountField);
        controlPanel.add(calculateButton);

        this.add(scroll);

        this.setSize(1400, 900);
        this.setTitle("Key Generator");
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);

        keyGenDisplay.append("Key Format: ");
        keysDisplay.append("Keys Here: ");

        tabs.add("Key Generator", keyGenDisplay);
        tabs.add("Keys", keysDisplay);

        this.add(tabs);
        this.setVisible(true);

    }
}

最佳答案

private JTextArea keysDisplay = new JTextArea();

首先你应该使用类似的东西:

private JTextArea keysDisplay = new JTextArea(5, 20);

这将允许文本区域计算其自己的首选大小。当滚动条添加到滚动 Pane 并且超过 5 行文本添加到文本区域时,滚动条将正常工作。

this.add(scroll);

...

this.add(tabs);

您的框架正在使用BorderLayout。当您不使用约束时,“默认使用 CENTER”。

您不能将多个组件添加到 BorderLayout 的同一区域。因此仅显示最后添加的组件。

为选项卡组件指定不同的约束。

关于java - 使 JTextArea 在 Swing 中可滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43354772/

相关文章:

java - AudioRecord 线程中的处理

java - 如何在 Java 中获取 protobuf 重复字段构建器?

swing - Scala Swing ListView 的移除/添加元素事件

java - 在主类之外使用 Java 的 2d 图形

java - 为什么 JList 参数化没有破坏 Java 中的兼容性?

java - 用java实现书签列表

java - Jython 独立 jar 和包

java - Java中的函数数组?

java - 在 Jpanel 上放置组件

java - 比较 Google 表格中的日期