• (3 Pages)
  • +
  • 1
  • 2
  • 3

Basic GUI Concepts An intro to the wide world of graphical interfaces. Rate Topic: ***** 4 Votes

#1 SPlutard  Icon User is offline

  • code.ninja
  • member icon

Reputation: 17
  • View blog
  • Posts: 615
  • Joined: 13-August 05

Post icon  Posted 09 August 2006 - 02:45 AM

*
POPULAR

First thing's first: this tutorial won't teach you everything you need to know about GUI's - there are entire books on the subject. I'm just going to guide you through the basics, just enough to get you on your feet so you can explore on your own. And perhaps the best resource for that, when you're ready, is the Java API which lists EVERYTHING Sun officially includes in Java and how to use it. They also have some decent tutorials of their own too.
** Also: I assume you've already covered the basics of Java programming and object-oriented design concepts (to some degree, at least). If you need to, I reccommend Jhin's Hello World tutorial, it's really quite good.

Now that that's over, let's get started with some vocab.:

The Frame
The frame is the border of the window that will "hold" all your components - your text fields, labels, radio buttons, etc.. Every window must have a frame to place components, just as every book must have a cover to hold pages.

Content Pane (or just pane)
The content pane is where all components will be placed. You could think of it as the background. Every GUI must have a content pane, just as books must have pages.

Layout Manager
The layout manager places the components in the pane in a certain configuration, depending on which layout manager you specify. If you set it to "null" as I often do, you must specify the exact coordinates (in pixels) for each component. Layout managers can be nice, but they can also cause lots of headaches.

Coordinates
Coordinates are specified rather intuitively in Java. If you remember your high school algebra - or at least how to plot points on an x-y graph - you'll be fine. Java's coordinate system uses standard (x, y) coordinates, but they're plotted like this: A point (x, y) is located x pixels to the right and y pixels down from the top-left corner of the pane.

Here's a couple of pictures for you visual types:
Posted Image Posted Image

How it Works
Here's basically what we're going to do:
  • Make a frame
  • Get a hold of the content panel
  • Make our components
  • Add our components to the GUI
  • Set up event handlers
</Boring Intro>

Now for the fun part: the code. :) For this tutorial, let's make a really simple app that computes the area of a rectangle.
Ok, we'll need to import these: javax.swing.JFrame;, java.awt.event.*; and java.awt.*; - they'll come in handy.

*Almost all of the code for this project will be put in the class' constructor. Very little code will actually go into the main method.

To make a frame, our class has to extend JFrame, which also allows us to manipulate the frame. When we create a frame, we have to specify a few things: dimensions, title, default close operation, and visibility. :blink: Visibility and default close operation?
Yup. If a window is set as visible, the user can see it on his screen. As straight-forward as it sounds, this is one of the most commonly forgotten frame attributes and makes for a very frustrated prorgammer. Default close operation is a bit outside the scope of this tutorial, so we'll just keep it simple and leave it set to EXIT_ON_CLOSE. Basically, it just defines how the window reacts when the user presses the big 'x'.

What does all this look like? Here are those methods in action:
import javax.swing.JFrame;
import java.awt.*;

public class RectangleProgram extends JFrame
{
	private static final int WIDTH = 400;
	private static final int HEIGHT = 300;
	
	public RectangleProgram()
	{
		setTitle("Sample Title: Area of a Rectangle");
		setSize(WIDTH, HEIGHT);
		setVisible(true);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
	}
	
}


Now, we've got our frame. Next: content panel.
We use a Container object to manipulate the content pane (CP) along with a nifty statement: getContentPane(). The class Container only has two methods that we need to mess with: add and setLayout. Let's save add for later, but we'll set the layout (manager) to a simple grid layout with 4 rows and 2 columns.

Here's the code for what we just did:
Container pane = getContentPane();
pane.setLayout(new GridLayout (4, 2));


Components, Components, Components
In this tutorial you will be introduced to three components: JLabel, JTextField, JButton. (Betcha' can't figure out what they do. :P) Keep in mind that there are tons of other types of components, but these are three of the most basic, and are therefore good for learning.

We declare & instantiate them just like any other object. The JLabel constructor accepts two arguments: a string of text (the prompt) and an alignment constant. JTextField: and integer specifying the size of the field in characters. JButton: an String that will be the text on the button. One thing to note: we declare the components outside the class' constructor, but we instantiate them inside the constructor - like other instance variables.

Next, we have to add the components to the CP. To do that, just use pane.add(<Component>); - where Component refers to the reference variable for the component you want to add.

Here's the program now:
import java.awt.*;
import javax.swing.*;

public class RectangleProgram extends JFrame
{
	private static final int WIDTH = 400;
	private static final int HEIGHT = 300;
	
	private JLabel lengthL, widthL, areaL, perimeterL;
	private JTextField lengthTF, widthTF, areaTF, perimeterTF;
	private JButton calculateB, exitB;
	
	public RectangleProgram()
	{
		//Instantiate the labels:
		lengthL = new JLabel("Enter the length: ", SwingConstants.RIGHT);
		widthL = new JLabel("Enter the width: ", SwingConstants.RIGHT);
		areaL = new JLabel("Area: ", SwingConstants.RIGHT);
		perimeterL = new JLabel("Perimeter: ", SwingConstants.RIGHT);
		
		//Text fields next:
		lengthTF = new JTextField(10);
		widthTF = new JTextField(10);
		areaTF = new JTextField(10);
		perimeterTF = new JTextField(10);
		
		//Buttons too:
		calculateB = new JButton("Calculate");
		exitB = new JButton("Exit");
		
		//Set the window's title.
		setTitle("Sample Title: Area of a Rectangle");
		
		//Get the content pane (CP).
		Container pane = getContentPane();
		
		//Set the layout.
		pane.setLayout(new GridLayout(5, 2));
		
		//Other JFrame stuff.
		setSize(WIDTH, HEIGHT);
		setVisible(true);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
	}
	
}


Ok. All our components are ready; steps 3 & 4 are done. What's left? Well, right now those buttons won't do a thing - we haven't told them what to do when they're pressed.

When something happens in a GUI window, it's called an event. If we want to be able to react to events (like button clicks), we have to register an action listener that waits & listens for something to happen. When it "hears" something, it executes the code we put in the abstract method actionPerformed, which is where we'll be putting our area formula and output statements. For us, each button will have a different "handler" that handles each button's function using (implementing) the ActionListener. Notice that the handler we specified is the argument used when adding the ActionListener.

Also, notice the we use the getText and setText methods to manipulate the data entered into the text fields. Also, let's use the setEditable() statement on areaTF since it's solely an output field, and we don't want to confuse our user too much.

And so, here we are. Already, the final product is nearly ready. All we have to to is add a main method to start the ball rolling, and we're done. There is only one line in main: RectangleProgram rectObj = new RectangleProgram();

So, here it is:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class RectangleProgram extends JFrame
{
	private static final int WIDTH = 400;
	private static final int HEIGHT = 300;
	
	private JLabel lengthL, widthL, areaL;
	private JTextField lengthTF, widthTF, areaTF;
	private JButton calculateB, exitB;
	
	//Button handlers:
	private CalculateButtonHandler cbHandler;
	private ExitButtonHandler ebHandler;
	
	public RectangleProgram()
	{
		lengthL = new JLabel("Enter the length: ", SwingConstants.RIGHT);
		widthL = new JLabel("Enter the width: ", SwingConstants.RIGHT);
		areaL = new JLabel("Area: ", SwingConstants.RIGHT);
		
		lengthTF = new JTextField(10);
		widthTF = new JTextField(10);
		areaTF = new JTextField(10);
		
		//SPecify handlers for each button and add (register) ActionListeners to each button.
		calculateB = new JButton("Calculate");
		cbHandler = new CalculateButtonHandler();
		calculateB.addActionListener(cbHandler);
		exitB = new JButton("Exit");
		ebHandler = new ExitButtonHandler();
		exitB.addActionListener(ebHandler);
		
		setTitle("Sample Title: Area of a Rectangle");
		Container pane = getContentPane();
		pane.setLayout(new GridLayout(4, 2));
		
		//Add things to the pane in the order you want them to appear (left to right, top to bottom)
		pane.add(lengthL);
		pane.add(lengthTF);
		pane.add(widthL);
		pane.add(widthTF);
		pane.add(areaL);
		pane.add(areaTF);
		pane.add(calculateB);
		pane.add(exitB);
		
		setSize(WIDTH, HEIGHT);
		setVisible(true);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
	}
	
	private class CalculateButtonHandler implements ActionListener
	{
		public void actionPerformed(ActionEvent e)
		{
			double width, length, area;
			
			length = Double.parseDouble(lengthTF.getText()); //We use the getText & setText methods to manipulate the data entered into those fields.
			width = Double.parseDouble(widthTF.getText());
			area = length * width;
			
			areaTF.setText("" + area);
		}
	}
	
	public class ExitButtonHandler implements ActionListener
	{
		public void actionPerformed(ActionEvent e)
		{
			System.exit(0);
		}
	}
	
	public static void main(String[] args)
	{
		RectangleProgram rectObj = new RectangleProgram();
	}
	
}


Admittedly, this isn't exactly the most exciting or flashy GUI you'll ever see. However, it accomplishes a task: to introduce broad concepts. Hopefully, from here, you will go on to expand your knowledge, building on the foundation we've established here. As far as resources go, there is no shortage of them - go look for some basic Java GUI books at the library, or free e-books online, and - as always - be sure to check </DIC> for other tutorials, code snippets, and more resources than you'll know what to do with.



Diagrams from Sun's Website
RectangleProgram adapted from Java Programming, From Programming Analysis To Design, Second Edition by DS Malik (a horrible book, by the way)

This post has been edited by SPlutard: 09 August 2006 - 03:14 PM


Is This A Good Question/Topic? 17
  • +

Replies To: Basic GUI Concepts

#2 kcor  Icon User is offline

  • New D.I.C Head
  • member icon

Reputation: 1
  • View blog
  • Posts: 7
  • Joined: 15-October 06

Posted 13 November 2006 - 10:23 AM

Excellent in-depth tutorial on the fundamentals of GUI design. Well done!
Was This Post Helpful? 0
  • +
  • -

#3 alpha02  Icon User is offline

  • Sexy DIC God
  • member icon

Reputation: 47
  • View blog
  • Posts: 803
  • Joined: 20-May 06

Posted 08 January 2007 - 02:49 PM

Very good tutorial! I had some trouble understanding this concept before, and now I find it easy. Thanks for this tutorial!
Was This Post Helpful? 0
  • +
  • -

#4 fresher  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 42
  • Joined: 22-December 06

Posted 06 March 2007 - 11:46 AM

Thanks for the step-by-step explanation. much obliged!
Was This Post Helpful? 0
  • +
  • -

#5 zidane1845  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 27-July 07

Posted 18 September 2007 - 06:49 PM

yeah thanks for this, was very clear and helpful
Was This Post Helpful? 0
  • +
  • -

#6 nick2price  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 562
  • View blog
  • Posts: 2,826
  • Joined: 23-November 07

Posted 15 June 2008 - 12:08 PM

I know you have used a grid layout here, but not a good idea to mention a null layout. I hear this is bad programming.
Was This Post Helpful? 0
  • +
  • -

#7 StaceyE  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 28
  • Joined: 30-July 08

Posted 05 August 2008 - 10:33 AM

Thank you. This tutorial has helped me understand several things more clearly. :^:
Was This Post Helpful? 0
  • +
  • -

#8 IMU  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 38
  • Joined: 07-August 08

Posted 12 August 2008 - 10:34 PM

A nice tutorial which help me a lot
Was This Post Helpful? 0
  • +
  • -

#9 grace ng  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 19-October 08

Posted 19 October 2008 - 08:35 PM

How to write remove and clear button event.....Can give tips or tutorial
Was This Post Helpful? 0
  • +
  • -

#10 tanah.melayu  Icon User is offline

  • New D.I.C Head
  • member icon

Reputation: 5
  • View blog
  • Posts: 45
  • Joined: 21-February 09

Posted 23 February 2009 - 09:28 AM

DS Malik? :blink:

that's why i feel like i ever did this before... :P anywhere, i wrote a good tutorial. even i can refresh my knowledge on GUI's basic. thanks and thumbs up! :^: keep on posting basic tutorials like this coz there are a lot of things which maybe i miss to learn. TQ!
Was This Post Helpful? 0
  • +
  • -

#11 jashsayani  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 02-April 09

Posted 02 April 2009 - 05:14 AM

Great tutorial !!
Was This Post Helpful? 0
  • +
  • -

#12 Walaa Ibrahim  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 03-April 09

Posted 03 April 2009 - 08:47 AM

View PostStaceyE, on 5 Aug, 2008 - 09:33 AM, said:

Thank you. This tutorial has helped me understand several things more clearly. :^:

Thanx alot
Was This Post Helpful? 0
  • +
  • -

#13 Guest_Kanybek*


Reputation:

Posted 05 April 2009 - 02:36 PM

Thanks 4 this. Good job.
Was This Post Helpful? 0

#14 russki02  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 04-April 09

Posted 08 April 2009 - 10:26 AM

Another day another lesson learned. Ain't life grand. Thank you for the contribution.
Was This Post Helpful? 0
  • +
  • -

#15 kbgriggs  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 23-July 09

Posted 11 August 2009 - 05:47 PM

Thank you for the tutorial. Can you point me to info on next and previous buttons. I am working on a project for school and to be quite honest I am really struggling with it. I have all of my code built but am stuck with these new buttons. I have looked at a lot of code on the net but every time I try to incorporate it with my code, I do something wrong and nothing compiles.
Was This Post Helpful? 0
  • +
  • -

  • (3 Pages)
  • +
  • 1
  • 2
  • 3