简体   繁体   中英

how do i add a JScrollPane to this JTextArea?

(I'm new to java btw) i have this unfinished program that and I would like to add a jscrollpane to the jtextarea . However I can't get it to work. I've tried doing

add(new JScollPane(area));

which didn't work. I tried:

panel.add(new JScrollPane(area));

and that didnt't work either. I also tried:

area.add(pane);

and:

area.add(new JScrollPane());

but nothing works. HELP!!! take a look

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);

}

This is just my constructor bu nothing else in the code involves the jscrollpane .

You added area two times. First one with JScrollPane and second one without JScrollPane. You should remove second part.

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

Also make sure proper layout for area . By default JPanel is FlowLayout , but for JTextArea it should be on BorderLayout with CENTER alignment.

您可以尝试添加

scroll.setViewportView(area);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM