Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aligning panels with GridBagLayout

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

    }

}
}
like image 696
cgasser Avatar asked May 11 '12 17:05

cgasser


People also ask

Why do we need layout management what is GridBagLayout?

The Java GridBagLayout class is used to align components vertically, horizontally or along their baseline. The components may not be of the same size. Each GridBagLayout object maintains a dynamic, rectangular grid of cells. Each component occupies one or more cells known as its display area.

What is the difference between grid and GridBagLayout?

A GridLayout puts all the components in a rectangular grid and is divided into equal-sized rectangles and each component is placed inside a rectangle whereas GridBagLayout is a flexible layout manager that aligns the components vertically and horizontally without requiring that the components be of the same size.

How does GridBagLayout work?

Essentially, GridBagLayout places components in rectangles (cells) in a grid, and then uses the components' preferred sizes to determine how big the cells should be. The following figure shows the grid for the preceding applet. As you can see, the grid has three rows and three columns.

What is Weightx GridBagLayout?

weightx and weighty are used to determine how to distribute space among columns and among rows. This values are important for specifying resizing behavior. If you do not specify any of weightx or weighty, all the components will clump together in the center of their container.


3 Answers

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;
    }
}
like image 190
nIcE cOw Avatar answered Oct 31 '22 22:10

nIcE cOw


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

like image 3
Robin Avatar answered Nov 01 '22 00:11

Robin


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


    }
}
}
like image 1
cgasser Avatar answered Oct 31 '22 22:10

cgasser