使JTextArea在Swing中可滚动

时间:2017-04-11 19:36:30

标签: 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);

    }
}

1 个答案:

答案 0 :(得分:1)

private JTextArea keysDisplay = new JTextArea();

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

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

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

this.add(scroll);

...

this.add(tabs);

您的相框正在使用BorderLayout。如果您不使用约束,则默认使用" CENTER。

您无法将多个组件添加到BorderLayout的同一区域。因此,只显示添加的最后一个组件。

为制表符组件指定不同的约束。