Welcome to Dream.In.Code
Getting Java Help is Easy!

Join 132,412 Java Programmers for FREE! Get instant access to thousands of Java experts, tutorials, code snippets, and more! There are 1,362 people online right now. Registration is fast and FREE... Join Now!




Basic GUI Concepts

 
Reply to this topicStart new topic

> Basic GUI Concepts, An intro to the wide world of graphical interfaces.

SPlutard
Group Icon



post 9 Aug, 2006 - 01:45 AM
Post #1


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:
IPB Image IPB Image

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

Now for the fun part: the code. smile.gif 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.gif 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:
CODE
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:
CODE
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. tongue.gif) 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:
CODE
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:
CODE
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: 9 Aug, 2006 - 02:14 PM
Go to the top of the page
+Quote Post


Register to Make This Ad Go Away!

kcor
Group Icon



post 13 Nov, 2006 - 09:23 AM
Post #2
Excellent in-depth tutorial on the fundamentals of GUI design. Well done!
Go to the top of the page
+Quote Post

alpha02
Group Icon



post 8 Jan, 2007 - 01:49 PM
Post #3
Very good tutorial! I had some trouble understanding this concept before, and now I find it easy. Thanks for this tutorial!
Go to the top of the page
+Quote Post

fresher
*



post 6 Mar, 2007 - 10:46 AM
Post #4
Thanks for the step-by-step explanation. much obliged!
Go to the top of the page
+Quote Post

zidane1845
*



post 18 Sep, 2007 - 05:49 PM
Post #5
yeah thanks for this, was very clear and helpful
Go to the top of the page
+Quote Post

nick2price
**



post 15 Jun, 2008 - 11:08 AM
Post #6
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.
Go to the top of the page
+Quote Post

StaceyE
*



post 5 Aug, 2008 - 09:33 AM
Post #7
Thank you. This tutorial has helped me understand several things more clearly. icon_up.gif
Go to the top of the page
+Quote Post

IMU
*



post 12 Aug, 2008 - 09:34 PM
Post #8
A nice tutorial which help me a lot
Go to the top of the page
+Quote Post

grace ng
*



post 19 Oct, 2008 - 07:35 PM
Post #9
How to write remove and clear button event.....Can give tips or tutorial
Go to the top of the page
+Quote Post


Reply to this topicStart new topic
2 User(s) are reading this topic (1 Guests and 1 Anonymous Users)
0 Members:

 

Lo-Fi Version Time is now: 11/22/08 08:44AM

Live Java Help!

Java Tutorials

Reference Sheets

Java Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month