As per a JScrollPane in a JTextArea?

1

I'm trying to create a project where I print multiple phrases in a JTextArea , but for this, I need to include a JScrollPane . I looked at some examples on the internet but none are working.

public class Projeto extends JFrame {

    JPanel painel = new JPanel();
    public static JTextArea textarea = new JTextArea();
    public static JScrollPane sp = new JScrollPane();
    JButton cmd1;

public static void main(String[] args) {
   new Projeto();
}

public Projeto(){
    super("Árvore");
    setResizable(false);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setLocationRelativeTo(null);

    painel.setPreferredSize(new Dimension(600,400));
    painel.setLayout(null);

    cmd1 = new JButton("Start!");
    cmd1.setBounds(450, 50, 100, 30);
    painel.add(cmd1);

    textarea.setBounds(50, 50, 300, 300);
    textarea.setEditable(true);
    sp.add(textarea);

    painel.add(sp);       

    add(painel);
    pack();

    setVisible(true);

    event e = new event();
    cmd1.addActionListener(e);            
}

public static void atualiza(String frase){
    textarea.append(frase);
}   

public class event implements ActionListener{
    Pai p = new Pai();
    public void actionPerformed(ActionEvent e){

        p.start();                       
    }          
}   
}
    
asked by anonymous 22.08.2017 / 14:01

1 answer

2

Set JTextArea to portview of JScrollPane :

sp.setViewportView(textarea);

A JScrollPane is a flexible container, which adapts as a component added to it. But for this, this component needs to be a viewPort of the scrollable panel. This is only possible by passing the component to the panel in your builder when you start it, or by using the setViewportView() ". The add method does not work correctly for this particular panel.

A tip:

  

Avoid using absolute layout unless you are in dire need and know the consequences , because absolute layout makes it difficult to maintain the screen and make your application look different depending on the monitor and resolution being executed.

     

There are several layouts managers for you to you do not have to worry about manual positioning or organization of components. Not to mention that the use of layouts makes your code easier to maintain than inserting a lot of setbounds , and in case you need to change the position of some component, you will have to position all of them manually.

In your code, using absolute layout, JTextArea will never be displayed, because you have defined a size and position for it, but for the scrollpane there is nothing about its size and position. With the change below, the component is normally displayed:

sp.setBounds(50, 50, 300, 300);
textarea.setEditable(true);
sp.setViewportView(textarea);
    
22.08.2017 / 14:03