[Java] How to use GUI

Junior Spellweaver
Joined
Mar 22, 2008
Messages
139
Reaction score
5
I've noticed alot of people don't know much about Java GUI. There are programs that build GUI code for you, but who needs them.


I will be using JCreator to create my GUI.

To Start off:
- Create a new blank workspace called GUIGoodness.
- Create a new EMPTY project, and Name it GUIGoodness.
- Add a new Java Class File to that project and name it GUI.


1. Setting your code up:
You should just have something similar to this in your file -
Code:
/**
 * @(#)GUI.java
 *
 *
 * @author 
 * @version 1.00 2009/4/15
 */


public class GUI {

    public GUI() {
    }
    
    
}

You need to add these imports to the top -
Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


Now we need to change the line -
Code:
public class GUI {
to
Code:
public class GUI extends JFrame implements ActionListener {
This allows us to use JFrame and ActionListener.

2. Adding JFrame and a Container:
Add these variables into your class -
Code:
private JFrame displayWindow;
private Container cp;


Now we need to make the Container, which will basically create a window with no buttons inside it.

Add this inside public GUI{ -
Code:
cp = getContentPane();
cp.setLayout(null);
cp.setBackground(Color.white);


Now we need to set some attributes for the window.

Add this under what you just added -
Code:
setTitle("GUIGoodness");
setLocation(150,250);
setSize(200,200);
setResizable(false);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);

You can change up the Size if you want.

3. Main Method:
Add this after the closing brace of public GUI -
Code:
public static void main(String args[]) 
            {
                GUI frame = new GUI();
                frame.setVisible(true);
            }


And this -
Code:
public void actionPerformed(ActionEvent e) 
        {
        //JButton actions
            if(e.getSource() instanceof JButton)
            {
                JButton clicked = (JButton)e.getSource();
                
            }
    
        }
This will be used later when we give a button an action.

Your program should look like this -
Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


public class GUI extends JFrame implements ActionListener {
    
    private JFrame displayWindow;
    private Container cp;

    public GUI() {
        
        cp = getContentPane();
        cp.setLayout(null);
        cp.setBackground(Color.white);
        
        //main gui
        setTitle("GUIGoodness");
        setLocation(150,250);
        setSize(200,200);
        setResizable(false);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }
    
        public static void main(String args[]) 
            {
                GUI frame = new GUI();
                frame.setVisible(true);
            }
            
        public void actionPerformed(ActionEvent e) 
        {
        //JButton actions
            if(e.getSource() instanceof JButton)
            {
                JButton clicked = (JButton)e.getSource();
                
            }
    
        }
    
    
}


4. Creating an Object(JButton, JLabel):
To create a Button, TextField or Label, you first need to declare a variable, like this -
Code:
private JButton btn;


Now you need to create the button, like this -
Code:
btn = new JButton("Click Me!"); //creates the object
btn.setBounds(0,0,120,50); //sets the size and position (225,290 is the position, and 120,50 is the size)
btn.addActionListener(this);
cp.add(btn); //this shows the button on the actual window.

Place that code in public GUI.

Now Run your project. It should look like this if you did not change anything.
Vintage - [Java] How to use GUI - RaGEZONE Forums


Now lets add a JLabel, Do the same you did for the button, but instead of JButton, use JLabel.
Here's my variable -
Code:
private JLabel lbl;
Now this is how you create a JLabel, it's slightly different than a JButton.
Code:
lbl = new JLabel("CLICK THE BUTTON!!");
        lbl.setBounds(0,60,120,20);
        cp.add(lbl);
After you add that, your program should look like this.
Vintage - [Java] How to use GUI - RaGEZONE Forums


We're done with making objects now. Let's go into giving the Button an action.

5. Giving an Action:
Giving an action is actually quite easy, It just requires one if statement.

Vintage - [Java] How to use GUI - RaGEZONE Forums

In this method, you need to add an if statement under -
Code:
JButton clicked = (JButton)e.getSource();


This is how you would do that...
Code:
if(clicked == btn) //btn is the name of my button, NOT the text inside it.
                {
                    lbl.setText("YAY YOU CLICKED IT"); //changes the text in our label.
                }

This checks if the JButton btn was clicked, if so, it changes the text in our JLabel lbl to "YAY YOU CLICKED IT".


In the end your entire program should look like this -
Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


public class GUI extends JFrame implements ActionListener {
    
    private JFrame displayWindow;
    private Container cp;
    
    private JButton btn;
    private JLabel lbl;

    public GUI() {
        
        cp = getContentPane();
        cp.setLayout(null);
        cp.setBackground(Color.white);
        
        //main gui
        setTitle("GUIGoodness");
        setLocation(150,250);
        setSize(200,200);
        setResizable(false);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        
        btn = new JButton("Click Me!"); //creates the object
        btn.setBounds(0,0,120,50); //sets the size and position (225,290 is the position, and 120,50 is the size)
        btn.addActionListener(this);
        cp.add(btn); //this shows the button on the actual window.
        
        lbl = new JLabel("CLICK THE BUTTON!!");
        lbl.setBounds(0,60,120,20);
        cp.add(lbl);

    }
    
        public static void main(String args[]) 
            {
                GUI frame = new GUI();
                frame.setVisible(true);
            }
            
        public void actionPerformed(ActionEvent e) 
        {
        //JButton actions
            if(e.getSource() instanceof JButton)
            {
                JButton clicked = (JButton)e.getSource();
                
                if(clicked == btn)
                {
                    lbl.setText("YAY YOU CLICKED IT");
                }
                
            }
    
        }
    
    
}
Well, thats the basics on how to make a GUI and give it funcionality.

If you experience any problems compiling, just post the error you get and I'll tell you what you did wrong, and how to fix it.
 
Yeah I get a ClassCastException on:
Code:
JButton clicked = (JButton)e.getSource();

What's wrong?

Actually I'm just kidding you do an instanceof check for it anyhow so that error wouldn't happen on that line. Very well done on this tutorial, even though I'd rather use anonymous classing for making the frame, but this works out quite well. Good job. JCreator, huh? Are you taking a Computer Science course at a high school or something? That's usually where it's used. I use the Professional version myself, It is simple and lightweight, and that's all I need.

Anyways, nice tutorial, thank you for taking the time to put it together.
 
then to make it one step easier you can download IDE's such as netbeans that actually have a template where you can drag and drop items into the container itself... such as netbeans

here is an actual tutorial approved by sun itself for netbeans

and i didn't read the entire tutorial but Java's gui is called swing and is far more extensive then you can learn in a couple of years of computer science classes

http://java.sun.com/docs/books/tutorial/uiswing/

very nice guide =)
 
Back