如何将 JScrollPane 添加到此 JTextArea?

how do i add a JScrollPane to this JTextArea?

(顺便说一句,我是 java 的新手) 我有一个未完成的程序,我想在 jtextarea 中添加一个 jscrollpane。但是我无法让它工作。我试过

add(new JScollPane(area));

没用。我试过了:

panel.add(new JScrollPane(area));

那也没用。我也试过:

area.add(pane);

和:

area.add(new JScrollPane());

但没有任何效果。帮助!!!看看

public class Constructor extends JFrame {
private static final long serialVersionUID = 123456789L;

    JScrollPane scroll;
    public JPanel panel;
    static JTextField field;
    static JTextArea area;
    String displayCommand, commandIs;

public Constructor() {

    panel = new JPanel();
    panel.setLayout(getLayout());
    panel.setSize(600, 450);

    scroll = new JScrollPane(area);
    scroll.setBounds(0, 0, 10, 395);


    field = new JTextField();
    field.setSize(595, 25);
    field.setLocation(0, 400);
    field.addActionListener(
            new ActionListener(){
            public void actionPerformed(ActionEvent event){
                showCommand(event.getActionCommand());
                field.setText("");
                }
            }
        );
    area = new JTextArea();
    area.setSize(595,395);
    area.setLocation(0,0);
    area.setEditable(false);
    area.setFont(new Font("Lucida Console", Font.BOLD, 13));
    area.setText("Welcome to JConsole! This Application is for executing commands."
            + "\nType help for more info");

    panel.add(new JScrollPane(area));
    panel.add(area);
    panel.add(field);
    add(panel);

}

这只是我的构造函数,代码中没有其他内容涉及 jscrollpane

您添加了 area 两次。第一个有 JScrollPane,第二个没有 JScrollPane。您应该删除第二部分。

panel.add(new JScrollPane(area));
//panel.add(area); Remove this part.

还要确保 area 的布局正确。默认情况下,JPanelFlowLayout,但对于 JTextArea,它应该在 BorderLayout 上,居中对齐。

你可以试试加这个

scroll.setViewportView(area);