I'm trying to create a calculator using the gridbag layout, but I can't even get started. This layout managers keeps starting stuff in the direct center of the frame and wont put anything anywhere else. I tried this:

c.anchor = GridBagConstraints.SOUTH;


I just can't seem to get this thing working. Could you guys help me out. I hate to ask for some code, but it would really be helpful in this situation.

Hi servercrash,

I believe your problem is related to all components getting added to the center. Buy default if you are using gridbaglayout as a layout manager to a container, the components in the container will get added to the center. You will have to specify the constraints while adding. I have attached an example hope this helps.

all the best
srinivas

Attachments
/**
*Developed under jdk1.5
*/
import javax.swing.*;
import java.awt.*;
class TestGridBagLayout extends JFrame
{
	TestGridBagLayout()
	{
		/**
		*	this line would have been
		*	getContentPane().setLayout(new GridBagLayout());	
		*	if it were any version prior to jdk1.5
		*/
		setLayout(new GridBagLayout());
		

		JButton jb1=new JButton("one");
		JButton jb2=new JButton("two");
		JButton jb3=new JButton("three");
		JButton jb4=new JButton("four");
		JButton jb5=new JButton("five");
		JButton jb6=new JButton("six");

		GridBagConstraints gbc=new GridBagConstraints();

		gbc.gridx=0;
		gbc.gridy=0;
		/**
		*	this line would have been
		*	getContentPane().add(jb1,gbc);	
		*	if it were any version prior to jdk1.5
		*/
		add(jb1,gbc);

		gbc.gridx=1;
		gbc.gridy=0;
		/**
		* unless u specify horizontal, the component will occupy 2 grids but will not fill the space
		* as in jb6
		*/
		gbc.fill=GridBagConstraints.HORIZONTAL;
		gbc.gridwidth=2;
		add(jb2,gbc);

		/**
		*GridBagLayout honors preferred size since three is the biggest component
		* in this grid(x=0) the width of the grid is that of jb3
		*/
		gbc.fill=GridBagConstraints.NONE;		
		gbc.gridwidth=1;
		gbc.gridx=0;
		gbc.gridy=1;
		add(jb3,gbc);
		
		gbc.gridx=1;
		gbc.gridy=1;
		add(jb4,gbc);

		gbc.gridx=2;
		gbc.gridy=1;
		gbc.fill=GridBagConstraints.VERTICAL;
		gbc.gridheight=2;
		add(jb5,gbc);

		gbc.fill=GridBagConstraints.NONE;		
		gbc.gridheight=1;
		gbc.gridx=0;
		gbc.gridy=2;
		gbc.gridwidth=2;
		add(jb6,gbc);

		setSize(300,300);
		show();
	}
	public static void main(String args[])
	{
		new TestGridBagLayout();
	}
}

Thanks man, but I'm still have tons of problems with this. I'll attach the code that I have, please see if you can at least help me get this thing started. By the way, this is NOT homework. I'm just trying to learn the gridbag layout while making a calculator but can't get this thing going.

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

public class CalculatorApplet extends JApplet implements ActionListener
{
	JMenu fileMenu;
	JMenuItem exitItem;
	
	JMenu editMenu;
	JMenuItem undoItem;
	JMenuItem redoItem;
	JMenuItem addMemItem;
	JMenuItem pasteMemItem;
	JMenuItem clearItem;
	
	JMenu formatMenu;
	JRadioButtonMenuItem firstFormatItem;
	JRadioButtonMenuItem secondFormatItem;
	JRadioButtonMenuItem thirdFormatItem;
	JRadioButtonMenuItem fourthFormatItem;
	
	
	JButton[] btnSciPad;
	JButton[] btnNums;
	JButton[] btnOperators;
	JButton[] btnMemPad;
	JButton btnCalculate;
	JButton btnClear;
	
	String[] sciPadNames = {"Cos","Sin","Tan","cos-1","sin-1","tan-1","x^y","1/x","x^1/y","log10x","10^x","ln","sqrt"};
	String[] numPadNames = {"1","2","3","4","5","6","7","8","9","0"};
	String[] operatorsNames = {"+","-","/","*",".","+/-"};
	String[] memPadNames = {"M+","M-","Back"};
	
	JTextField display;
	
	public void init()
	{
		Container content = getContentPane();
		GridBagLayout gbl = new GridBagLayout();

		
		display = new JTextField(20);
		content.add(display);
		JMenuBar menuBar = new JMenuBar();
		fileMenu = new JMenu("File");
		exitItem = new JMenuItem("Exit");
		fileMenu.add(exitItem);
		
		editMenu = new JMenu("Edit");
		undoItem = new JMenuItem("Undo");
		redoItem = new JMenuItem("Redo");
		addMemItem = new JMenuItem("addM");
		pasteMemItem = new JMenuItem("pasteM");
		clearItem = new JMenuItem("Clear");
		editMenu.add(undoItem);
		editMenu.add(redoItem);
		editMenu.add(addMemItem);
		editMenu.add(pasteMemItem);
		editMenu.add(clearItem);
		
		formatMenu = new JMenu("Format");
		firstFormatItem = new JRadioButtonMenuItem("####");
		secondFormatItem = new JRadioButtonMenuItem("####.#");
		thirdFormatItem = new JRadioButtonMenuItem("####.##");
		fourthFormatItem = new JRadioButtonMenuItem("####.####");
		content.setLayout(gbl);
		gbl.layoutContainer(content);
		GridBagConstraints c = new GridBagConstraints();
		c.fill = GridBagConstraints.HORIZONTAL;
		c.gridwidth = 4;
		c.gridheight = 12;
		btnSciPad = new JButton[sciPadNames.length];
		for (int i=0; i<btnSciPad.length; i++)
		{
			btnSciPad[i] = new JButton(sciPadNames[i]);
			//content.add(btnSciPad[i]);
		}
		btnNums = new JButton[numPadNames.length];
		for (int i=0; i<btnNums.length; i++)
		{
			btnNums[i] = new JButton(numPadNames[i]);
			//content.add(btnNums[i]);
		}
		btnOperators = new JButton[operatorsNames.length];
		for (int i=0; i<btnOperators.length; i++)
		{
			btnOperators[i] = new JButton(operatorsNames[i]);
			//content.add(btnOperators[i]);
		}
		btnMemPad = new JButton[memPadNames.length];
		for (int i=0; i<memPadNames.length; i++)
		{
			btnMemPad[i] = new JButton(memPadNames[i]);
			//content.add(btnMemPad[i]);
		}
		    double[][] weights = gbl.getLayoutWeights();
		    for (int i=0; i<2; i++) {
			for (int j=0; j<weights[i].length; j++) {
			    weights[i][j] = 1;
			}
		    }
		gbl.columnWeights = weights[0];
		gbl.rowWeights = weights[1];
		btnCalculate = new JButton("Calculate");
		c.gridx = 0;
		c.gridy = 0;
		c.insets = new Insets(2,2,2,2);
		gbl.setConstraints(btnCalculate,c);
		content.add(btnCalculate,c);
		c.gridx = 1;
		btnClear = new JButton("Clear");
		content.add(btnClear,c);
		
		setContentPane(content);
		setVisible(true);
	}
	
	public void actionPerformed(ActionEvent ae)
	{
	}
}

hey i am attempting the same thing, after being introduced to java at my IBM work experiance i'm now really intrested in making GUI's etc. So far i have built the interface, there is no system code assigned to the buttons yet. I would just like to know if there is any way of creating arrays with the buttons. Because then i would be able to assign an index to each button. This would then mean that i would only need one action listener. I think.

Sorry if none of the above makes sense, i have only been doing this for 2 weeks.

Does anyone know of any good step by step books, or online help. This is the only place i have found that gives help on little snippets of code, such as alligning text in a JTEXTFIELD

Ok, I finally figured it out. It's not as hard as it looks. Thrilla, I'll help you out, but I'm really busy at the moment so just give me a little while and I'll see what I can do.

this is what i have managed so far.

For someone who has only been doing all this for 2 weeks i hope it aint too bad

Attachments
import java.awt.Container;
import java.awt.Container;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class Calculator extends JFrame 

{
	public Calculator()
	
	{
		super("Calculator");
		
		Container pane = getContentPane();
		pane.setLayout(new GridBagLayout());
		GridBagConstraints c = new GridBagConstraints();
		c.fill = GridBagConstraints.HORIZONTAL;
		
		
		//Define buttons and captions
		JButton button0 = new JButton("0");
		JButton button1 = new JButton("1");
		JButton button2 = new JButton("2");
		JButton button3 = new JButton("3");
		JButton button4 = new JButton("4");
		JButton button5 = new JButton("5");
		JButton button6 = new JButton("6");
		JButton button7 = new JButton("7");
		JButton button8 = new JButton("8");
		JButton button9 = new JButton("9");
		JButton buttonPlus = new JButton("+");
		JButton buttonMinus = new JButton("-");
		JButton buttonMultiply = new JButton("x");
		JButton buttonDivide = new JButton("/");
		JButton buttonEquals = new JButton("=");
		JButton buttonCancel = new JButton("C");
		
		//Define display
		JTextField display = new JTextField(10);
		display.setFont(new Font("Ariel",Font.BOLD,18));			
		//display.setEnabled(false);
		display.setHorizontalAlignment(JTextField.RIGHT);
		
		
		//Arrange display and buttons
		c.gridx = 0;
		c.gridy = 0;
		c.weightx = 0.4;
		c.weighty = 0.2;
		c.gridwidth =4;
		c.gridheight = 1;
		c.ipadx= 0;
		c.ipady=10;
		c.insets = new Insets(5,5,5,5);
		pane.add(display,c);
		
		c.gridx = 0;
		c.gridy = 3;
		c.weightx = 0.25;
		c.weighty = 0;
		c.gridwidth =1;
		c.gridheight = 1;
		c.ipadx= 0;
		c.ipady=0;
		pane.add(button1,c);
		
		c.gridx = 1;
		c.gridy = 3;
		c.weightx = 0.25;
		c.weighty = 0;
		c.gridwidth =1;
		c.gridheight = 1;
		c.ipadx= 0;
		c.ipady=0;
		pane.add(button2,c);
		
		c.gridx = 2;
		c.gridy = 3;
		c.weightx = 0.25;
		c.weighty = 0;
		c.gridwidth =1;
		c.gridheight = 1;
		c.ipadx= 0;
		c.ipady=0;
		pane.add(button3,c);
		
		c.gridx = 3;
		c.gridy = 3;
		c.weightx = 0.25;
		c.weighty = 0;
		c.gridwidth =1;
		c.gridheight = 1;
		c.ipadx= 0;
		c.ipady=0;
		pane.add(buttonMultiply,c);
		
		c.gridx = 0;
		c.gridy = 2;
		c.weightx = 0.25;
		c.weighty = 0;
		c.gridwidth =1;
		c.gridheight = 1;
		c.ipadx= 0;
		c.ipady=0;
		pane.add(button4,c);
		
		c.gridx = 1;
		c.gridy = 2;
		c.weightx = 0.25;
		c.weighty = 0;
		c.gridwidth =1;
		c.gridheight = 1;
		c.ipadx= 0;
		c.ipady=0;
		pane.add(button5,c);
		
		c.gridx = 2;
		c.gridy = 2;
		c.weightx = 0.25;
		c.weighty = 0;
		c.gridwidth =1;
		c.gridheight = 1;
		c.ipadx= 0;
		c.ipady=0;
		pane.add(button6,c);
		
		c.gridx = 3;
		c.gridy = 2;
		c.weightx = 0.25;
		c.weighty = 0;
		c.gridwidth =1;
		c.gridheight = 1;
		c.ipadx= 0;
		c.ipady=0;
		pane.add(buttonMinus,c);
		
		c.gridx = 0;
		c.gridy = 1;
		c.weightx = 0.25;
		c.weighty = 0;
		c.gridwidth =1;
		c.gridheight = 1;
		c.ipadx= 0;
		c.ipady=0;
		pane.add(button7,c);
		
		c.gridx = 1;
		c.gridy = 1;
		c.weightx = 0.25;
		c.weighty = 0;
		c.gridwidth =1;
		c.gridheight = 1;
		c.ipadx= 0;
		c.ipady=0;
		pane.add(button8,c);
				
		c.gridx = 2;
		c.gridy = 1;
		c.weightx = 0.25;
		c.weighty = 0;
		c.gridwidth =1;
		c.gridheight = 1;
		c.ipadx= 0;
		c.ipady=0;
		pane.add(button9,c);
		
		c.gridx = 3;
		c.gridy = 1;
		c.weightx = 0.25;
		c.weighty = 0;
		c.gridwidth =1;
		c.gridheight = 1;
		c.ipadx= 0;
		c.ipady=0;
		pane.add(buttonPlus,c);
		
		c.gridx = 0;
		c.gridy = 4;
		c.weightx = 0.25;
		c.weighty = 0;
		c.gridwidth =1;
		c.gridheight = 1;
		c.ipadx= 0;
		c.ipady=0;
		pane.add(button0,c);
		
		c.gridx = 1;
		c.gridy = 4;
		c.weightx = 0.25;
		c.weighty = 0;
		c.gridwidth =1;
		c.gridheight = 1;
		c.ipadx= 0;
		c.ipady=0;
		pane.add(buttonCancel,c);
		
		c.gridx = 2;
		c.gridy = 4;
		c.weightx = 0.25;
		c.weighty = 0;
		c.gridwidth =1;
		c.gridheight = 1;
		c.ipadx= 0;
		c.ipady=0;
		pane.add(buttonEquals,c);
		
		c.gridx = 3;
		c.gridy = 4;
		c.weightx = 0.25;
		c.weighty = 0;
		c.gridwidth =1;
		c.gridheight = 1;
		c.ipadx= 0;
		c.ipady=0;
		pane.add(buttonDivide,c);
		
		
		pack();
		setSize(250,225);
		setResizable(false);
		setVisible(true);
		
	}
	
	public static void main(String[] args) 
	
	{
		Calculator app = new Calculator();
	}

}

That is EXCELLENT for a beginner. The example you gave really helped me out because I just could not figure it out. So, thank you very much.
I personally would much rather use the setBounds() method which gives you more freedom(in my opinion) and is much easier to use.

As for your question:

Yes you can use button arrays(if that's what you were asking). I guess you looked at my code. At first I was trying to use arrays but I don't think that's the best way to go using the gridbaglayout.

Good resources:

java.sun.com has the best tutorials.
javaalmanac.com has some really good stuff.

I think searching google is the most helpful. I personally don't like going to one site and looking around for a tutorial. Just search google for what you want to know, and I gurantee you, you will find great resources that way. One more thing, posting in forums are very helpful. If you ever have any questions or need anything, just post and I will see what I can do. If you will be more specific as to what you need, I can look for some resources for you.

:-) thankyou

actually i havent looked at your code yet, not quite sure what part of mine helped you, i tryed doing the interface using actual coordinates and sizes etc, but i found that took too long. If you need any more help on gridbaglayout then let me know, i aint an expert but it worked first time for me.

Just need to figure out more basic commands, its real annoying at the moment not knowing enough to progress, i find it takes me 20 mins or so to find the command i need, such as text aligning in the JTextField, or how to increase its font size with in the field.

Gonna do some more work on it tommorrow, let me know how you get on.

:)

I finished the calculator with added scientific buttons, but it doesn't have operator presidence. This is one thing I'm working on right now. I'll send you the calc via PM if I ever finish it to let you see what I got.

Hi everyone,
While using GridBagLayout, how can we add components to the layout. i mean, if i have a choice menu and the user selects one of the options from it, then another choice menu should be added to its side.
i wrote some code for it but instead of appearing at the required place, the new choice menu was appearing on the top left corner inspite of setting the proper constraints. a code snippet of the action() method for handling the user inputs is:

public boolean action(Event e,Object arg)
{
if(e.target instanceof Choice)
{
if(((String)arg).equals("South"))
{
GridBagLayout gridbag=(GridBagLayout)getLayout();
GridBagConstraints gbc=new GridBagConstraints();
Choice c=new Choice();
buildConstraints(gbc,2,23,1,2,100,0); //sets constraints in gbc
c.addItem("South-East");
c.addItem("South-West");
gridbag.setConstraints(c,gbc);
add(c);


}
}
return true;
}

when the 'South' option is selected a new Choice menu shud appear with 'South-East' and 'South-West'the constraints set are correct according to the desired output. but the new menu still appears at top-left corner. i dont understand why.
btw, this is an applet and i've used awt components not swing ones.
any help in this matter will be appreciated.
thanx

Edited 3 Years Ago by happygeek: fixed formatting

I didnt even know java existed 2 weeks ago so please bare with me, take a look at how i have coded the positions for the buttons for a calculator. There is repeated code for each button position, this may seem silly but i have done this so that it is easy to see what the properties for each button is.

I have no idea if this helps, let me know if it does, i am very new to this, but i am learning quickly.

Serial, I loved the way you used the properties for the gridbaglayout on each button. That's what helped me out. I've known Java for a year and am very good at it, but I've never used the gridbaglayout and to tell you the truth, the code you showed me really helped out.

This article has been dead for over six months. Start a new discussion instead.