Aueisbiejei3i939
Aueisbiejei3i939

Reputation: 101

Make JTextArea scrollable in Swing

How can I make it so my JTextArea is scrollable. I want to make it so that keysDisplay has a scrollbar which can be used to scroll through the text area. I have skipped some unrealated code in 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);

    }
}

Upvotes: 0

Views: 85

Answers (1)

camickr
camickr

Reputation: 324108

private JTextArea keysDisplay = new JTextArea();

First of all you should use something like:

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

This will allow the text area to calculate its own preferred size. Scrollbars will then work properly when added to a scrollpane and more than 5 rows of text are added to the text area.

this.add(scroll);

...

this.add(tabs);

Your frame is using a BorderLayout. When you don't use a constraint then "CENTER is used by default.

You can't add multile components to the same area of the BorderLayout. So only the last component added is displayed.

Specify a different constraint for the tabs component.

Upvotes: 1

Related Questions