Search code examples
javaswingjlabellayout-managerjtextarea

About Java Layout


i still learning about java and i have simple code

import javax.swing.*;

Public class Test extends JFrame{
JLabel name = new JLabel("Name");
JTextArea ta = new JTextArea();

Test(){
    this.setSize(435, 400);
    this.setTitle("Test");
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    this.setLayout(null);
    name.setBounds(10, 10, 50, 20);
    this.add(name);
    ta.setBounds(90, 10, 300, 200); 
    ta.setLineWrap(true);
    JScrollPane scroll = new JScrollPane(ta);
    this.add(scroll);
}

public static void main(String [] args){
    new Test().setVisible(true);
}
}

What layout should i choose ? i want the textarea show beside the name label


Solution

  • If it's just a Label and a TextArea, just use a simple GridLayout

    Test(){
    
        setLayout(new GridLayout(1, 2));   // sets a Grid Layout with 1 row and 2 columns
        add(name);
    
        JScrollPane scroll = new JScrollPane(ta);
        ta.setLineWrap(true);
        add(scroll);
    
    
    }
    
    public static void main(String[] args) {
        JFrame frame = new Test();
        frame.setSize(435, 400);
        frame.setTitle("Test");
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.setVisible(true);
    }