Java Swing Panel layout

20,936

Solution 1

What you want is called the BoxLayout, which feeds UI elements in columns or rows. And then you can nest them one inside another, e.g. have one horizontal box layout panel as an element in another that is vertical (kind of like nested HTML tables). So all of your elements would go in a top level vertical BoxLayout and the line that has JLabel2 and JTextField would be its own horizontal BoxLayout nested in the top level vertical layout. Here is a pretty decent tutorial about layout managers and it includes the BoxLayout.

Solution 2

There are many different ways, and many different LayoutManagers to use. Read up some more on them here:

Here is an example I made which uses GridBagLayout:

enter image description here

//necessary imports
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;

public class Test {

    /**
     * Default constructor for Test.class
     */
    public Test() {
        initComponents();
    }

    public static void main(String[] args) {
        /**
         * Set look and feel of app
         */
        try {
            for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (Exception e) {
            // If Nimbus is not available, you can set the GUI to another look and feel.
        }
        /**
         * Create GUI and components on Event-Dispatch-Thread
         */
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                Test test = new Test();
            }
        });
    }

    /**
     * Initialize GUI and components (including ActionListeners etc)
     */
    private void initComponents() {

        JFrame jFrame = new JFrame("Chat Test");
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jFrame.setResizable(false);

        //Initialise Panel 1 & Components
        JPanel p1 = new JPanel(new GridBagLayout());
        JPanel p2 = new JPanel(new GridBagLayout());
        //Label 1 - For TextArea
        JLabel l1 = new JLabel("Chat Log");
        //TextArea - To display conversation
        final JTextArea t1 = new JTextArea(10, 10);
        JScrollPane pane = new JScrollPane(t1);
        //Label 2 - For TextField
        JLabel l2 = new JLabel("Message");
        //Message Box - For user input
        final JTextField t2 = new JTextField(10);
        //Button 1 - To send message
        JButton b1 = new JButton("Send");

        GridBagConstraints gc = new GridBagConstraints();

        gc.fill = GridBagConstraints.HORIZONTAL;
        gc.weightx = 1;
        gc.gridx = 0;
        gc.gridy = 0;
        p1.add(l1, gc);

        gc.gridx = 0;
        gc.gridy = 1;
        p1.add(pane, gc);

        GridBagConstraints gc2 = new GridBagConstraints();
        gc2.fill = GridBagConstraints.HORIZONTAL;
        gc2.weightx = 1;
        gc2.gridx = 0;
        gc2.gridy = 0;
        gc2.ipadx = 10;
        p2.add(l2, gc2);

        gc2.gridx = 1;
        gc2.gridy = 0;
        p2.add(t2, gc2);

        gc2.gridx = 1;
        gc2.gridy = 1;
        p2.add(b1, gc2);

        b1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ev) {
                //do something
                t1.setText(t2.getText());
            }
        });

        jFrame.add(p1, BorderLayout.CENTER);
        jFrame.add(p2, BorderLayout.SOUTH);

        //pack frame (size JFrame to match preferred sizes of added components and set visible
        jFrame.pack();
        jFrame.setVisible(true);
    }
}
Share:
20,936
Javacadabra
Author by

Javacadabra

Updated on October 27, 2020

Comments

  • Javacadabra
    Javacadabra over 3 years

    I am working on a Java project for college that involves us setting up a TCP Server and Client. I have that part working and now to add more of a feel to my project I want to add a GUI.

    We have not begun learning about GUI's in Java yet. However I want to try as I think it would be a useful exercise. I have a very basic GUI set up and the appropriate ActionListener set for the button. My next problem is positioning my panels so they look neat and tidy on the Frame...

    At the moment I have all the components in one panel as seen below:

    public ClientGUI(){
    
        //Initialise Frame
        frame = new JFrame("TCP Client");
    
        //Initialise Panel 1 & Components
        p1 = new JPanel();
    
        //Set Layout
        p1.setLayout(new GridLayout(1,2));
    
        //Label 1 - For TextArea
        l1 = new JLabel("Chat Log");
        p1.add(l1);
    
        //TextArea - To display conversation
        t1 = new JTextArea(10,10);
        p1.add(t1);
    
        //Label 2 - For TextField
        l2 = new JLabel("Message");
        p1.add(l2);
    
        //Message Box - For user input
        t2 = new JTextField(10);
        p1.add(t2);
    
        //Button 1 - To send message
        b1 = new JButton("Send");
        p1.add(b1);
    
        //Add panels to frame
        frame.add(p1);
    
        //Frame properties...
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400,400);
        frame.setVisible(true);
    
        //Add Event listener to button
        b1.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent ev){
                //do something
                t1.setText(t2.getText());
            }
        });
    

    I would love for it to look something like the rough wireframe below.

    Desired Layout

    I'd appreciate any feedback anyone might have! Thanks very much.