Aligning panels with GridBagLayout
Asked Answered
D

4

6

I'm not exactly new to java (I've been using it for a year now) but this is my first go at swing. I'm trying to make a very simple chat client to learn both socket and swing at once. My question is "What must I do to align my panels correctly?". I've tried a lot of things (Though I don't have it in my code). Usually I work something like this out on my own, but I'm to the point I need to ask for help. Do I need to change the wieghtx, weighty? What I want the client to look like is something like this.

enter image description here

This is what it currently looks like.

enter image description here

Here is my code.

package com.client.core;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;


public class Window extends JFrame{

private int screenWidth = 800;
private int screenHeight = 600;

public Window(){

    //Initial Setup
    super("NAMEHERE - Chat Client Alpha v0.0.1");
    setResizable(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(screenWidth,screenHeight);
    GridBagConstraints c = new GridBagConstraints();

    //Main Panel
    JPanel window = new JPanel();
    window.setLayout(new GridBagLayout());
    window.setBackground(Color.black);

    //Panels
    JPanel display = new JPanel();
    JPanel chat = new JPanel();
    chat.setLayout(new GridBagLayout());
    JPanel users = new JPanel();


    display.setBackground(Color.blue);
    c.gridx = 0;
    c.gridy = 0;
    c.insets= new Insets(5,5,5,5);
    window.add(display, c);

    chat.setBackground(Color.red);
    c.gridx = 0;
    c.gridy = 3;
    c.gridheight = 2;
    c.gridwidth = 1;
    c.insets= new Insets(5,5,5,5);
    window.add(chat, c);

    users.setBackground(Color.green);
    c.gridx = 2;
    c.gridy = 0;
    c.insets= new Insets(5,5,5,5);
    window.add(users, c);

    //Buttons


    //Text fields
    JTextArea text = new JTextArea("DEREADFADSFEWFASDFSADFASDF");
    c.gridx = 0;
    c.gridy = 0;
    chat.add(text);
    JTextField input = new JTextField("type here to chat", 50);
    c.gridx = 0;
    c.gridy = 1;
    c.insets= new Insets(5,5,5,5);
    chat.add(input);


    add(window);


}

static class ActLis implements ActionListener{

    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub

    }

}
}
Dalmatian answered 11/5, 2012 at 17:32 Comment(8)
GridBagLayout is fairly difficult to write with by hand, especially for people new to Swing. You could achieve that layout far more simply through the use of BorderLayout, having a panel for the left side that contains the three left side components.Koah
Agreed that GridBagLayout is overly complex, especially if you are new to swing. I recommend using either MigLayout or JGoodies FormLayout. The allow for complex layouts but make it a lot more clear on how to layout the panels.Clannish
Related: #10334059Spank
@Vulcan I'm trying to learn swing, not go with what is easiest. I'll give BorderLayout a try, I just thought GridBagLayout seemed the most versatile and be most useful to use in the long run.Dalmatian
@JeffStorey I want to try to learn the libraries included in java then I'll move on to use something like JGoodies.Dalmatian
@Zexanima GridBagLayout is generally intended for GUI builders rather than hand coding. It's possible to do, but terribly inconvenient. GridBagLayout is the most versatile, you're right, but if you want to make extremely complex GUIs, you should use a GUI builder tool such as Netbeans GUI builder or JFormDesigner.Koah
@Zexanima, while I understand that, GridBagLayout is not usually used in practice (in my experiences) because of its complexity. There is definite value in learning the layouts that you will likely use like BorderLayout, GridLayout, etc. But take advantage of the fact that these other layout managers exist.Clannish
I kind of disagree that GridBagLayout should only be used with GUI builders. I personnally don't like GUI builders, but that's religious. GridBagLayout has some basic concepts that may look difficult to learn but are actually quite logic. The parallel with HTML table is obvious and basing your thinking on that makes it not that hard to master. Combine a GridBagLayout with a Model, and it becomes both very powerful and easy to write. For what it's worth, I tend to use mainly BorderLayout, GridBagLayout and sometimes FlowLayout.Nutritious
P
3

What you could do, and probably gives the desired result

JPanel somethingHere = ...;
JPanel chat = ...;
JPanel userList = ...;

JPanel leftPanel = new JPanel( new BorderLayout() );
leftPanel.add( somethingHere, BorderLayout.CENTER );
leftPanel.add( chat, BorderLayout.SOUTH );

JPanel total = new JPanel( new BorderLayout() );
total.add( leftPanel, BorderLayout.CENTER );
total.add( userList, BorderLayout.EAST );

Way simpler then messing with GridBagLayout

Pestiferous answered 11/5, 2012 at 17:50 Comment(4)
Alright, you're the second one to suggest BorderLayout so I will give it a try. Thank you!Dalmatian
@Pestiferous : I had tried this once with BorderLayout, sometimes what happens, since the JTextArea will be empty at the start, it occupies way too less spece, which sometimes is not appealing to the eyes, so either too much of Nesting you have to do, to achieve the desired result. hence sometimes GridBagLayout do comes in handy for such situations. +1 though for the try :-)Demasculinize
@nIcEcOw Typically a JTextArea will be contained in a scrollpane and then you manually set the number of rows/columns. And if you put the scrollpane in the center you can enlarge it afterwards by resizing the framePestiferous
@Pestiferous : That's the point, since as your messenger will start, you won't expect someone to enlarge it by dragging first, to see what the window says, moreover, it's the component on the RIGHT/LEFT side, CENTER component is good to go with BorderLayout, since BorderLayout never bothers about the size, it gives it's own sizes depending on the actual window :-)Demasculinize
D
4

If you wanted something like this as an output :

MESSENGER WINDOW

You can take help from this code example, though you can remove the last ButtonPanel if you don't need that :

package to.uk.gagandeepbali.swing.messenger.gui;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Color;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.JTextField;

public class ChatPanel extends JPanel
{
    private JButton backButton;
    private JButton exitButton;
    private JButton sendButton;

    private JTextPane chatPane;
    private JTextPane namePane;
    private JTextField chatField;

    private GridBagConstraints gbc;

    private final int GAP = 10;
    private final int SMALLGAP = 1;

    public ChatPanel()
    {
        gbc = new GridBagConstraints();
    }

    protected void createGUI()
    {
        setOpaque(true);
        setBackground(Color.WHITE);
        setLayout(new BorderLayout(5, 5));

        JPanel centerPanel = new JPanel();
        centerPanel.setOpaque(true);
        centerPanel.setBackground(Color.WHITE);
        centerPanel.setBorder(BorderFactory.createEmptyBorder(GAP, GAP, 0, GAP));
        centerPanel.setLayout(new GridBagLayout());
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 5;
        gbc.weightx = 0.8;
        gbc.weighty = 1.0;
        gbc.fill = GridBagConstraints.BOTH;
        gbc.anchor = GridBagConstraints.FIRST_LINE_START;
        chatPane = new JTextPane();
        JScrollPane scrollerChat = new JScrollPane();
        scrollerChat.setBorder(BorderFactory.createTitledBorder("Chat"));
        scrollerChat.setViewportView(chatPane);
        centerPanel.add(scrollerChat, gbc);

        gbc.gridx = 5;
        gbc.gridwidth = 2;
        gbc.weightx = 0.2;
        namePane = new JTextPane();
        JScrollPane scrollerName = new JScrollPane(namePane);
        scrollerName.setBorder(BorderFactory.createTitledBorder("Names"));
        centerPanel.add(scrollerName, gbc);

        gbc.gridx = 0;
        gbc.gridy = 5;
        gbc.gridwidth = 5;
        gbc.weightx = 0.8;
        gbc.weighty = 0.1;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        chatField = new JTextField();
        chatField.setOpaque(true);
        chatField.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createTitledBorder("")
                , BorderFactory.createEmptyBorder(SMALLGAP, SMALLGAP, SMALLGAP, SMALLGAP)));
        centerPanel.add(chatField, gbc);

        gbc.gridx = 5;
        gbc.gridwidth = 2;
        gbc.weightx = 0.2;
        sendButton = new JButton("Send");
        sendButton.setBorder(BorderFactory.createTitledBorder(""));
        centerPanel.add(sendButton, gbc);       

        JPanel bottomPanel = new JPanel();
        bottomPanel.setOpaque(true);
        bottomPanel.setBackground(Color.WHITE);
        bottomPanel.setBorder(
                BorderFactory.createTitledBorder(""));
        bottomPanel.setLayout(new BorderLayout());

        JPanel buttonPanel = new JPanel();
        buttonPanel.setOpaque(true);
        buttonPanel.setBackground(Color.WHITE);
        buttonPanel.setBorder(BorderFactory.createEmptyBorder(GAP, GAP, 0, GAP));
        backButton = new JButton("Back");
        exitButton = new JButton("Exit");
        buttonPanel.add(backButton);
        buttonPanel.add(exitButton);
        bottomPanel.add(buttonPanel, BorderLayout.CENTER);

        add(centerPanel, BorderLayout.CENTER);
        add(bottomPanel, BorderLayout.PAGE_END);
    }

    public JTextPane getChatPane()
    {
        return chatPane;
    }

    public JTextPane getNamePane()
    {
        return namePane;
    }

    public JTextField getChatField()
    {
        return chatField;
    }

    public JButton getExitButton()
    {
        return exitButton;
    }   

    public JButton getBackButton()
    {
        return backButton;
    }

    public JButton getSendButton()
    {
        return sendButton;
    }
}
Demasculinize answered 12/5, 2012 at 4:54 Comment(2)
Thanks for the help! I found what I wanted just messing with BoxLayout though.Dalmatian
@Zexanima : You're MOST WELCOME and KEEP SMILING :-). Glad you got it :-)Demasculinize
P
3

What you could do, and probably gives the desired result

JPanel somethingHere = ...;
JPanel chat = ...;
JPanel userList = ...;

JPanel leftPanel = new JPanel( new BorderLayout() );
leftPanel.add( somethingHere, BorderLayout.CENTER );
leftPanel.add( chat, BorderLayout.SOUTH );

JPanel total = new JPanel( new BorderLayout() );
total.add( leftPanel, BorderLayout.CENTER );
total.add( userList, BorderLayout.EAST );

Way simpler then messing with GridBagLayout

Pestiferous answered 11/5, 2012 at 17:50 Comment(4)
Alright, you're the second one to suggest BorderLayout so I will give it a try. Thank you!Dalmatian
@Pestiferous : I had tried this once with BorderLayout, sometimes what happens, since the JTextArea will be empty at the start, it occupies way too less spece, which sometimes is not appealing to the eyes, so either too much of Nesting you have to do, to achieve the desired result. hence sometimes GridBagLayout do comes in handy for such situations. +1 though for the try :-)Demasculinize
@nIcEcOw Typically a JTextArea will be contained in a scrollpane and then you manually set the number of rows/columns. And if you put the scrollpane in the center you can enlarge it afterwards by resizing the framePestiferous
@Pestiferous : That's the point, since as your messenger will start, you won't expect someone to enlarge it by dragging first, to see what the window says, moreover, it's the component on the RIGHT/LEFT side, CENTER component is good to go with BorderLayout, since BorderLayout never bothers about the size, it gives it's own sizes depending on the actual window :-)Demasculinize
D
1

Here is what I came out with thus far. The red box is where I plan to add a simple 2D avatar interface with LWJGL.

enter image description here

Here is the code for it

package com.client.core;

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;


public class Window extends JFrame{

private int screenWidth = 800;
private int screenHeight = 600;

public Window(){

    //Initial Setup
    super("NAMEHERE - Chat Client Alpha v0.0.1");
    setResizable(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(screenWidth,screenHeight);


    //Main Panels
    JPanel window = new JPanel(new BorderLayout());
    JPanel center = new JPanel(new BorderLayout());
    JPanel right = new JPanel(new BorderLayout());


    //Panels
    JPanel display = new JPanel( new BorderLayout());
    display.setBackground(Color.red);
    JPanel chat = new JPanel();
    chat.setLayout(new BoxLayout(chat, BoxLayout.Y_AXIS));
    chat.setBackground(Color.blue);
    JPanel users = new JPanel(new BorderLayout());
    users.setBackground(Color.green);


    //TextFields
    JTextArea chatBox = new JTextArea("Welcome to the chat!", 7,50);
    chatBox.setEditable(false);
    JTextField chatWrite = new JTextField();
    JScrollPane userList = new JScrollPane();
    JTextField userSearch = new JTextField(10);
    userList.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    users.add(userList);
    users.add(userSearch, BorderLayout.NORTH);
    chat.add(chatBox);
    chat.add(chatWrite);
    chat.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));

    //Menu bar
    JMenuBar menu = new JMenuBar();
        JMenu file = new JMenu("File");
            JMenuItem exit = new JMenuItem("Exit");
            JMenuItem ipconnect = new JMenuItem("Connect to IP");
    file.add(ipconnect);
    file.add(exit);
    menu.add(file);


    //Main window adding
    right.add(users);
    center.add(display, BorderLayout.CENTER);
    center.add(chat, BorderLayout.SOUTH);
    window.add(center, BorderLayout.CENTER);
    window.add(right, BorderLayout.EAST);
    window.add(menu, BorderLayout.NORTH);
    add(window);




    //Listeners
    chatWrite.addKeyListener(new KeyLis());
    ipconnect.addActionListener(new ActLis());
    exit.addActionListener(new ActLis());
}







static class KeyLis implements KeyListener{

    @Override
    public void keyPressed(KeyEvent e) {
        if(e.getKeyCode() == KeyEvent.VK_ENTER){
            System.out.println("Message recieved.");
        }

    }

    @Override
    public void keyReleased(KeyEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void keyTyped(KeyEvent e) {
        // TODO Auto-generated method stub

    }



}

static class ActLis implements ActionListener{

    @Override
    public void actionPerformed(ActionEvent e) {
    if(e.getActionCommand() == "Exit"){
        System.exit(0);
    } else if(e.getActionCommand() == "Connect to IP"){
        System.out.println("Connecting....");
        JFrame frameip = new JFrame();
        JPanel panelip = new JPanel();  
        JButton buttonip = new JButton("Hello");
        frameip.add(panelip);
        panelip.add(buttonip);
        JDialog ippop =  new JDialog(frameip, "Enter IP", false);
    }


    }
}
}
Dalmatian answered 12/5, 2012 at 16:46 Comment(2)
Ahha, that's good :-) , let me try my hands on this, if I be able to do this with GridBag, will let you know, on this :-)Demasculinize
This looks good in itself I guess, no need for GridBagLayout I guess :-) Too GOODDemasculinize
C
0

I had to build a similar layout using a GridBagLayout. The code below shows how I achieved it.

enter image description here

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class GridBagLayoutTest {
    public GridBagLayoutTest() {
    
    JFrame jframe = new JFrame();
    jframe.setLayout(new GridBagLayout());
    jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jframe.setSize(800, 600);
    jframe.setVisible(true);
    
    // Left
    JPanel leftPanel = new JPanel(new GridBagLayout());
    leftPanel.setBackground(Color.YELLOW);
    
    GridBagConstraints gridBagConstraints = new GridBagConstraints();
    gridBagConstraints.fill = GridBagConstraints.BOTH;
    gridBagConstraints.weightx = .7f;
    gridBagConstraints.weighty = 1f;
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 0;
    
    jframe.add(leftPanel, gridBagConstraints);
    
    JPanel leftTopPanel = new JPanel(new FlowLayout());
    leftTopPanel.setBackground(Color.RED);
    
    GridBagConstraints gridBagConstraints0 = new GridBagConstraints();
    gridBagConstraints0.fill = GridBagConstraints.BOTH;
    gridBagConstraints0.weightx = 1f;
    gridBagConstraints0.weighty = .7f;
    gridBagConstraints0.gridx = 0;
    gridBagConstraints0.gridy = 0;
    
    leftPanel.add(leftTopPanel, gridBagConstraints0);
    
    JPanel leftMiddlePanel = new JPanel(new FlowLayout());
    leftMiddlePanel.setBackground(Color.BLACK);
    
    gridBagConstraints0 = new GridBagConstraints();
    gridBagConstraints0.fill = GridBagConstraints.BOTH;
    gridBagConstraints0.weightx = 1f;
    gridBagConstraints0.weighty = .2f;
    gridBagConstraints0.gridx = 0;
    gridBagConstraints0.gridy = 1;
    
    leftPanel.add(leftMiddlePanel, gridBagConstraints0);
    
    JPanel leftBottomBottomPanel = new JPanel(new FlowLayout());
    leftBottomBottomPanel.setBackground(Color.PINK);
    
    gridBagConstraints0 = new GridBagConstraints();
    gridBagConstraints0.fill = GridBagConstraints.BOTH;
    gridBagConstraints0.weightx = 1f;
    gridBagConstraints0.weighty = .1f;
    gridBagConstraints0.gridx = 0;
    gridBagConstraints0.gridy = 2;
    
    leftPanel.add(leftBottomBottomPanel, gridBagConstraints0);
    
    // Right
    JPanel rightPanel = new JPanel();
    rightPanel.setBackground(Color.GREEN);
    
    gridBagConstraints = new GridBagConstraints();
    gridBagConstraints.fill = GridBagConstraints.BOTH;
    gridBagConstraints.weightx = .3f;
    gridBagConstraints.weighty = 1f;
    gridBagConstraints.gridx = 1;
    gridBagConstraints.gridy = 0;
    
    jframe.add(rightPanel, gridBagConstraints);
}


public static void main (String args[]) {
    new GridBagLayoutTest();
}
Covarrubias answered 9/2, 2022 at 6:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.