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

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

#16 Laythe  Icon User is offline

  • D.I.C Head

Reputation: 5
  • View blog
  • Posts: 76
  • Joined: 09-June 09

Posted 31 August 2009 - 12:58 PM

Hello.
I have a question and i hope someone will answer me Please :)
when i create the CalculaterButtonHandler class and the ExitButtonHandler class separately the code dont compile and i get runtime exception.
Is there something i can do to make it work that way?

This post has been edited by Laythe: 31 August 2009 - 01:02 PM

Was This Post Helpful? 0
  • +
  • -

#17 wittymind  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 29-May 09

Posted 08 September 2009 - 10:30 AM

forgot to use setEditable() for areaTF
Can do it right after creating area Text Field
areaTF = new JTextField(10);
areaTF.setEditable(false);

Was This Post Helpful? 0
  • +
  • -

#18 judgement  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 27-October 09

Posted 27 October 2009 - 03:12 AM

I thought it was almost impossible for me to understand button events. thanks a million
Was This Post Helpful? 0
  • +
  • -

#19 cubeen  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 13-November 09

Posted 15 November 2009 - 02:45 PM

Brilliant tutorial. Thank you!
Was This Post Helpful? 0
  • +
  • -

#20 odpisani  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 27-February 09

Posted 30 December 2009 - 05:18 AM

Thanx! It's a great tutorial! :^:
Was This Post Helpful? 0
  • +
  • -

#21 Terillius  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 29-March 10

Posted 02 April 2010 - 09:39 PM

Nice! Isn't it true that you don't have to getContentPane() anymore? You can just add things to the frame.
Was This Post Helpful? 0
  • +
  • -

#22 this.user  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 04-July 10

Posted 22 July 2010 - 11:12 AM

Very well put.
thanks
Was This Post Helpful? 0
  • +
  • -

#23 frick  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 26-July 10

Posted 26 July 2010 - 08:47 PM

Wow, that is good tutorial. Nice work. But i have some ask, what is difference between Container and Pane?

Anybody can help me...
Was This Post Helpful? 0
  • +
  • -

#24 macosxnerd101  Icon User is offline

  • Self-Trained Economist
  • member icon




Reputation: 10596
  • View blog
  • Posts: 39,257
  • Joined: 27-December 08

Posted 27 July 2010 - 02:04 PM

Container is the superclass for all containers like Applets, JFrames, JPanels, etc. JPanels are specific types of lightweight Containers, designed to be contained in a top-level Container (like a JFrame or JApplet) or other nested Containers (ie., other JPanels).
Was This Post Helpful? 0
  • +
  • -

#25 tecklee89  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 13-September 09

Posted 27 July 2010 - 11:29 PM

is exception handler required for the input text field? I think it is also rather important so that it won't get error from that. awesome tutorial anyway!!
Was This Post Helpful? 0
  • +
  • -

#26 ChrisDeCamp  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 22
  • Joined: 13-November 10

Posted 15 December 2010 - 02:10 AM

Excellent Tutorial! This really helped me a lot!!

Thank you,

Chris DeCamp





View PostSPlutard, on 09 August 2006 - 12:45 AM, said:

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)

Was This Post Helpful? 0
  • +
  • -

#27 VulcanDesign  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 5
  • View blog
  • Posts: 98
  • Joined: 06-December 09

Posted 15 December 2010 - 02:22 AM

Really really really helpful, thanks!
Was This Post Helpful? 0
  • +
  • -

#28 k3y  Icon User is offline

  • D.I.C Head

Reputation: 36
  • View blog
  • Posts: 205
  • Joined: 25-February 12

Posted 15 December 2012 - 07:52 PM

I am garbage with GUI and through this tutorial, you made things very simple. Thanks for the tutorial.
Was This Post Helpful? 0
  • +
  • -

#29 k3y  Icon User is offline

  • D.I.C Head

Reputation: 36
  • View blog
  • Posts: 205
  • Joined: 25-February 12

Posted 02 March 2013 - 08:48 PM

Quote

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

Great tutorial, also that is the book I had to buy for my first semester. I agree it is an awful book, and some of the sample code didn't work correctly. I stopped reading it about a week in, and, used Oracle and D.I.C tutorials (still do =D) and it makes Java much more enjoyable to learn.

This post has been edited by k3y: 02 March 2013 - 08:48 PM

Was This Post Helpful? 0
  • +
  • -

#30 Orion_N  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 27-August 13

Posted 04 September 2013 - 02:14 PM

Thanks for the tutorial, just what I was looking for. I want to implement a GUI in one of my projects and now things seem much more clear!
Was This Post Helpful? 0
  • +
  • -

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