Programming Forums
User Name Password Register
 

RSS Feed
FORUM INDEX | TODAY'S POSTS | UNANSWERED THREADS | ADVANCED SEARCH

Reply
 
Thread Tools Display Modes
Old Feb 21st, 2009, 3:22 AM   #1
Raikiriu
Ex-CS & Math student.
 
Raikiriu's Avatar
 
Join Date: Feb 2009
Location: Canada(Quebec)
Posts: 192
Rep Power: 9 Raikiriu is on a distinguished road
Java Programming Tutorial : Part I to GUI Programming

Okay, so this is my first ever TUT so be patient with me
We Will be covering the basic GUI programming in java. As you all are aware GUI stands for [i]general user interface[i] usually pronounced gooey. A GUI program is basically a window, like the windows calculator or notepad. It has many components like menu bars, labels, text box's and buttons etc...
So since there is so much to write about im going to break it into 4 parts,
Part I : Creating Windows and adding stuff to them
Part II : a bit about layout managers.
Part III : Borders to make it look pretty
Part IV : Using Consol output to Debug GUI apps.

************Part I******************
First off, we will be focusing on two classes that are the back bone of GUI programming, The AWT(Abstract Windowing Toolkit) package and Swing Package

So first things first, to make a Java Windowed Program, you need the packages.
The header of the program should start like this...
import java.awt.*; // note I use * cause im a lazy kid who doesn't want to write out ever element
import javax.swing.*;

Although awt comes in a bit later, it's good practice not to forget it and even if your
not going to use it, keep it there in case.

Next we're going to creat our first window.
import javax.swing.*;
import java.awt.*;

public class SimpleWindow
{
	public static void main(String []args)
	{
		final int WINDOW_HEIGHT = 250; //Variable to reference the height of the window
		final int WINDOW_WIDTH = 350;
		
		//Creating the window
		JFrame window = new JFrame(); // This creates the frame that holds components
		
		//Set the title
		window.setTitle("My First Window");

		//Set the size of the window
		window.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);

		//Specify what happens when the close button is click(lil X on top)
		window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		//Display The windo
		window.setVisible(true);
	}
}

A quick look through that code, WINDOW_HEIGHT and WIDTH are the height and width in pixels.

JFrame window = new JFrame() . here we are creating an instance of the JFrame class by dafault it is set to VISIBLE = FALES

the rest are methods of JFrame().
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) I'm going into a bit of detail here,
if you want to only hide the window and not exit the program, instead of EXIT_ON_CLOSE it would be HIDE_ON_CLOSE

Right, next little thing is using inheritance to extend the JFrame Class.
For those who do not know what inheritance is, it's basically a class inherites methods from another class.
say class a has methods getInt and toString and class b has toInt and toChar and class a extends class b class b
can use getInt and toString without creating an instance of class a. But inheritance is for later right now lets focus
on the windows
This would be the code of the Inherited class
import javax.swing.*;
import java.awt.*;

public class SimpleWindow extends JFrame
{
	/**
	Constructor
	*/
	public SimpleWindow()
	{
		final int WINDOW_HEIGHT = 250;
		final int WINDO_WIDTH = 350;
		
		//Set the title
		setTitle("A Simple Window");
		
		//set the size of the window
		setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
		
		//Set the close button thingy
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		setVisible(true);
	}
}
Hmm, how nice no need to create an instance of JFrame(). Alot simpler.
And now the fun part. Adding components to our window. Oh also, if you want to see your window before moving on,
I almost forgot, create another .java File called SimpleWindowDemo.java and inside it
public class SimpleWindowDemo
{
	public static void main(String[]args)
	{
		SimpleWindow myWindow = new SimpleWindow();
	}
}
So, inheritance does have a down side ^^.
Anyway, back to adding components.
Lets make a demo program that converts Kilometers to Miles. The algorithme is
Mile = Kilometer x 0.6214
So,
import java.swing.*;
import java.awt.*;

public class KiloConverterWindow extends JFrame
{
	/** 
	Now the fun part, i'm going to descrive each element
	*/
	private JPanel panel; //The panel contains the elements you add to the window
	private JLabel messageLabel; // the Label contains text that is un-editable.
	private JTextField kiloTextField; //The text Field is usually used as a user Input area
	private JButton calcButton; // I think the name says all its a button...
	private final int WINDOW_WIDTH = 310;
	private final int WINDOW_HEIGHT = 100;
	
	/**
	Constructor
	*/
	
	public KiloConverterWindow()
	{
		//Set title
		setTitle("Kilometer Converter");
		
		//set the size
		setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
		
		//Specify the close thingy...
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		/**
		Now we add components to the panel(sort of)
		*/ 
		
		//Build the panel and add it to the frame
		buildPanel();
		
		add(panel); // adds the panel to the frame
		
		//setVisible
		setVisible(true);
		
	}
	
	/**
	Next is the build panel method to which we add a label, text field and a button
	*/
	
	private void buildPanel()
	{
		//Create a label to display instructions
		messageLabel = new JLabel("Enter a distance in kilometers");
		
		//creat a textField 10 characters wide.
		kiloTextField = new JTextField(10);
		
		//Creat a button with the caption Calculate.
		calcButton = new JButton("Calculate");
		
		//Create a JPanel object and let the panel field reference it
		panel = new JPanel();
		
		//Add the components to the panel
		panel.add(messageLabel);
		panel.add(kiloTextField);
		panel.add(calcButton);
	}
}
And then to run it, just make another java file called KilometerConverterDemo.java with
'KiloConverterWindow kc = new KiloConverterWindow();' in the main area. you can also add this to the end of
you GUI program instead of the external main().
public static void main(String []args)
{
	KiloConverterWindow kc = new KiloConverterWindow();
}
We're almost there. There is one last thing left to see before moving on and that is handeling events with
action listeners.Basically Action Listeners are private inner classes. If I write a tut on classes i'll include it there
but for now just be content with action listeners to handle events. Events are actions that happen
withing a program, like a calculation, a transfer of data, etc... and are mostly handled by functions called "Event Listeners"
Let's use the programe KiloConverterWindow to demonstrate how an Event Listener Works...
import java.swing.*;
import java.awt.*;
import java.awt.event.*;// I like to separate them...you dont have to just remove the 1st awt.

public class KiloConverterWindow extends JFrame
{
	/** 
	Now the fun part, i'm going to descrive each element
	*/
	private JPanel panel; //The panel contains the elements you add to the window
	private JLabel messageLabel; // the Label contains text that is un-editable.
	private JTextField kiloTextField; //The text Field is usually used as a user Input area
	private JButton calcButton; // I think the name says all its a button...
	private final int WINDOW_WIDTH = 310;
	private final int WINDOW_HEIGHT = 100;
	
	/**
	Constructor
	*/
	
	public KiloConverterWindow()
	{
		//Set title
		setTitle("Kilometer Converter");
		
		//set the size
		setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
		
		//Specify the close thingy...
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		/**
		Now we add components to the panel(sort of)
		*/ 
		
		//Build the panel and add it to the frame
		buildPanel();
		
		add(panel); // adds the panel to the frame
		
		//setVisible
		setVisible(true);
		
	}
	
	/**
	Next is the build panel method to which we add a label, text field and a button
	*/
	
	private void buildPanel()
	{
		//Create a label to display instructions
		messageLabel = new JLabel("Enter a distance in kilometers");
		
		//creat a textField 10 characters wide.
		kiloTextField = new JTextField(10);
		
		//Creat a button with the caption Calculate.
		calcButton = new JButton("Calculate");
		
		//Add an action Listener to the button
		calcButton.addActionListener(new CalcButtonListener());
		
		//Create a JPanel object and let the panel field reference it
		panel = new JPanel();
		
		//Add the components to the panel
		panel.add(messageLabel);
		panel.add(kiloTextField);
		panel.add(calcButton);
	}
	
	/**
	A few lines of code come after the build panel
	*/
	
	private class CalcButtonListener implements ActionListener
	{
		/**
		The actionPerformed method executes when the user clicks
		on the button
		@param e The event object
		*/
		public void actionPerformed(ActionEvent e)
		{
			String input; // to hold the users input
			double miles; // to hold the nimber of miles
			
			//Get the text entered in the text Field.
			input = kiloTextField.getText();
			
			//convert the input into miles
			miles = Double.parseDouble(input) * 0.6214;
			
			//Display the results
			JOptionPane.showMessageDialog(null, input + " kilometers is " + miles " miles.");
		}
	}
}

For any Questions Concerning Part I, feel free to ask and i'll answer as soon as possible. Also if there are
any compiling errors let me know, i wrote this at 3am without sleeping...so yeah, and stay tuned for Part II
*****************************PART I END**************************
(Note sorry for the formating wrote it in text pad and it copied weird)
Raikiriu is offline   Reply With Quote
Old Sep 28th, 2010, 12:37 PM   #2
Bobby
Newbie
 
Join Date: Sep 2010
Posts: 1
Rep Power: 0 Bobby is on a distinguished road
Re: Java Programming Tutorial : Part I to GUI Programming

Thank you for the brilliant tutorial on GUI I like your comments, very easy to understand. I only found two typing errors; the last line had a [+] missing, and it is evident that you have retyped everything over again in each section seeing as the later import statements had [java.swing.*] at these points. Just thought you might want to know, however, no problem there.

As it goes though, when I added the last function and compiled it, there was no noticeable difference on the output.

My e-mail is <snipped> should you have the time to contact me direct, though I won’t be checking them for a day or so.

Regards ; Bobby

Last edited by Ancient Dragon; Oct 1st, 2010 at 1:04 AM. Reason: snipped email
Bobby is offline   Reply With Quote
Old Sep 30th, 2010, 9:52 PM   #3
Thanatopsis
Mainframe Developer
 
Join Date: Mar 2010
Location: Illinois
Posts: 214
Rep Power: 8 Thanatopsis is on a distinguished road
Thumbs up Re: Java Programming Tutorial : Part I to GUI Programming

This is a nice little rundown. We now have somewhere we can point people with simple Java GUI problems. yay!

hats off to Raikiriu.
__________________
"Beware of bugs in the above code; I have only proved it correct, not tried it."
-Don Knuth-
Thanatopsis is offline   Reply With Quote
Old Sep 30th, 2010, 11:46 PM   #4
DaWei
Resident Grouch
 
DaWei's Avatar
 
Join Date: Jun 2005
Posts: 8,368
Rep Power: 22 DaWei will become famous soon enoughDaWei will become famous soon enough
Re: Java Programming Tutorial : Part I to GUI Programming

Thanks.
DaWei is offline   Reply With Quote
Reply

Bookmarks

« Previous Thread in Forum | Next Thread in Forum »

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Programming With Java : Basic GUI Raikiriu Java 0 Feb 21st, 2009 2:29 AM
Java & Swing GUI Freaky Chris Java 7 Feb 7th, 2009 1:23 PM
Starting C++ GUI Programming kurt C++ 9 Jun 17th, 2008 8:35 PM
Programming with Java: Tutorial ReggaetonKing Java 7 May 20th, 2008 11:58 AM
Assembly tutorial, part one. Mad_guy Software Design and Algorithms 21 Apr 15th, 2006 8:02 PM




DaniWeb IT Discussion Community
All times are GMT -5. The time now is 5:57 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2017, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC