Swing GUI, part 1

Creating a Java GUI is really simple, some people might think its hard, but learning about the basics of how you should create a GUI, you will come very far and you will be able to create nice, functional and nifty Graphical User Interfaces.

Here is a GUI with a textpane and a button. This application does not do anything, but will teach you the ease of creating a small GUI.

Here is a example of your first java GUI.

// Includes layouts
import java.awt.*;
// Includes Swing components.
import javax.swing.*;

/**
 * We are here extending the JFrame, this is just the frame that 
 * we want to på J* components inside.
 *
 */
public class Tut1 extends JFrame{
	static public void main(String[] args){
		Tut1 t = new Tut1("My first GUI");
	}
	
	public Tut1(String title){
		// sets the title of the application.
		setTitle(title);
		
		
		// There are many layouts, today we will look at borderlayout
		// Notice, default layout is FlowLayout.
		setLayout(new BorderLayout());
		
		
		
		// Add a textfield in Center ( Stretches when scaling screen )
		add(new JTextPane(), BorderLayout.CENTER);
		// Add a button in south
		add(new JButton("A Button"), BorderLayout.SOUTH);
		
		// packs the screen to fit components, this means that we cant set size manually
		// pack() is a smart method that scales everything for us, including components and the frame.
		pack();
		setVisible(true);
	}
}

Layout

You can set layout on container components such as JFrame. There are many layouts that exists, some being FlowLayout, GridLayout and the one we used in this tutorial: BorderLayout.

BorderLayout basically have 5 places to put components in the container. That is: NORTH, WEST, SOUTH, EAST and CENTER.

FlowLayout adds components from left to right, if size of screen is not wide enough, it will float below the other components.

GridLayout is nice for showing forms with equal grid size on both sides. Forexample Name [inputfield] Email [inputField]. If you want consistant spacing between components GridLayout is your choise of layout.

JPanel container

Some times you would want to group specific components, such as input fields and labels and putting this into their own layout.

JPanel is a container that you can also set the layout on with setLayout().

Here is a example of putting some lables with input fields into its own panel, and using GridLayout.

// We provide amount of rows and columns, you can set one to 0 if you dont know how many of it you have.
JPanel p = new JPanel(new GridLayout(0, 2));
p.add(new JLabel("Name:"));
p.add(new JTextField());
p.add(new JLabel("Email:"));
p.add(new JTextField());
p.add(new JLabel("Phonenumber:"));
p.add(new JTextField());

// Now we can add the panel to the frame or to another panel.

Comment by Anonymous on 25th October 2011, 11:24 PM Comment this post

Cool thanks!

Please write the code you see on this image:

Human verification