有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使JTextArea在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) 个答案

  1. # 1 楼答案

    private JTextArea keysDisplay = new JTextArea();
    

    首先,你应该使用以下方法:

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

    这将允许文本区域计算自己的首选大小。当滚动条被添加到滚动窗格中,并且文本区域中添加了5行以上的文本时,滚动条将正常工作

    this.add(scroll);
    
    ...
    
    this.add(tabs);
    

    您的帧正在使用BorderLayout。如果不使用约束,则默认情况下使用“中心”

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

    为选项卡组件指定其他约束