0% found this document useful (0 votes)
3 views7 pages

An Introduction To Java GUI Programming - CodeProject

This document serves as an introduction to Java GUI programming, targeting beginners with little to no experience. It covers the basic structure of Java GUI applications, focusing on components like JFrame and JPanel, as well as event handling through ActionListener. The article provides sample code snippets to demonstrate the creation of simple GUI elements and their functionalities in Java using AWT and Swing toolkits.

Uploaded by

abaynesh moges
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views7 pages

An Introduction To Java GUI Programming - CodeProject

This document serves as an introduction to Java GUI programming, targeting beginners with little to no experience. It covers the basic structure of Java GUI applications, focusing on components like JFrame and JPanel, as well as event handling through ActionListener. The article provides sample code snippets to demonstrate the creation of simple GUI elements and their functionalities in Java using AWT and Swing toolkits.

Uploaded by

abaynesh moges
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

An Introduction to Java GUI Programming - CodeProject [Link]

aspx

Not quite what you are looking for? You may want to try: ×
Executing commands on a remote machine - Part 1
A11Y and I18N Testing of Java based GUIs
highlights off

7,831,652 members and growing! (30,857 online)


Email Password S ign in Join Remember me? Lost password?

Home Articles Questions & Answers Learning Zones Features Help! The Lounge java gui programming
» Languages » Java » General

Licence CPOL

An Introduction to Java GUI First Posted


Views
19 Feb 2009
51,975
See Also
More like this
Downloads 0
Programming Bookmarked 38 times
More by this author

By logicchild | 19 Feb 2009


Java Windows Java SE Beginner Swing Virtualization virtual-machine

An article to launch the beginner into the world of Java GUI programming

Article Browse Code Stats Revisions (3) 4.37 (13 votes) 11 Sponsored Links

Introduction
This article is meant for the individual who has little or no experience in Java GUI programming. As
such, this paper will focus on the hierarchal tree structure that roots at the frame and goes into the
content pane panel. The primary focus will then be on the button widget (control in .NET) and the
corresponding method used to handle that event listener. Any .NET programmer will find these concepts
extremely similar, except that the coding style requires more text is some cases and the terms used are
different. A quick and easy way to compile this code on the command line after installing Sun's Java
Runtime at [Link] and Sun's J2EE SDK 5.0 is to go to the default directory: c:\Sun
\SDK\JDK\bin> type con > [Link] Ctrl-Z and then compile. To set your path:set
PATH=%PATH%;.;C:\Sun\SDK\JDK\bin.

Java GUI programming involves two packages: the original abstract windows kit (AWT) and the newer
Swing toolkit. Swing components have the prefix J to distinguish them from the original AWT ones (e.g.
JFrame instead of Frame). To include Swing components and methods in your project, you must import
the [Link].*, [Link].*, and [Link].* packages. Displayable frames are top-level
See Also...
containers such as JFrame, JWindows, JDialog, and JApplet, which interface with the operating
system's window manager. Non-displaying content panes are intermediate containers such as JPanel,
JOptionsPane, JScrollPane, and JSplitPane. Containers are therefore widgets or GUI controls that
are used to hold and group other widgets such as text boxes, check boxes, radio buttons, et al. In .NET
the main UI, called the Windows Form, holds the controls that are dragged and dropped onto the control
surface. Every GUI starts with a window meant to display things. In Swing, there are three types of
windows: the Applet, the Dialog, and the Frame. These interface with the windows manager. In swing, a
frame object is called a JFrame. A JFrame is considered the top most container. These are also called
displayable frames. Non-displaying content panes are intermediate containers such as JPanel,
JScrollPane, JLayeredPane, JSplitPane and JTabbedPane which organize the layout structure
when multiple controls are being used. Stated simply, the content pane is where we place out text fields
are other widgets, so to add and display GUI controls, we need to specify that it is the content pane that
we are adding to. The content pane is then at the top of a containment hierarchy, in which this tree-like
hierarchy has a top-level container (in our case JFrame). Working down the tree, we would find other
top level containers like JPanel to hold the components. Here is the code that produces a simple
frame upon to build on:
Collapse

import [Link].*;
import [Link].*;
import [Link].*; //notice javax
public class Frame1 extends JFrame
The Daily Insider
{
JPanel pane = new JPanel();
Frame1() // the frame constructor method
{
super("My Simple Frame"); setBounds(100,100,300,100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container con = [Link](); // inherit main frame
[Link](pane); // add the panel to frame
// customize panel here
// [Link](someWidget);
setVisible(true); // display this frame
}
public static void main(String args[]) {new Frame1();}
}

1 of 7 5/29/2011 7:53 PM
An Introduction to Java GUI Programming - CodeProject [Link]

If you have never compiled Java code, then consider this basic code in order to show the compilation
and interpretation process. As .NET compilers emit IL code and metadata, where the metadata tables are
read by the CLR to verify type safety (that is, that the correct data types are passed to the correct
methods), the JIT compiler converts the IL code into native code for execution. There is no
interpretation as there is with the Java Virtual Machine. The Java platform is defined by the APIs
(collections of compiled libraries for use programs and the JVM (which is similar to the CLR). A Java
source code file is compiled into byte code wherein a class file is generated that functions as a blueprint
for the runtime execution. Here is an example:

Collapse

import [Link].*;
public class Sys {
public static void main(String[] args) {
[Link]
(“This is a string passed to the print line method of the System class”);
}
}

Collapse

c:\Sun\SDK\jdk\bin>[Link] [Link] // the [Link] compiler


// compiles the source code

Collapse
c:\Sun\SDK\jdk\bin>[Link] Sys // the [Link] interprets the byte code file
// (in the same directory where the class file is.

This is a string passed to the print line method of the System class.

Here is code that show a GUI with a button.

The button, however, does nothing when pressed:

Collapse

import [Link].*;
import [Link].*;
import [Link].*;
public class Frame2 extends JFrame
{
JPanel pane = new JPanel();
JButton pressme = new JButton("Press Me");
Frame2() // the frame constructor
{
super("JPrompt Demo"); setBounds(100,100,300,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container con = [Link](); // inherit main frame
[Link](pane); // JPanel containers default to FlowLayout
[Link]('P'); // associate hotkey to button
[Link](pressme); [Link]();
setVisible(true); // make frame visible
}
public static void main(String args[]) {new Frame2();}
}

Collapse

C:\...\bin>[Link] [Link]

Collapse

C:\...\bin>[Link] Frame2

Java GUIs are event based as they respond to the standard input devices like key presses, mouse-
clicks, radio buttons, etc. Here is the output of the button press:

Collapse

2 of 7 5/29/2011 7:53 PM
An Introduction to Java GUI Programming - CodeProject [Link]

import [Link].*;
import [Link].*;
import [Link].*;
public class Frame3 extends JFrame implements ActionListener
{
JLabel answer = new JLabel("");
JPanel pane = new JPanel(); // create pane object
JButton pressme = new JButton("Press Me");
Frame3() // the constructor
{
super("Event Handler Demo"); setBounds(100,100,300,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container con = [Link](); // inherit main frame
[Link](pane); [Link]('P'); // associate hotkey
[Link](this); // register button listener
[Link](answer); [Link](pressme); [Link]();
setVisible(true); // make frame visible
}
// here is the basic event handler
public void actionPerformed(ActionEvent event)
{
Object source = [Link]();
if (source == pressme)
{
[Link]("Button pressed!");
[Link](null,"I hear you!","Message Dialog",
JOptionPane.PLAIN_MESSAGE); setVisible(true); // show something
}
}
public static void main(String args[]) {new Frame3();}
}

The first step in adding a basic button push event handler to the above example is to import [Link].*
which contains all of the event classes. Next add the phrase implements ActionListener to the
class header to use the interface. Register event listeners for each button widget using the
addActionListener(this) method. The reserved word this indicates that the required (by
implements ActionListener) handler method called actionPerformed() will be included in the
current class. For example, consider this more colorful example:

Collapse

3 of 7 5/29/2011 7:53 PM
An Introduction to Java GUI Programming - CodeProject [Link]

import [Link].*;
import [Link];

public class ButtonDemo{

public JPanel createContentPane (){

// We create a bottom JPanel to place everything on.


JPanel totalGUI = new JPanel();
[Link](null);

// Creation of a Panel to contain the title labels


JPanel titlePanel = new JPanel();
[Link](null);
[Link](10, 0);
[Link](250, 30);
[Link](titlePanel);

JLabel redLabel = new JLabel("Red Team");


[Link](0, 0);
[Link](100, 30);
[Link](0);
[Link]([Link]);
[Link](redLabel);

JLabel blueLabel = new JLabel("Blue Team");


[Link](120, 0);
[Link](100, 30);
[Link](0);
[Link]([Link]);
[Link](blueLabel);

// Creation of a Panel to contain the score labels.


JPanel scorePanel = new JPanel();
[Link](null);
[Link](10, 40);
[Link](250, 30);
[Link](scorePanel);

JLabel redScore = new JLabel("0");


[Link](0, 0);
[Link](100, 30);
[Link](0);
[Link](redScore);

JLabel blueScore = new JLabel("0");


[Link](120, 0);
[Link](100, 30);
[Link](0);
[Link](blueScore);

// Creation of a label to contain all the JButtons.


JPanel buttonPanel = new JPanel();
[Link](null);
[Link](10, 80);
[Link](250, 70);
[Link](buttonPanel);

// We create a button and manipulate it using the syntax we have


// used before.
JButton redButton = new JButton("Red Score!");
[Link](0, 0);
[Link](100, 30);
[Link](redButton);

JButton blueButton = new JButton("Blue Score!");


[Link](120, 0);
[Link](100, 30);
[Link](blueButton);

JButton resetButton = new JButton("Reset Score");


[Link](0, 40);
[Link](220, 30);
[Link](resetButton);

[Link](true);
return totalGUI;
}

private static void createAndShowGUI() {

[Link](true);
JFrame frame = new JFrame("[=] JButton Scores! [=]");

//Create and set up the content pane.


ButtonExample demo = new ButtonExample();
[Link]([Link]());

[Link](JFrame.EXIT_ON_CLOSE);
[Link](250, 190);
[Link](true);
}

public static void main(String[] args) {


//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
[Link](new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}

4 of 7 5/29/2011 7:53 PM
An Introduction to Java GUI Programming - CodeProject [Link]

OUTPUT

[Link]

Nothing will happen when the buttons are pressed as the event listener is needed:

Collapse

5 of 7 5/29/2011 7:53 PM
An Introduction to Java GUI Programming - CodeProject [Link]

import [Link].*;
import [Link];
import [Link];
import [Link];

public class ButtonDemo_Extended implements ActionListener{

// Definition of global values and items that are part of the GUI.
int redScoreAmount = 0;
int blueScoreAmount = 0;

JPanel titlePanel, scorePanel, buttonPanel;


JLabel redLabel, blueLabel, redScore, blueScore;
JButton redButton, blueButton, resetButton;

public JPanel createContentPane (){

// We create a bottom JPanel to place everything on.


JPanel totalGUI = new JPanel();
[Link](null);

// Creation of a Panel to contain the title labels


titlePanel = new JPanel();
[Link](null);
[Link](10, 0);
[Link](250, 30);
[Link](titlePanel);

redLabel = new JLabel("Red Team");


[Link](0, 0);
[Link](120, 30);
[Link](0);
[Link]([Link]);
[Link](redLabel);

blueLabel = new JLabel("Blue Team");


[Link](130, 0);
[Link](120, 30);
[Link](0);
[Link]([Link]);
[Link](blueLabel);

// Creation of a Panel to contain the score labels.


scorePanel = new JPanel();
[Link](null);
[Link](10, 40);
[Link](260, 30);
[Link](scorePanel);

redScore = new JLabel(""+redScoreAmount);


[Link](0, 0);
[Link](120, 30);
[Link](0);
[Link](redScore);

blueScore = new JLabel(""+blueScoreAmount);


[Link](130, 0);
[Link](120, 30);
[Link](0);
[Link](blueScore);

// Creation of a Panel to contain all the JButtons.


buttonPanel = new JPanel();
[Link](null);
[Link](10, 80);
[Link](260, 70);
[Link](buttonPanel);

// We create a button and manipulate it using the syntax we have


// used before. Now each button has an ActionListener which posts
// its action out when the button is pressed.
redButton = new JButton("Red Score!");
[Link](0, 0);
[Link](120, 30);
[Link](this);
[Link](redButton);

blueButton = new JButton("Blue Score!");


[Link](130, 0);
[Link](120, 30);
[Link](this);
[Link](blueButton);

resetButton = new JButton("Reset Score");


[Link](0, 40);
[Link](250, 30);
[Link](this);
[Link](resetButton);

[Link](true);
return totalGUI;
}

// This is the new ActionPerformed Method.


// It catches any events with an ActionListener attached.
// Using an if statement, we can determine which button was pressed
// and change the appropriate values in our GUI.
public void actionPerformed(ActionEvent e) {
if([Link]() == redButton)
{
redScoreAmount = redScoreAmount + 1;
[Link](""+redScoreAmount);
}
else if([Link]() == blueButton)
{

6 of 7 5/29/2011 7:53 PM
An Introduction to Java GUI Programming - CodeProject [Link]

Suggested Reading
The Guidebook at [Link]
JR's Education Pages at [Link]

History
20th February, 2009: Initial post

License
This article, along with any associated source code and files, is licensed under The Code Project Open
License (CPOL)

About the Author

logicchild I started electronics training at age 33. I began studying microprocessor


technology in an RF communications oriented program. I am 43 years old now.
Other I have studied C code, opcode (mainly x86 and AT+T) for around 3 years in
Pref. Trust order to learn how to recognize viral code and the use of procedural languages.
United States I am currently learning C# and the other virtual runtime system languages. I
guess I started with the egg rather than the chicken. My past work would
Member indicate that my primary strength is in applied mathematics.

Sign Up to vote for this article


Article Top
Advertisement

Comments and Discussions


You must Sign In to use this message board. (secure sign-in)
FAQ FAQ S earch

Profile popups Noise level Medium Layout Normal Per page 25 U pdat e

Msgs 1 to 11 of 11 (Total in Forum: 11) (Refresh) First PrevNext


My vote of 2 itvntbu 0:33 19 Apr '11

thank you! melanie santos 2:48 15 Apr '10

Great Article Syed M Hussain 0:10 14 Jul '09

Nice! Vu1ture 5:05 23 Apr '09

Good One. Seun 11:51 3 Mar '09

good one!! Ohad Redlich 3:59 3 Mar '09

So glad to have left Java well behind me, I have to say I do not 5:19 24 Feb '09
Sacha Barber
miss it at all.
Re: So glad to have left Java well behind me, I have to say I do not 4:25 26 Feb '09
Sike Mullivan
miss it at all.
Re: So glad to have left Java well behind me, I have to say I do not 7:39 6 Mar '09
Leblanc Meneses
miss it at all.
Re: So glad to have left Java well behind me, I have to say I do 21:59 6 Mar '09
Sacha Barber
not miss it at all.
thank u virsam 0:13 20 Feb '09

Last Visit: 19:00 31 Dec '99 Last Update: 7:50 29 May '11 1

General News Question Answer Joke Rant Admin

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+PgUp/PgDown to switch pages.

link | Privacy | Terms of Use | Mobile Copyright 2009 by logicchild


Last Updated: 19 Feb 2009 Everything else Copyright © CodeProject, 1999-2011
Web23 | Advertise on the Code Project

7 of 7 5/29/2011 7:53 PM

You might also like