Chuyển tới nội dung
Home » Java Swing Programs Examples With Output | Java Swing Tooltip

Java Swing Programs Examples With Output | Java Swing Tooltip

Swing application to add two numbers using Java using IntellIj | Java GUI

Components of Swing Class the task’s percentage

Component A Component is the Abstract base class for about the non-menu user-interface controls of Java SWING. Components are representing an object with a graphical representation.
Container A Container is a component that can container Java SWING Components
JComponent A JComponent is a base class for all swing UI Components In order to use a swing component that inherits from JComponent, the component must be in a containment hierarchy whose root is a top-level Java Swing container.
JLabel A JLabel is an object component for placing text in a container.
JButton This class creates a labeled button.
JColorChooser A JColorChooser provides a pane of controls designed to allow the user to manipulate and select a color.
JCheckBox A JCheckBox is a graphical (GUI) component that can be in either an on-(true) or off-(false) state.
JRadioButton The JRadioButton class is a graphical (GUI) component that can be in either an on-(true) or off-(false) state. in the group
JList A JList component represents the user with the scrolling list of text items.
JComboBox A JComboBox component is Presents the User with a show up Menu of choices.
JTextField A JTextField object is a text component that will allow for the editing of a single line of text.
JPasswordField A JPasswordField object it is a text component specialized for password entry.
JTextArea A JTextArea object is a text component that allows for the editing of multiple lines of text.
Imagelcon A ImageIcon control is an implementation of the Icon interface that paints Icons from Images
JScrollbar A JScrollbar control represents a scroll bar component in order to enable users to Select from range values.
JOptionPane JOptionPane provides set of standard dialog boxes that prompt users for a value or Something.
JFileChooser A JFileChooser it Controls represents a dialog window from which the user can select a file.
JProgressBar As the task progresses towards completion, the progress bar displays the tasks percentage on its completion.
JSlider A JSlider this class is letting the user graphically (GUI) select by using a value by sliding a knob within a bounded interval.
JSpinner A JSpinner this class is a single line input where the field that lets the user select by using a number or an object value from an ordered sequence.

Feeling lost in the vast world of Backend Development? It’s time for a change! Join our Java Backend Development – Live Course and embark on an exciting journey to master backend development efficiently and on schedule. What We Offer:

  • Comprehensive Course
  • Expert Guidance for Efficient Learning
  • Hands-on Experience with Real-world Projects
  • Proven Track Record with 100,000+ Successful Geeks

Last Updated :
09 Jan, 2024

Like Article

Save Article

Share your thoughts in the comments

Please Login to comment…

History[edit]

The Internet Foundation Classes (IFC) were a graphics library for Java originally developed by Netscape Communications Corporation and first released on December 16, 1996. On April 2, 1997, Sun Microsystems and Netscape Communications Corporation announced their intention to incorporate IFC with other technologies to form the Java Foundation Classes.[4] The “Java Foundation Classes” were later renamed “Swing.”

Swing introduced a mechanism that allowed the look and feel of every component in an application to be altered without making substantial changes to the application code. The introduction of support for a pluggable look and feel allows Swing components to emulate the appearance of native components while still retaining the benefits of platform independence.
Originally distributed as a separately downloadable library, Swing has been included as part of the Java Standard Edition since release 1.2.[5] The Swing classes and components are contained in the

javax.swing

package hierarchy.

Development of Swing’s successor, JavaFX, started in 2005, and it was officially introduced two years later at JavaOne 2007.[6] JavaFX was open-sourced in 2011 and, in 2012, it became part of the Oracle JDK download. JavaFX is replacing Swing owing to several advantages, including being more lightweight, having CSS styling, sleek design controls, and the use of FXML and Scene Builder.[7] In 2018, JavaFX was made a part of the OpenJDK under the OpenJFX project to increase the pace of its development.[8]

Members of the Java Client team that was responsible for Swing included James Gosling (Architect), Rick Levenson (manager), Amy Fowler & Hans Muller (co-technical leads), Tom Ball, Jeff Dinkins, Georges Saab,[9] Tim Prinzing, Jonni Kanerva, and Jeannette Hung & Jim Graham (2D Graphics).[10]

Swing application to add two numbers using Java using IntellIj | Java GUI
Swing application to add two numbers using Java using IntellIj | Java GUI

Java Swing standard colours

The

Color

class defines thirteen colour values, including red,
green, blue, and yellow.

package com.zetcode; import javax.swing.GroupLayout; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import java.awt.Color; import java.awt.Dimension; import java.awt.EventQueue; import java.util.ArrayList; class MyLabel extends JLabel { public MyLabel() { super(“”, null, LEADING); } @Override public boolean isOpaque() { return true; } } public class StandardColoursEx extends JFrame { public StandardColoursEx() { initUI(); } private void initUI() { Color[] stdCols = { Color.black, Color.blue, Color.cyan, Color.darkGray, Color.gray, Color.green, Color.lightGray, Color.magenta, Color.orange, Color.pink, Color.red, Color.white, Color.yellow }; var labels = new ArrayList

(); for (var col : stdCols) { var lbl = createColouredLabel(col); labels.add(lbl); } createLayout(labels.toArray(new JLabel[0])); setTitle(“Standard colours”); setLocationRelativeTo(null); setDefaultCloseOperation(EXIT_ON_CLOSE); } private JLabel createColouredLabel(Color col) { var lbl = new MyLabel(); lbl.setMinimumSize(new Dimension(90, 40)); lbl.setBackground(col); return lbl; } private void createLayout(JLabel[] labels) { var pane = (JPanel) getContentPane(); var gl = new GroupLayout(pane); pane.setLayout(gl); pane.setToolTipText(“Content pane”); gl.setAutoCreateContainerGaps(true); gl.setAutoCreateGaps(true); gl.setHorizontalGroup(gl.createParallelGroup() .addGroup(gl.createSequentialGroup() .addComponent(labels[0]) .addComponent(labels[1]) .addComponent(labels[2]) .addComponent(labels[3])) .addGroup(gl.createSequentialGroup() .addComponent(labels[4]) .addComponent(labels[5]) .addComponent(labels[6]) .addComponent(labels[7])) .addGroup(gl.createSequentialGroup() .addComponent(labels[8]) .addComponent(labels[9]) .addComponent(labels[10]) .addComponent(labels[11])) .addComponent(labels[12]) ); gl.setVerticalGroup(gl.createSequentialGroup() .addGroup(gl.createParallelGroup() .addComponent(labels[0]) .addComponent(labels[1]) .addComponent(labels[2]) .addComponent(labels[3])) .addGroup(gl.createParallelGroup() .addComponent(labels[4]) .addComponent(labels[5]) .addComponent(labels[6]) .addComponent(labels[7])) .addGroup(gl.createParallelGroup() .addComponent(labels[8]) .addComponent(labels[9]) .addComponent(labels[10]) .addComponent(labels[11])) .addComponent(labels[12]) ); pack(); } public static void main(String[] args) { EventQueue.invokeLater(() -> { var ex = new StandardColoursEx(); ex.setVisible(true); }); } }

The example shows thirteen

JLabel

components; each of the labels
has a different background colour.

JLabel

is usually used
to display text; but it can display colours, too.

class MyLabel extends JLabel { public MyLabel() { super(“”, null, LEADING); } @Override public boolean isOpaque() { return true; } }


JLabel

component is a specific component with a default transparent background.
In order to paint on a label, we override the

isOpaque()

method, which
returns

true

.

Color[] stdCols = { Color.black, Color.blue, Color.cyan, Color.darkGray, Color.gray, Color.green, Color.lightGray, Color.magenta, Color.orange, Color.pink, Color.red, Color.white, Color.yellow };

Here we have an array of the built-in static colour values.

var labels = new ArrayList

(); for (var col : stdCols) { var lbl = createColouredLabel(col); labels.add(lbl); }

A list of

JLabel

components is created. A new label is
created with the

createColouredLabel()

method.

public JLabel createColouredLabel(Color col) { var lbl = new MyLabel(); lbl.setMinimumSize(new Dimension(90, 40)); lbl.setBackground(col); return lbl; }

The

createColouredLabel()

method creates a new label.
We set a minimum size for the label. The

setBackground()

sets the background colour for a component.

Conclusion

Any desktop application can be developed easily using both Java AWT and Java Swing toolkits. The most commonly used Swing controls to develop the desktop applications are used in 15 examples of this tutorial. This tutorial will help the new Java programmers to learn the method of developing the desktop applications using the Java Swing controls from the basic.

Java Swing For Beginners | What is Java Swing | Java Swing Tutorial | Intellipaat
Java Swing For Beginners | What is Java Swing | Java Swing Tutorial | Intellipaat

Difference between Java Swing and Java AWT

There are certain points from which Java Swing is different than Java AWT as mentioned below:

Java AWT is an API to develop GUI applications in Java.

Swing is a part of Java Foundation Classes and is used to create various applications.

Components of AWT are heavy weighted.

The components of Java Swing are lightweight.

Components are platform dependent.

Components are platform independent.

Execution Time is more than Swing.

Execution Time is less than AWT.

AWT components require java.awt package.

Swing components requires javax.swing package.

To know more about the topic, refer to Java Swing vs Java AWT.

Form Design with Some Basic Controls

Java has many swing controls to take input from the user. Create a Java file with the following code to know the uses of some basic swing controls. The uses of textbox, radio buttons, and text area controls are shown in this example. The textbox is used to take the product name. The radio button is used to select the product type. The text area is used to take the product description.

class SwingExample3 {

public static void main(String[] args) {

//Declare frame object

JFrame win = new JFrame();

//Set the title

win.setTitle(“Java Swing Example-3”);

//Set the window size

win.setSize(500, 320);

//Create a label object, set the position, and add to the frame

JLabel lbl1 = new JLabel(“Product Name:”, JLabel.LEFT);

lbl1.setBounds(80,20,100,20);

win.add(lbl1);

//Create text object set the position, and add to the frame

JTextField name = new JTextField();

name.setBounds(200,20,200,20);

win.add(name);

//Create a label object, set the position, and add to the frame

JLabel lbl2 = new JLabel(“Product Type:”, JLabel.LEFT);

lbl2.setBounds(80,60,100,20);

win.add(lbl2);

//Create the radio buttons, set the position, and add to the frame

JRadioButton rdbtn1 = new JRadioButton(“Local”);

rdbtn1.setActionCommand(“Local”);

JRadioButton rdbtn2 = new JRadioButton(“Foreign”);

rdbtn2.setActionCommand(“Foreign”);

rdbtn1.setBounds(200,40,80,50);

rdbtn2.setBounds(300,40,90,50);

ButtonGroup bgrp = new ButtonGroup();

bgrp.add(rdbtn1);

bgrp.add(rdbtn2);

win.add(rdbtn1);

win.add(rdbtn2);

/*Create a label object, set the position, and add to the frame */

JLabel lbl3 = new JLabel(“Desctiption:”, JLabel.LEFT);

lbl3.setBounds(80,100,120,20);

win.add(lbl3);

//Create textarea object set the position, and add to the frame

JTextArea txtArea = new JTextArea();

txtArea.setBounds(200,100,200,100);

win.add(txtArea);

//Create a button, set the position, and add to the frame

JButton btn = new JButton(“Submit”);

btn.setBounds(200, 220, 100, 30);

win.add(btn);

//Set window position

win.setLocationRelativeTo(null);

//Disable the default layout of the frame

win.setLayout(null);

//Make the window visible

win.setVisible(true);

Output:

The following dialog box will appear after executing the Java class file:

JAVA - How To Design Login And Register Form In Java Netbeans
JAVA – How To Design Login And Register Form In Java Netbeans

JButton example

In our next example, we will have a button. When we click on the button, the application terminates.

package com.zetcode; import javax.swing.GroupLayout; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFrame; import java.awt.EventQueue; public class QuitButtonEx extends JFrame { public QuitButtonEx() { initUI(); } private void initUI() { var quitButton = new JButton(“Quit”); quitButton.addActionListener((event) -> System.exit(0)); createLayout(quitButton); setTitle(“Quit button”); setSize(300, 200); setLocationRelativeTo(null); setDefaultCloseOperation(EXIT_ON_CLOSE); } private void createLayout(JComponent… arg) { var pane = getContentPane(); var gl = new GroupLayout(pane); pane.setLayout(gl); gl.setAutoCreateContainerGaps(true); gl.setHorizontalGroup(gl.createSequentialGroup() .addComponent(arg[0]) ); gl.setVerticalGroup(gl.createSequentialGroup() .addComponent(arg[0]) ); } public static void main(String[] args) { EventQueue.invokeLater(() -> { var ex = new QuitButtonEx(); ex.setVisible(true); }); } }

We position a

JButton

on the window and add an action listener
to this button.

var quitButton = new JButton(“Quit”);

Here we create a button component. This constructor takes a string label as a parameter.

quitButton.addActionListener((event) -> System.exit(0));

We plug an action listener to the button. The action terminates the
application by calling the

System.exit()

method.

createLayout(quitButton);

The child components need to be placed into containers. We delegate the task
to the

createLayout()

method.

var pane = getContentPane(); var gl = new GroupLayout(pane); pane.setLayout(gl);

The content pane of a

JFrame

is an area where child components
are placed. The children are organised by specialised non-visible components
called layout managers. The default layout manager of a content pane is
the

BorderLayout

manager. This manager is very simple.
In this tutorial, we use the

GroupLayout

manager which is
more powerful and flexible.

gl.setAutoCreateContainerGaps(true);

The

setAutoCreateContainerGaps()

method creates gaps between components
and the edges of the container. Space or gaps are important part of the design
of each application.

gl.setHorizontalGroup(gl.createSequentialGroup() .addComponent(arg[0]) ); gl.setVerticalGroup(gl.createSequentialGroup() .addComponent(arg[0]) );


GroupLayout

manager defines the layout for each dimension independently.
In one step, we lay out components alongside the horizontal axis; in the other
step, we lay out components along the vertical axis. In both kinds of layouts we can arrange
components sequentially or in parallel. In a horizontal layout, a row of components
is called a sequential group and a column of components is called a
parallel group. In a vertical layout, a column of components is called a
sequential group and a row of components a parallel group.

In our example we have only one button, so the layout is very simple. For each dimension,
we call the

addComponent()

method with the button component as a parameter.
(Each child component must be added for both dimensions.)

See also[edit]

  • swingLabs – Extensions to Swing
  • Standard Widget Toolkit – A third party widget toolkit maintained by the Eclipse Foundation.
  • JavaFX – A software platform for creating and delivering desktop applications as well as rich internet applications that can run across a wide variety of devices, which is intended to be the successor to Swing. JavaFX is under the OpenJFX project.[18]
Java program to Make Calculator | Learn Coding
Java program to Make Calculator | Learn Coding

Java Swing tooltip

Tooltips are part of the internal application’s help system. Swing shows a small window if we hover a mouse pointer over an object that has a tooltip set.

package com.zetcode; import java.awt.EventQueue; import javax.swing.GroupLayout; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JPanel; public class TooltipEx extends JFrame { public TooltipEx() { initUI(); } private void initUI() { var btn = new JButton(“Button”); btn.setToolTipText(“A button component”); createLayout(btn); setTitle(“Tooltip”); setLocationRelativeTo(null); setDefaultCloseOperation(EXIT_ON_CLOSE); } private void createLayout(JComponent… arg) { var pane = (JPanel) getContentPane(); var gl = new GroupLayout(pane); pane.setLayout(gl); pane.setToolTipText(“Content pane”); gl.setAutoCreateContainerGaps(true); gl.setHorizontalGroup(gl.createSequentialGroup() .addComponent(arg[0]) .addGap(200) ); gl.setVerticalGroup(gl.createSequentialGroup() .addComponent(arg[0]) .addGap(120) ); pack(); } public static void main(String[] args) { EventQueue.invokeLater(() -> { var ex = new TooltipEx(); ex.setVisible(true); }); } }

In the example, we set a tooltip for the frame and the button.

btn.setToolTipText(“A button component”);

To enable a tooltip, we call the

setTooltipText()

method.

var pane = (JPanel) getContentPane(); var gl = new GroupLayout(pane); pane.setLayout(gl);

A content pane is an instance of a

JPanel

component.
The

getContentPane()

method returns a

Container

type. Since setting a tooltip requires a

JComponent

instance,
we cast the object to a

JPanel

.

pane.setToolTipText(“Content pane”);

A tooltip is set for the content pane.

gl.setHorizontalGroup(gl.createSequentialGroup() .addComponent(arg[0]) .addGap(200) ); gl.setVerticalGroup(gl.createSequentialGroup() .addComponent(arg[0]) .addGap(120) );

We call the

addGap()

method for horizontal and vertical dimensions.
It creates some space to the right and to the bottom of the button. (The aim
is to increase the initial size of the window.)

pack();

The

pack()

method automatically sizes

JFrame

based on the size of its components. It takes the defined space into account,
too. Our window will display the button and the spaces that we have set
with the

addGap()

method.

Display the Different Types of Dialog Boxes

Different dialog boxes are used in Java to display the messages with different types of buttons and take input from the user. Create a Java file with the following code that displays a message box with an OK button, a message box with the Yes, No, and Cancel buttons, and an input dialog box to take input from the user.

class SwingExample4 {

public static void main(String[] args) {

//Declare a JFrame object

JFrame frame = new JFrame();

//Display a simple message dialog box with a default icon

JOptionPane.showMessageDialog(frame,”Learn Java Swing”);

//Display a simple message dialog box with a warning icon

JOptionPane.showMessageDialog(frame,”Something is missing.”,”Alert”,JOptionPane.WARNING_MESSAGE);

//Take input from the confirm dialog box

int input =JOptionPane.showConfirmDialog(frame,”Do you want to learn Java swing?”);

//Check whether the user pressed YES or not

if(input == JOptionPane.YES_OPTION){

JOptionPane.showMessageDialog(null, “Glad to hear it.”);

//Take string value from the user

String answer = JOptionPane.showInputDialog(“What is your favorite programming language? “);

//Display message with the input value

JOptionPane.showMessageDialog(null, “You like ” + answer + “!”);

Output:

Different dialog boxes will appear one after another after executing the Java class file. The first message box with the OK button appears in the output:

The second message box with an alert icon and an OK button appears in the next output:

The third message box with three buttons appears in the next output:

The following output will appear if the user will select the “Yes” button from the previous dialog box:

Next, the following input dialog box will appear to take input from the user:

The value that is taken from the user is displayed in the last message box:

Senior Programmers vs Junior Developers #shorts
Senior Programmers vs Junior Developers #shorts

What is Swing in Java?

Swing in Java is a Graphical User Interface (GUI) toolkit that includes the GUI components. Swing provides a rich set of widgets and packages to make sophisticated GUI components for Java applications. Swing is a part of Java Foundation Classes(JFC), which is an API for Java GUI programing that provide GUI.

The Java Swing library is built on top of the Java Abstract Widget Toolkit (AWT), an older, platform dependent GUI toolkit. You can use the Java simple GUI programming components like button, textbox, etc., from the library and do not have to create the components from scratch.

In this Java Swing tutorial, you will learn Java GUI basics like-

  • What is Swing in Java?
  • What is a Container Class?
  • What is GUI in Java?
  • How to Make a GUI in Java with Example
  • Java Layout Manager
  • Java BorderLayout
  • Java FlowLayout
  • Java GridBagLayout

Java Swing class Hierarchy Diagram

All components in Java Swing are JComponent which can be added to container classes.

Java Swing mouse move events


MouseMotionAdapter

is used for receiving mouse motion events.

package com.zetcode; import javax.swing.GroupLayout; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JLabel; import java.awt.Container; import java.awt.EventQueue; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionAdapter; public class MouseMoveEventEx extends JFrame { private JLabel coords; public MouseMoveEventEx() { initUI(); } private void initUI() { coords = new JLabel(“”); createLayout(coords); addMouseMotionListener(new MouseMotionAdapter() { @Override public void mouseMoved(MouseEvent e) { super.mouseMoved(e); int x = e.getX(); int y = e.getY(); var text = String.format(“x: %d, y: %d”, x, y); coords.setText(text); } }); setTitle(“Mouse move events”); setSize(300, 200); setLocationRelativeTo(null); setDefaultCloseOperation(EXIT_ON_CLOSE); } private void createLayout(JComponent… arg) { var pane = getContentPane(); var gl = new GroupLayout(pane); pane.setLayout(gl); gl.setAutoCreateContainerGaps(true); gl.setHorizontalGroup(gl.createParallelGroup() .addComponent(arg[0]) .addGap(250) ); gl.setVerticalGroup(gl.createSequentialGroup() .addComponent(arg[0]) .addGap(130) ); pack(); } public static void main(String[] args) { EventQueue.invokeLater(() -> { var ex = new MouseMoveEventEx(); ex.setVisible(true); }); } }

In the example, we display the coordinates of a mouse pointer in a label component.

addMouseMotionListener(new MouseMotionAdapter() { @Override public void mouseMoved(MouseEvent e) { super.mouseMoved(e); int x = e.getX(); int y = e.getY(); var text = String.format(“x: %d, y: %d”, x, y); coords.setText(text); } });

We override the

moseMoved()

method of the adapter. From
the

MouseEvent

object we get the x and y coordinates
of the mouse pointer, build a string and set it to the label.

In this chapter, we have created some simple Java Swing programs.

Introduction

So far, we have covered the basic programming constructs (such as variables, data types, decision, loop, array and method) and introduced the important concept of Object-Oriented Programming (OOP). As discussed, OOP permits higher level of abstraction than traditional Procedural-Oriented Languages (such as C). You can create high-level abstract data types called classes to mimic real-life things. These classes are self-contained and are reusable.

In this article, I shall show you how you can reuse the graphics classes provided in JDK for constructing your own Graphical User Interface (GUI) applications. Writing your own graphics classes (and re-inventing the wheels) is mission impossible! These graphics classes, developed by expert programmers, are highly complex and involve many advanced design patterns. However, re-using them are not so difficult, if you follow the API documentation, samples and templates provided.

I shall assume that you have a good grasp of OOP, including composition, inheritance, polymorphism, abstract class and interface; otherwise, read the earlier articles. I will describe another important OO concept called nested class (or inner class) in this article.

There are current three sets of Java APIs for graphics programming: AWT (Abstract Windowing Toolkit), Swing and JavaFX.

  1. AWT API was introduced in JDK 1.0. Most of the AWT UI components have become obsolete and should be replaced by newer Swing UI components.
  2. Swing API, a much more comprehensive set of graphics libraries that enhances the AWT, was introduced as part of Java Foundation Classes (JFC) after the release of JDK 1.1. JFC consists of Swing, Java2D, Accessibility, Internationalization, and Pluggable Look-and-Feel Support APIs. JFC has been integrated into core Java since JDK 1.2.
  3. The latest JavaFX, which was integrated into JDK 8, was meant to replace Swing. JavaFX was moved out from the JDK in JDK 11, but still available as a separate module.

Other than AWT/Swing/JavaFX graphics APIs provided in JDK, other organizations/vendors have also provided graphics APIs that work with Java, such as Eclipse’s Standard Widget Toolkit (SWT) (used in Eclipse), Google Web Toolkit (GWT) (used in Android), 3D Graphics API such as Java bindings for OpenGL (JOGL), Java3D, and etc. Furthermore, developers have moved to use technologies such as HTML5 as the basis of webapps.

You need to refer to the “JDK API documentation” for the AWT/Swing APIs (under module

java.desktop

) while reading this chapter. The best online reference for Graphics programming is the “Swing Tutorial” @ http://docs.oracle.com/javase/tutorial/uiswing/. For advanced 2D graphics programming, read “Java 2D Tutorial” @ http://docs.oracle.com/javase/tutorial/2d/index.html. For 3D graphics, read my 3D articles.

Programming GUI with AWT

I shall start with the AWT before moving into Swing to give you a complete picture of Java Graphics.

AWT Packages

AWT is huge! It consists of 12 packages of 370 classes (Swing is even bigger, with 18 packages of 737 classes as of JDK 8). Fortunately, only 2 packages –

java.awt

and

java.awt.event

– are commonly-used.

  1. The

    java.awt

    package contains the core AWT graphics classes:

    • GUI Component classes, such as

      Button

      ,

      TextField

      , and

      Label

      .
    • GUI Container classes, such as

      Frame

      and

      Panel

      .
    • Layout managers, such as

      FlowLayout

      ,

      BorderLayout

      and

      GridLayout

      .
    • Custom graphics classes, such as

      Graphics

      ,

      Color

      and

      Font

      .
  2. GUI Component classes, such as
  3. The

    java.awt.event

    package supports event handling:

    • Event classes, such as

      ActionEvent

      ,

      MouseEvent

      ,

      KeyEvent

      and

      WindowEvent

      ,
    • Event Listener Interfaces, such as

      ActionListener

      ,

      MouseListener

      ,

      MouseMotionListener

      ,

      KeyListener

      and

      WindowListener

      ,
    • Event Listener Adapter classes, such as

      MouseAdapter

      ,

      KeyAdapter

      , and

      WindowAdapter

      .
  4. Event classes, such as

AWT provides a platform-independent and device-independent interface to develop graphic programs that runs on all platforms, including Windows, macOS, and Unixes.

AWT Containers and Components

There are two groups of GUI elements:

  1. Component (Widget, Control): Components are elementary GUI entities, such as

    Button

    ,

    Label

    , and

    TextField

    . They are also called widgets, controls in other graphics systems.
  2. Container: Containers, such as

    Frame

    and

    Panel

    , are used to hold components in a specific layout (such as

    FlowLayout

    or

    GridLayout

    ). A container can also hold sub-containers.

In the above figure, there are three containers: a

Frame

and two

Panel

s. A

Frame

is the top-level container of an AWT program. A

Frame

has a title bar (containing an icon, a title, and the minimize/maximize/close buttons), an optional menu bar and the content display area. A

Panel

is a rectangular area used to group related GUI components in a certain layout. In the above figure, the top-level

Frame

contains two

Panel

s. There are five components: a

Label

(providing description), a

TextField

(for users to enter text), and three

Button

s (for user to trigger certain programmed actions).

In a GUI program, a component must be kept (or added) in a container.
You need to identify a container to hold the components. Every container has a method called

add(Component c)

. A

container

(say

aContainer

) can invoke

aContainer.add(aComponent)

to add

aComponent

into itself. For example,

Panel pnl = new Panel(); // Panel is a container Button btn = new Button(“Press”); // Button is a component pnl.add(btn); // The Panel container adds a Button component

GUI components are also called controls (e.g., Microsoft ActiveX Control), widgets (e.g., Eclipse’s Standard Widget Toolkit, Google Web Toolkit), which allow users to interact with (or control) the application.

AWT Container Classes
Top-Level Containers: Frame, Dialog and Applet

Each GUI program has a top-level container. The commonly-used top-level containers in AWT are

Frame

,

Dialog

and

Applet

:

  • A

    Frame

    provides the “main window” for your GUI application. It has a title bar (containing an icon, a title, the minimize, maximize/restore-down and close buttons), an optional menu bar, and the content display area. To write a GUI program, we typically start with a subclass extending from

    java.awt.Frame

    to inherit the main window as follows:

    import java.awt.Frame; // Using Frame class in package java.awt // A GUI program is written as a subclass of Frame – the top-level container // This subclass inherits all properties from Frame, e.g., title, icon, buttons, content-pane public class MyGUIProgram extends Frame { // private variables …… // Constructor to setup the GUI components and event handlers public MyGUIProgram() { …… } // The entry main() method public static void main(String[] args) { // Invoke the constructor (to setup the GUI) by allocating an instance new MyGUIProgram(); } }

  • An AWT

    Dialog

    is a “pop-up window” used for interacting with the users. A

    Dialog

    has a title-bar (containing an icon, a title and a close button) and a content display area, as illustrated.
  • An AWT

    Applet

    (in package

    java.applet

    ) is the top-level container for an applet, which is a Java program running inside a browser. Applet is no longer supported in most of the browsers.
Secondary Containers: Panel and ScrollPane

Secondary containers are placed inside a top-level container or another secondary container. AWT provides these secondary containers:


  • Panel

    : a rectangular box used to layout a set of related GUI components in pattern such as grid or flow.

  • ScrollPane

    : provides automatic horizontal and/or vertical scrolling for a single child component.
  • others.
Hierarchy of the AWT Container Classes

The hierarchy of the AWT

Container

classes is as follows:

As illustrated, a

Container

has a

LayoutManager

to layout the components in a certain pattern, e.g., flow, grid.

AWT Component Classes

AWT provides many ready-made and reusable GUI components in package

java.awt

. The frequently-used are:

Button

,

TextField

,

Label

,

Checkbox

,

CheckboxGroup

(radio buttons),

List

, and

Choice

, as illustrated below.

AWT GUI Component: java.awt.Label

A

java.awt.Label

provides a descriptive text string. Take note that

System.out.println()

prints to the system console, NOT to the graphics screen. You could use a

Label

to label another component (such as text field) to provide a text description.

Check the JDK API specification for

java.awt.Label

.

Constructors

public Label(String strLabel, int alignment); // Construct a Label with the given text String, of the text alignment public Label(String strLabel); // Construct a Label with the given text String public Label(); // Construct an initially empty Label

The

Label

class has three constructors:

  1. The first constructor constructs a

    Label

    object with the given text string in the given alignment. Note that three

    static

    constants

    Label.LEFT

    ,

    Label.RIGHT

    , and

    Label.CENTER

    are defined in the class for you to specify the alignment (rather than asking you to memorize arbitrary integer values).
  2. The second constructor constructs a

    Label

    object with the given text string in default of left-aligned.
  3. The third constructor constructs a

    Label

    object with an initially empty string. You could set the label text via the

    setText()

    method later.

Constants (

final static

fields)

public static final LEFT; // Label.LEFT public static final RIGHT; // Label.RIGHT public static final CENTER; // Label.CENTER

These three constants are defined for specifying the alignment of the

Label

‘s text, as used in the above constructor.

Public Methods

// Examples public String getText(); public void setText(String strLabel); public int getAlignment(); public void setAlignment(int alignment); // Label.LEFT, Label.RIGHT, Label.CENTER

The

getText()

and

setText()

methods can be used to read and modify the

Label

‘s text. Similarly, the

getAlignment()

and

setAlignment()

methods can be used to retrieve and modify the alignment of the text.

Constructing a Component and Adding the Component into a Container

Three steps are necessary to create and place a GUI component:

  1. Declare the component with an identifier (name);
  2. Construct the component by invoking an appropriate constructor via the

    new

    operator;
  3. Identify the container (such as

    Frame

    or

    Panel

    ) designed to hold this component. The container can then add this component onto itself via

    aContainer.add(aComponent)

    method. Every container has a

    add(Component)

    method. Take note that it is the container that actively and explicitly adds a component onto itself, NOT the other way.

Example

Label lblInput; // Declare an Label instance called lblInput lblInput = new Label(“Enter ID”); // Construct by invoking a constructor via the new operator add(lblInput); // this.add(lblInput) – “this” is typically a subclass of Frame lblInput.setText(“Enter password”); // Modify the Label’s text string lblInput.getText(); // Retrieve the Label’s text string

An Anonymous Label Instance

You can create a

Label

without specifying an identifier, called anonymous instance. In the case, the Java compiler will assign an anonymous identifier for the allocated object. You will not be able to reference an anonymous instance in your program after it is created. This is usually alright for a

Label

instance as there is often no need to reference a

Label

after it is constructed.

Example

// Allocate an anonymous Label instance. // “this” container adds the instance. // You CANNOT reference an anonymous instance to carry out further operations. add(new Label(“Enter Name: “, Label.RIGHT)); // Same as Label xxx = new Label(“Enter Name: “, Label.RIGHT)); // xxx assigned by compiler add(xxx);

AWT GUI Component: java.awt.Button

A

java.awt.Button

is a GUI component that triggers a certain programmed action upon clicking.

Constructors

public Button(String btnLabel); // Construct a Button with the given label public Button(); // Construct a Button with empty label

The

Button

class has two constructors. The first constructor creates a

Button

object with the given label painted over the button. The second constructor creates a

Button

object with no label.

Public Methods

public String getLabel(); // Get the label of this Button instance public void setLabel(String btnLabel); // Set the label of this Button instance public void setEnable(boolean enable); // Enable or disable this Button. Disabled Button cannot be clicked.

The

getLabel()

and

setLabel()

methods can be used to read the current label and modify the label of a button, respectively.

Note: The latest Swing’s

JButton

replaces

getLabel()/setLabel()

with

getText()/setText()

to be consistent with all the components. We will describe Swing later.

Event

Clicking a button fires a so-called

ActionEvent

and triggers a certain programmed action. I will explain event-handling later.

Example

Button btnColor = new Button(“Red”); // Declare and allocate a Button instance called btnColor add(btnColor); // “this” Container adds the Button … btnColor.setLabel(“Green”); // Change the button’s label btnColor.getLabel(); // Read the button’s label

AWT GUI Component: java.awt.TextField

A

java.awt.TextField

is single-line text box for users to enter texts. (There is a multiple-line text box called

TextArea

.) Hitting the “ENTER” key on a

TextField

object fires an

ActionEvent

.

Constructors

public TextField(String initialText, int columns); // Construct a TextField instance with the given initial text string with the number of columns. public TextField(String initialText); // Construct a TextField instance with the given initial text string. public TextField(int columns); // Construct a TextField instance with the number of columns.

Public Methods

public String getText(); // Get the current text on this TextField instance public void setText(String strText); // Set the display text on this TextField instance public void setEditable(boolean editable); // Set this TextField to editable (read/write) or non-editable (read-only)

Event

Hitting the “ENTER” key on a

TextField

fires a

ActionEvent

, and triggers a certain programmed action.

Example

TextField tfInput = new TextField(30); // Declare and allocate an TextField instance called tfInput add(tfInput); // “this” Container adds the TextField TextField tfResult = new TextField(); // Declare and allocate an TextField instance called tfResult tfResult.setEditable(false) ; // Set to read-only add(tfResult); // “this” Container adds the TextField …… // Read an int from TextField “tfInput”, square it, and display on “tfResult”. // getText() returns a String, need to convert to int int number = Integer.parseInt(tfInput.getText()); number *= number; // setText() requires a String, need to convert the int number to String. tfResult.setText(number + “”);

Take note that

getText()/SetText()

operates on

String

. You can convert a

String

to a primitive, such as

int

or

double

via

static

method

Integer.parseInt()

or

Double.parseDouble()

. To convert a primitive to a

String

, simply concatenate the primitive with an empty

String

.

Example 1: AWTCounter

Let’s assemble a few components together into a simple GUI counter program, as illustrated. It has a top-level container

Frame

, which contains three components – a

Label

“Counter”, a non-editable

TextField

to display the current count, and a “Count”

Button

. The

TextField

shall display count of initially.

Each time you click the button, the counter’s value increases by 1.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66

import java.awt.*; // Using AWT container and component classes import java.awt.event.*; // Using AWT event classes and listener interfaces // An AWT program inherits from the top-level container java.awt.Frame public class AWTCounter extends Frame { private Label lblCount; // Declare a Label component private TextField tfCount; // Declare a TextField component private Button btnCount; // Declare a Button component private int count = 0; // Counter’s value // Constructor to setup GUI components and event handlers public AWTCounter () { setLayout(new FlowLayout()); // “super” Frame, which is a Container, sets its layout to FlowLayout to arrange // the components from left-to-right, and flow to next row from top-to-bottom. lblCount = new Label(“Counter”); // construct the Label component add(lblCount); // “super” Frame container adds Label component tfCount = new TextField(count + “”, 10); // construct the TextField component with initial text tfCount.setEditable(false); // set to read-only add(tfCount); // “super” Frame container adds TextField component btnCount = new Button(“Count”); // construct the Button component add(btnCount); // “super” Frame container adds Button component BtnCountListener listener = new BtnCountListener(); btnCount.addActionListener(listener); // “btnCount” is the source object that fires an ActionEvent when clicked. // The source object adds an instance of BtnCountListener as an ActionEvent listener, // which provides an ActionEvent handler called actionPerformed(). // Clicking “Count” button calls back actionPerformed(). setTitle(“AWT Counter”); // “super” Frame sets its title setSize(300, 100); // “super” Frame sets its initial window size // For inspecting the Container/Components objects // System.out.println(this); // System.out.println(lblCount); // System.out.println(tfCount); // System.out.println(btnCount); setVisible(true); // “super” Frame shows // System.out.println(this); // System.out.println(lblCount); // System.out.println(tfCount); // System.out.println(btnCount); } // The entry main() method public static void main(String[] args) { // Invoke the constructor to setup the GUI, by allocating an instance AWTCounter app = new AWTCounter(); // or simply “new AWTCounter();” for an anonymous instance } // Define an inner class to handle the “Count” button-click private class BtnCountListener implements ActionListener { // ActionEvent handler – Called back upon button-click. @Override public void actionPerformed(ActionEvent evt) { ++count; // Increase the counter value // Display the counter value on the TextField tfCount tfCount.setText(count + “”); // Convert int to String } } }

To exit this program, you have to close the CMD-shell (or press “control-c” on the CMD console); or push the “red” close button in Eclipse’s Application Console. This is because we have yet to write the handler for the

Frame

‘s close button. We shall do that in the later example.

Dissecting the AWTCounter.java

  • The

    import

    statements (Lines 1-2) are needed, as AWT container and component classes, such as

    Frame

    ,

    Button

    ,

    TextField

    , and

    Label,

    are kept in the

    java.awt

    package; while AWT events and event-listener interfaces, such as

    ActionEvent

    and

    ActionListener

    are kept in the

    java.awt.event

    package.
  • A GUI program needs a top-level container, and is often written as a subclass of

    Frame

    (Line 5). In other words, this class

    AWTCounter

    is a

    Frame

    , and inherits all the attributes and behaviors of a

    Frame

    , such as the title bar and content pane.
  • Lines 11 to 47 define a constructor, which is used to setup the GUI components and event handlers.
  • In Line 13, the

    setLayout()

    (inherited from the superclass

    Frame

    ) is used to set the layout of the container.

    FlowLayout

    is used which arranges the components in left-to-right and flows into next row in a top-to-bottom manner.
  • A

    Label

    ,

    TextField

    (non-editable), and

    Button

    are constructed. We invoke the

    add()

    method (inherited from the superclass

    Frame

    ) to add these components into container
  • In Line 34-35, we invoke the

    setSize()

    and the

    setTitle()

    (inherited from the superclass

    Frame

    ) to set the initial size and the title of the

    Frame

    . The

    setVisible(true)

    method (Line 42) is then invoked to show the display.
  • Line 27-28 is used to setup the callback event-handler, which will be discussed in length later. In brief, whenever the button is clicked, the

    actionPerformed()

    will be called. In the

    actionPerformed()

    (Lines 59-64), the counter value increases by 1 and displayed on the

    TextField

    .
  • In the entry

    main()

    method (Lines 50-54), an instance of

    AWTCounter

    is constructed. The constructor is executed to initialize the GUI components and setup the event-handlers. The GUI program then waits for the user action.
Inspecting Container/Components via toString()

It is interesting to inspect the GUI objects via the

toString()

, to gain an insight to these classes. (Alternatively, use a graphic debugger in Eclipse/NetBeans or study the JDK source code.) For example, if we insert the following code before and after the

setvisible()

:

System.out.println(this); //AWTCounter[frame0,93,0,300×100,invalid,hidden,layout=java.awt.FlowLayout,title=AWT Counter,resizable,normal] // name (assigned by compiler) is “frame0”; top-left (x,y) at (93,0); width/height is 300×100 (via setSize()); System.out.println(lblCount); //java.awt.Label[label0,0,0,0×0,invalid,align=left,text=Counter] // name is “Label0”; align is “Label.LEFT” (default); text is “Counter” (assigned in constructor) System.out.println(tfCount); //java.awt.TextField[textfield0,0,0,0×0,invalid,text=0,selection=0-0] // name is “Textfield0”; text is “0” (assigned in constructor) System.out.println(btnCount); //java.awt.Button[button0,0,0,0×0,invalid,label=Count] // name is “button0”; label text is “Count” (assigned in constructor) setVisible(true); // “super” Frame shows System.out.println(this); //AWTCounter[frame0,93,0,300×100,invalid,layout=java.awt.FlowLayout,title=AWT Counter,resizable,normal] System.out.println(lblCount); //java.awt.Label[label0,31,35,57×23,align=left,text=Counter] System.out.println(tfCount); //java.awt.TextField[textfield0,93,35,124×23,text=0,selection=0-0] System.out.println(btnCount); //java.awt.Button[button0,222,35,46×23,label=Count]

Example 2: AWTAccumulator

In this example, the top-level container is again the typical

java.awt.Frame

. It contains 4 components: a

Label

“Enter an Integer”, a

TextField

for accepting user input, another

Label

“The Accumulated Sum is”, and another non-editable

TextField

for displaying the sum. The components are arranged in

GridLayout

of 2 rows 2 columns.

The program shall accumulate the number entered into the input

TextField

and display the sum in the output

TextField

.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60

import java.awt.*; // Using AWT container and component classes import java.awt.event.*; // Using AWT event classes and listener interfaces // An AWT GUI program inherits (customized) from the top-level container // java.awt.Frame public class AWTAccumulator extends Frame { //private Label lblInput; // Declare input Label (to use anonymous) //private Label lblOutput; // Declare output Label (to use anonymous) private TextField tfInput; // Declare input TextField private TextField tfOutput; // Declare output TextField private int sum = 0; // Accumulated sum, init to 0 // Constructor to setup the GUI components and event handlers public AWTAccumulator() { setLayout(new GridLayout(2, 2)); // “super” Frame (Container) sets layout to GridLayout of 2 rows 2 columns. add(new Label(“Enter an Integer: “)); // “super” Frame adds an anonymous Label tfInput = new TextField(10); // Construct TextField add(tfInput); // “super” Frame adds TextField tfInput.addActionListener(new TFInputListener()); // “tfInput” is the source object that fires an ActionEvent upon entered. // The source add an anonymous instance of TFInputListener as an ActionEvent // listener, which provides an ActionEvent handler called actionPerformed(). // Hitting “enter” on tfInput invokes actionPerformed(). add(new Label(“The Accumulated Sum is: “)); // “super” Frame adds an anonymous Label tfOutput = new TextField(10); // allocate TextField tfOutput.setEditable(false); // read-only add(tfOutput); // “super” Frame adds TextField setTitle(“AWT Accumulator”); // “super” Frame sets title setSize(350, 120); // “super” Frame sets initial window size setVisible(true); // “super” Frame shows } // The entry main() method public static void main(String[] args) { // Invoke the constructor to setup the GUI, by allocating an anonymous instance new AWTAccumulator(); } // Define an inner class to handle the input TextField. // An ActionEvent listener must implement ActionListener interface. private class TFInputListener implements ActionListener { // ActionEvent handler – Called back upon hitting “enter” key on TextField @Override public void actionPerformed(ActionEvent evt) { // Get the String entered into the TextField tfInput, convert to int int numberIn = Integer.parseInt(tfInput.getText()); sum += numberIn; // Accumulate numbers entered into sum tfInput.setText(“”); // Clear input TextField tfOutput.setText(sum + “”); // Display sum on the output TextField // convert int to String } } }

Dissecting the AWTAccumulator.java

  1. An AWT GUI program extends from

    java.awt.Frame

    (Line 6) – the top-level window container.
  2. In the constructor (Line 14), we constructs 4 components – 2 anonymous

    java.awt.Label

    s and 2

    java.awt.TextField

    s. The

    Frame

    adds the components, in

    GridLayout

    .

  3. tfInput

    (

    TextField

    ) is the source object, which fires an

    ActionEvent

    upon hitting the Enter key.

    tfInput

    adds an anonymous instance of

    TFInputListener

    as an

    ActionEvent

    handler (Line 23). The listener class needs to implement

    ActionListener

    interface and provides implementation to method

    actionPerformed()

    . Whenever an user hits Enter on the

    tfInput

    (

    TextField

    ), the

    actionPerformed()

    will be called back.

AWT Event-Handling

Java adopts the so-called “Event-Driven” (or “Event-Delegation”) programming model for event-handling, similar to most of the visual programming languages like Visual Basic.

In event-driven programming, a piece of event-handling codes is executed (or called back by the graphics subsystem) when an event was fired in response to an user input (such as clicking a mouse button or hitting the ENTER key in a text field).

Callback Methods

In the above examples, the method

actionPerformed()

is known as a callback method. In other words, you never invoke

actionPerformed()

in your codes explicitly. The

actionPerformed()

is called back by the graphics subsystem under certain circumstances in response to certain user actions.

JavaScript can attach a Callback method to an Event Directly

In some languages, you can directly attach a method (or function) to an event (such as mouse-click). For example, the following JavaScript code (called

JSCounter.html

) implement a counter similar to the

AWTCounter

, with a text label, text field and button:

<br /> JavaScript Counter<br />

Count:



In Java, we CANNOT attach a method to a source object directly, as method is not a first-class object in Java. For example, a Java method cannot accept methods as its arguments and it cannot return a method; you cannot assign a method to a variable, etc. (JavaScript and C language CAN!).

Source, Event and Listener Objects

The AWT’s event-handling classes are kept in package

java.awt.event

.

Three kinds of objects are involved in the event-handling: a source, listener(s) and an event object.

The source object (such as

Button

and

Textfield

) interacts with the user. Upon triggered, the source object creates an event object to capture the action (e.g., mouse-click x and y, texts entered, etc). This event object will be messaged to all the registered listener object(s), and an appropriate event-handler method of the listener(s) is called-back to provide the response. In other words, triggering a source fires an event to all its listener(s), and invoke an appropriate event handler of the listener(s).

To express interest for a certain source’s event, the listener(s) must be registered with the source. In other words, the listener(s) “subscribes” to a source’s event, and the source “publishes” the event to all its subscribers upon activation. This is known as subscribe-publish or observable-observer design pattern.

The sequence of steps is illustrated above:

  1. The source object registers its listener(s) for a certain type of event.

    A source fires an event when triggered. For example, clicking a


    Button

    fires an

    ActionEvent

    , clicking a mouse button fires

    MouseEvent

    , typing a key fires

    KeyEvent

    , and etc.

    How the source and listener understand each other? The answer is via an agreed-upon interface. For example, if a source is capable of firing an event called


    XxxEvent

    (e.g.,

    ActionEvent

    ). Firstly, we need to declare an interface called

    XxxListener

    (e.g.,

    ActionListener

    ) containing the names of the handler methods (recall that an

    interface

    contains only

    abstract

    methods without implementation). For example, the

    ActionListener

    interface is declared as follows:

    // An ActionListener interface, which declares the signature of the handlers public interface ActionListener { public void actionPerformed(ActionEvent evt); }

    Secondly, all


    XxxEvent

    listeners must implement the

    XxxListener

    interface. That is, the listeners must provide their own implementations (i.e., programmed responses) to all the

    abstract

    methods declared in the

    XxxListener

    interface. In this way, the listener(s) can response to these events appropriately. For example,

    // An example of MouseListener, which provides implementation to the event handler methods class MyActionListener implement ActionListener { @Override public void actionPerformed(ActionEvent evt) { System.out.println(“ActionEvent detected!”); } }

    Thirdly, in the source, we need to maintain a list of


    XxxEvent

    listener object(s), and define two methods:

    addXxxListener()

    and

    removeXxxListener()

    to add and remove a

    XxxEvent

    listener from this list. For the

    ActionEvent

    , the signature of the methods are:

    public void addActionListener(ActionListener lis); public void removeActionListener(ActionListener lis);

    Take note that the


    addXxxListenser()

    takes a

    XxxListener

    object as its sole parameter. In other words, it can only add objects of the type

    XxxListener

    , and its sub-type. Since

    XxxListener

    is an

    interface

    , you cannot create instance of

    XxxListener

    , but need to create instance of a subclass implementing the

    XxxListener


    interface

    .

    In summary, we identify the source, the event-listener interface, and the listener object. The listener must implement the event-listener interface. The source object then registers listener object via the


    addXxxListener(XxxListener lis)

    method.

  2. The source is triggered by a user.
  3. The source create a

    XxxEvent

    object, which encapsulates the necessary information about the activation. For example, the

    (x, y)

    position of the mouse pointer, the text entered, etc.
  4. Finally, for each of the

    XxxEvent

    listeners in the listener list, the source invokes the appropriate handler on the listener(s), which provides the programmed response.

In summary, triggering a source fires an event to all its registered listeners, and invoke an appropriate handler of the listener.

Revisit Example 1 AWTCounter: ActionEvent and ActionListener Interface

Clicking a

Button

(or hitting the “Enter” key on a

TextField

) fires an

ActionEvent

to all its

ActionEvent

listener(s). An

ActionEvent

listener must implement the

ActionListener

interface, which declares one

abstract

method called

actionPerformed()

as follow:

public interface ActionListener { public void actionPerformed(ActionEvent evt); // Called back upon button-click (on Button), enter-key pressed (on TextField) }

Here are the event-handling steps:

  • We identify

    btnCount

    (of

    Button

    ) as the source object.
  • Clicking

    Button

    fires an

    ActionEvent

    to all its

    ActionEvent

    listener(s).
  • The listener(s) is required to implement

    ActionListener

    interface, and override the

    actionPerformed()

    method to provide the response. In Line 56-65, we write an inner class called

    BtnCountListener

    , which override the

    actionPerformed()

    to increment and display the count. An inner class is a class defined inside an outer class, and it can access the private entities of the outer class. We will elaborate on the inner class in the next section.
  • The source object registers listener via the

    addActionListener()

    . In this example, the source

    btnCount

    (

    Button

    ) adds an instance of

    BtnCountListener

    as a listener via:

    BtnCountListener listener = new BtnCountListener(); btnCount.addActionListener(listener);

    Note that


    addActionListener()

    takes an argument of the type

    ActionListener

    .

    BtnCountListener

    , which implements

    ActionListener

    interface (i.e., a subclass of

    ActionListener

    ), is upcasted and passed to the

    addActionListener()

    method.

  • Upon button-click, the

    btnCount

    creates an

    ActionEvent

    object, and calls back the

    actionPerformed(ActionEvent)

    method of all its registered listener(s) with the

    ActionEvent

    object created:

    ActionEvent evt = new ActionEvent( …… ); listener.actionPerformed(evt); // for all its listener(s)

The sequence diagram is as follows:

Revisit Example 2 AWTAccumulator: ActionEvent and ActionListener Interface

In this example,

  1. We identify the

    tfInput

    (of

    TextField

    ) as the source object.
  2. Hitting the “Enter” key on a

    TextField

    fires an

    ActionEvent

    to all its

    ActionEvent

    listener(s).
  3. In Line 46-59, we define an inner class called

    TFInputListener

    as the

    ActionEvent

    listener.The

    ActionEvent

    listener is required to implement the

    ActionListener

    interface, and override the

    actionPerformed()

    method to provide the programmed response upon activation.
  4. The source object

    tfInput

    (of

    TextField

    ) registers an anonymous instance of

    TFInputListener

    as its

    ActionEvent

    listener via the

    tfInput.addActionListener(new TFInputListener())

    (Line 23).
Example 3: WindowEvent and WindowListener Interface

A

WindowEvent

is fired (to all its

WindowEvent

listeners) when a window (e.g.,

Frame

) has been opened/closed, activated/deactivated, iconified/deiconified via the 3 buttons at the top-right corner or other means. The source of

WindowEvent

shall be a top-level window-container such as

Frame

.

A

WindowEvent

listener must implement

WindowListener

interface, which declares 7

abstract

event-handling methods, as follows. Among them, the

windowClosing()

, which is called back upon clicking the window-close button, is the most commonly-used.

public void windowClosing(WindowEvent evt) // Called-back when the user attempts to close the window by clicking the window close button. // This is the most-frequently used handler. public void windowOpened(WindowEvent evt) // Called-back the first time a window is made visible. public void windowClosed(WindowEvent evt) // Called-back when a window has been closed as the result of calling dispose on the window. public void windowActivated(WindowEvent evt) // Called-back when the Window is set to be the active Window. public void windowDeactivated(WindowEvent evt) // Called-back when a Window is no longer the active Window. public void windowIconified(WindowEvent evt) // Called-back when a window is changed from a normal to a minimized state. public void windowDeiconified(WindowEvent evt) // Called-back when a window is changed from a minimized to a normal state.

The following program added support for “close-window button” to “Example 1: AWTCounter”.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70

import java.awt.*; // Using AWT containers and components import java.awt.event.*; // Using AWT events classes and listener interfaces // An AWT GUI program inherits the top-level container java.awt.Frame public class WindowEventDemo extends Frame { private TextField tfCount; // Declare a TextField component private Button btnCount; // Declare a Button component private int count = 0; // Counter’s value // Constructor to setup the GUI components and event handlers public WindowEventDemo() { setLayout(new FlowLayout()); // “super” Frame sets to FlowLayout add(new Label(“Counter”)); // “super” Frame adds an anonymous Label tfCount = new TextField(“0”, 10); // Construct the TextField tfCount.setEditable(false); // read-only add(tfCount); // “super” Frame adds TextField btnCount = new Button(“Count”); // Construct the Button add(btnCount); // “super” Frame adds Button btnCount.addActionListener(new BtnCountListener()); // btnCount (source object) fires ActionEvent upon clicking // btnCount adds an anonymous instance of BtnCountListener // as an ActionEvent listener addWindowListener(new MyWindowListener()); // “super” Frame (source object) fires WindowEvent. // “super” Frame adds an anonymous instance of MyWindowListener // as a WindowEvent listener. setTitle(“WindowEvent Demo”); // “super” Frame sets title setSize(300, 100); // “super” Frame sets initial size setVisible(true); // “super” Frame shows } // The entry main() method public static void main(String[] args) { new WindowEventDemo(); // Let the construct do the job } // Define an inner class to handle ActionEvent of btnCount private class BtnCountListener implements ActionListener { @Override public void actionPerformed(ActionEvent evt) { ++count; tfCount.setText(count + “”); } } // Define an inner class to handle WindowEvent of this Frame private class MyWindowListener implements WindowListener { // Called back upon clicking close-window button @Override public void windowClosing(WindowEvent evt) { System.exit(0); // Terminate the program } // Not Used, BUT need to provide an empty body to compile. @Override public void windowOpened(WindowEvent evt) { } @Override public void windowClosed(WindowEvent evt) { } // For Debugging @Override public void windowIconified(WindowEvent evt) { System.out.println(“Window Iconified”); } @Override public void windowDeiconified(WindowEvent evt) { System.out.println(“Window Deiconified”); } @Override public void windowActivated(WindowEvent evt) { System.out.println(“Window Activated”); } @Override public void windowDeactivated(WindowEvent evt) { System.out.println(“Window Deactivated”); } } }

In this example, we shall modify the earlier

AWTCounter

example to handle the

WindowEvent

. Recall that pushing the “close-window” button on the

AWTCounter

has no effect, as it did not handle the

WindowEvent

of

windowClosing()

. We included the

WindowEvent

handling codes in this example.

  1. We identify the

    super


    Frame

    as the source object.
  2. The

    Frame

    fires the

    WindowEvent

    to all its registered

    WindowEvent

    listener(s).
  3. In Line 53-69, we define an inner class called

    MyWindowListener

    as the

    WindowEvent

    listener. It is required to implement the

    WindowListener

    interface, which declares 7 abstract methods:

    windowOpened()

    ,

    windowClosed()

    ,

    windowClosing()

    ,

    windowActivated()

    ,

    windowDeactivated()

    ,

    windowIconified()

    and

    windowDeiconified()

    .
  4. We register an anonymous instance of

    MyWindowListener

    as the

    WindowEvent

    listener to the source

    Frame

    via method

    addWindowListener(new MyWindowListener())

    .
  5. We override the

    windowClosing()

    handler to terminate the program using

    System.exit(0)

    . We ignore the other 6 handlers, but required to provide an empty body for compilation.

The sequence diagram is as follow:

Example 4: MouseEvent and MouseListener Interface

A

MouseEvent

is fired when you press, release, or click (press followed by release) a mouse-button (left or right button) at the source object; or position the mouse-pointer at (enter) and away (exit) from the source object.

A

MouseEvent

listener must implement the

MouseListener

interface, which declares the following five

abstract

methods:

public void mouseClicked(MouseEvent evt) // Called-back when the mouse-button has been clicked (pressed followed by released) on the source. public void mousePressed(MouseEvent evt) public void mouseReleased(MouseEvent evt) // Called-back when a mouse-button has been pressed/released on the source. // A mouse-click invokes mousePressed(), mouseReleased() and mouseClicked(). public void mouseEntered(MouseEvent evt) public void mouseExited(MouseEvent evt) // Called-back when the mouse-pointer has entered/exited the source.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57

import java.awt.*; import java.awt.event.*; public class MouseEventDemo extends Frame { private TextField tfMouseX; // to display mouse-click-x private TextField tfMouseY; // to display mouse-click-y // Constructor – Setup the UI components and event handlers public MouseEventDemo() { setLayout(new FlowLayout()); // “super” frame sets its layout to FlowLayout // Label (anonymous) add(new Label(“X-Click: “)); // “super” frame adds Label component // TextField tfMouseX = new TextField(10); // 10 columns tfMouseX.setEditable(false); // read-only add(tfMouseX); // “super” frame adds TextField component // Label (anonymous) add(new Label(“Y-Click: “)); // “super” frame adds Label component // TextField tfMouseY = new TextField(10); tfMouseY.setEditable(false); // read-only add(tfMouseY); // “super” frame adds TextField component addMouseListener(new MyMouseListener()); // “super” frame (source) fires the MouseEvent. // “super” frame adds an anonymous instance of MyMouseListener // as a MouseEvent listener. setTitle(“MouseEvent Demo”); // “super” Frame sets title setSize(350, 100); // “super” Frame sets initial size setVisible(true); // “super” Frame shows } public static void main(String[] args) { new MouseEventDemo(); // Let the constructor do the job } // Define an inner class to handle MouseEvent private class MyMouseListener implements MouseListener { // Called back upon mouse clicked @Override public void mouseClicked(MouseEvent evt) { tfMouseX.setText(evt.getX() + “”); tfMouseY.setText(evt.getY() + “”); } // Not used – need to provide an empty body to compile. @Override public void mousePressed(MouseEvent evt) { } @Override public void mouseReleased(MouseEvent evt) { } @Override public void mouseEntered(MouseEvent evt) { } @Override public void mouseExited(MouseEvent evt) { } } }

In this example, we setup a GUI with 4 components (two anonynous

Label

s and two non-editable

TextField

s) inside a top-level container

Frame

, arranged in

FlowLayout

.

To demonstrate the

MouseEvent

:

  1. We identity

    super


    Frame

    as the source object.
  2. The

    Frame

    fires a

    MouseEvent

    to all its

    MouseEvent

    listener(s) when you click/press/release a mouse-button or enter/exit with the mouse-pointer.
  3. In Line 42-56, we define an inner class called

    MyMouseListener

    as the

    MouseEvent

    listener. It is required to implement the

    MouseListener

    interface, which declares 5 abstract methods:

    mouseClicked()

    ,

    mousePressed()

    ,

    mouseReleased()

    ,

    mouseEntered()

    , and

    mouseExit()

    . We override the

    mouseClicked()

    to display the (x, y) coordinates of the mouse click on the two displayed

    TextField

    s. We ignore all the other handlers (for simplicity – but you need to provide an empty body for compilation).
  4. We register an anonymous instance of

    MyMouseListener

    as the

    MouseEvent

    listener to

    super


    Frame

    (source) via the method

    addMouseListener(new MyMouseListener())

    .

Try: Include a

WindowListener

to handle the close-window button.

Example 5: MouseEvent and MouseMotionListener Interface

A

MouseEvent

is also fired when you move and drag the mouse pointer at the source object. But you need to use

MouseMotionListener

to handle the mouse-move and mouse-drag. The

MouseMotionListener

interface declares the following two abstract methods:

public void mouseDragged(MouseEvent e) // Called-back when a mouse-button is pressed on the source component and then dragged. public void mouseMoved(MouseEvent e) // Called-back when the mouse-pointer has been moved onto the source component but no buttons have been pushed.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81

import java.awt.*; import java.awt.event.*; // An AWT GUI program inherits from the top-level container java.awt.Frame public class MouseMotionDemo extends Frame { // To display the (x, y) of the mouse-clicked private TextField tfMouseClickX; private TextField tfMouseClickY; // To display the (x, y) of the current mouse-pointer position private TextField tfMousePositionX; private TextField tfMousePositionY; // Constructor to setup the GUI components and event handlers public MouseMotionDemo() { setLayout(new FlowLayout()); // “super” frame sets to FlowLayout add(new Label(“X-Click: “)); tfMouseClickX = new TextField(10); tfMouseClickX.setEditable(false); add(tfMouseClickX); add(new Label(“Y-Click: “)); tfMouseClickY = new TextField(10); tfMouseClickY.setEditable(false); add(tfMouseClickY); add(new Label(“X-Position: “)); tfMousePositionX = new TextField(10); tfMousePositionX.setEditable(false); add(tfMousePositionX); add(new Label(“Y-Position: “)); tfMousePositionY = new TextField(10); tfMousePositionY.setEditable(false); add(tfMousePositionY); MyMouseListener listener = new MyMouseListener(); addMouseListener(listener); addMouseMotionListener(listener); // “super” frame (source) fires MouseEvent. // “super” frame adds an instance of MyMouseListener // as MouseListener and MouseMotionListener. setTitle(“MouseMotion Demo”); // “super” Frame sets title setSize(400, 120); // “super” Frame sets initial size setVisible(true); // “super” Frame shows } // The entry main() method public static void main(String[] args) { new MouseMotionDemo(); // Let the constructor do the job } // Define an inner class as both the MouseListener and MouseMotionListener // A Java class can extend one superclass but implement many interfaces private class MyMouseListener implements MouseListener, MouseMotionListener { /* MouseListener handlers */ // Called back when a mouse-button has been clicked @Override public void mouseClicked(MouseEvent evt) { tfMouseClickX.setText(evt.getX() + “”); tfMouseClickY.setText(evt.getY() + “”); } // Not Used, but need to provide an empty body for compilation @Override public void mousePressed(MouseEvent evt) { } @Override public void mouseReleased(MouseEvent evt) { } @Override public void mouseEntered(MouseEvent evt) { } @Override public void mouseExited(MouseEvent evt) { } /* MouseMotionEvent handlers */ // Called back when the mouse-pointer has been moved @Override public void mouseMoved(MouseEvent evt) { tfMousePositionX.setText(evt.getX() + “”); tfMousePositionY.setText(evt.getY() + “”); } // Not Used, but need to provide an empty body for compilation @Override public void mouseDragged(MouseEvent evt) { } } }

In this example, we shall illustrate both the

MouseListener

and

MouseMotionListener

.

  1. We identify the

    super


    Frame

    as the source, which fires the

    MouseEvent

    to its registered

    MouseListener

    and

    MouseMotionListener
  2. In Line 53-80, we define an inner class called

    MyMouseListener

    as both the

    MouseListener

    and

    MouseMotionListner

    .
  3. We register an instance of

    MyMouseListener

    as the

    super


    Frame

    via method

    addMouseListener()

    and

    addMouseMotionListener()

    .
  4. The

    MouseMotionListener

    needs to implement 2 abstract methods:

    mouseMoved()

    and

    mouseDragged()

    declared in the

    MouseMotionListener

    interface.
  5. We override the

    mouseMoved()

    to display the (x, y) position of the mouse pointer. We ignore the

    MouseDragged()

    handler by providing an empty body for compilation.

Try: Include a

WindowListener

to handle the close-window button.

Example 6: KeyEvent and KeyListener Interface

A

KeyEvent

is fired when you pressed, released, and typed (pressed followed by released) a key on the source object. A

KeyEvent

listener must implement

KeyListener

interface, which declares three abstract methods:

public void keyTyped(KeyEvent e) // Called-back when a key has been typed (pressed and released). public void keyPressed(KeyEvent e) public void keyReleased(KeyEvent e) // Called-back when a key has been pressed or released.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47

import java.awt.*; import java.awt.event.*; // An AWT GUI program inherits from the top-level container java.awt.Frame public class KeyEventDemo extends Frame { private TextField tfInput; // Single-line TextField to receive tfInput key private TextArea taDisplay; // Multi-line TextArea to taDisplay result // Constructor to setup the GUI components and event handlers public KeyEventDemo() { setLayout(new FlowLayout()); // “super” frame sets to FlowLayout add(new Label(“Enter Text: “)); tfInput = new TextField(10); add(tfInput); taDisplay = new TextArea(5, 40); // 5 rows, 40 columns add(taDisplay); tfInput.addKeyListener(new MyKeyListener()); // tfInput TextField (source) fires KeyEvent. // tfInput adds an anonymous instance of MyKeyListener // as a KeyEvent listener. setTitle(“KeyEvent Demo”); // “super” Frame sets title setSize(400, 200); // “super” Frame sets initial size setVisible(true); // “super” Frame shows } // The entry main() method public static void main(String[] args) { new KeyEventDemo(); // Let the constructor do the job } // Define an inner class to handle KeyEvent private class MyKeyListener implements KeyListener { // Called back when a key has been typed (pressed and released) @Override public void keyTyped(KeyEvent evt) { taDisplay.append(“You have typed ” + evt.getKeyChar() + “\n”); } // Not Used, but need to provide an empty body for compilation @Override public void keyPressed(KeyEvent evt) { } @Override public void keyReleased(KeyEvent evt) { } } }

In this example:

  1. We identify the

    tfInput

    (of

    TextField

    ) as the source object.
  2. The source fires a

    KeyEvent

    when you press/release/type a key to all its

    KeyEvent

    listener(s).
  3. In Line 35-46, we define an inner class called

    MyKeyListener

    as the

    KeyEvent

    listener.
  4. We register an anonymous instance of

    MyKeyListener

    as the

    KeyEvent

    listener to the source

    TextField

    via method

    input.addKeyListener()

    .
  5. The

    KeyEvent

    listener needs to implement the

    KeyListener

    interface, which declares 3 abstract methods:

    keyTyped()

    ,

    keyPressed()

    ,

    keyReleased()

    .
  6. We override the

    keyTyped()

    to display key typed on the display

    TextArea

    . We ignore the

    keyPressed()

    and

    keyReleased()

    .

Nested (Inner) Classes

Without Inner classes

In our

AWTCounter

example, suppose we would like to write an external ordinary class (say

MyExternalBtnListener

) as our

ActionEvent

listener. This class shall implement

ActionListener

interface and override the

actionPerformed()

method. An example is as follows:

import java.awt.*; // Using AWT container and component classes import java.awt.event.*; // Using AWT event classes and listener interfaces // An AWT program inherits from the top-level container java.awt.Frame public class AWTCounterExternal extends Frame { private Label lblCount; // Declare a Label component private TextField tfCount; // Declare a TextField component private Button btnCount; // Declare a Button component private int count = 0; // Counter’s value // Constructor to setup GUI components and event handlers public AWTCounterExternal () { setLayout(new FlowLayout()); // “super” Frame, which is a Container, sets its layout to FlowLayout to arrange // the components from left-to-right, and flow to next row from top-to-bottom. lblCount = new Label(“Counter”); // construct the Label component add(lblCount); // “super” Frame container adds Label component tfCount = new TextField(count + “”, 10); // construct the TextField component with initial text tfCount.setEditable(false); // set to read-only add(tfCount); // “super” Frame container adds TextField component btnCount = new Button(“Count”); // construct the Button component add(btnCount); // “super” Frame container adds Button component MyExternalBtnListener listener = new MyExternalBtnListener(); btnCount.addActionListener(listener); // “btnCount” is the source object that fires an ActionEvent when clicked. // The source add an instance of MyExternalBtnListener as an ActionEvent listener, // which provides an ActionEvent handler called actionPerformed(). // Clicking “btnCount” invokes actionPerformed(). setTitle(“AWT Counter”); // “super” Frame sets its title setSize(250, 100); // “super” Frame sets its initial window size // For inspecting the Container/Components objects // System.out.println(this); // System.out.println(lblCount); // System.out.println(tfCount); // System.out.println(btnCount); setVisible(true); // “super” Frame shows // System.out.println(this); // System.out.println(lblCount); // System.out.println(tfCount); // System.out.println(btnCount); } // The entry main() method public static void main(String[] args) { // Invoke the constructor to setup the GUI, by allocating an instance AWTCounterExternal app = new AWTCounterExternal(); // or simply “new AWTCounter();” for an anonymous instance } } // We write an external class as the Button’s ActionEvent listener. // This class must implement ActionListener interface and override // the actionPerformed() method. class MyExternalBtnListener implements ActionListener { // ActionEvent handler – Called back upon button-click. @Override public void actionPerformed(ActionEvent evt) { System.out.println(“You clicked the button!”); // Cannot access variables count and tfCount!!! // ++count; // Increase the counter value // tfCount.setText(count + “”); // Convert int to String } }

Can you see the problem? This external class cannot access the variables such as

count

and

tfCount

in the

AWTCounterExternal

class. We can fix this problem, but the solution is messy. An easy solution is to use an inner class instead of an ordinary external class (to be explained in the following sections).

What are Inner classes?

A nested class (or commonly called inner class) is a class defined inside another class – introduced in JDK 1.1. As an illustration, two nested classes

MyNestedClass1

and

MyNestedClass2

are defined inside the definition of an outer class called

MyOuterClass

.

public class MyOuterClass { // outer class defined here …… private class MyNestedClass1 { …… } // an nested class defined inside the outer class public static class MyNestedClass2 { …… } // an “static” nested class defined inside the outer class …… }

A nested class has these properties:

  1. A nested class is a proper class. That is, it could contain constructors, member variables and member methods. You can create an instance of a nested class via the

    new

    operator and constructor.
  2. A nested class is a member of the outer class, just like any member variables and methods defined inside a class.
  3. Most importantly, a nested class can access the

    private

    members (variables/methods) of the enclosing outer class, as it is at the same level as these

    private

    members. This is the property that makes inner class useful.
  4. A nested class can have

    private

    ,

    public

    ,

    protected

    , or the default access, just like any member variables and methods defined inside a class. A

    private

    inner class is only accessible by the enclosing outer class, and is not accessible by any other classes. [An top-level outer class cannot be declared

    private

    , as no one can use a

    private

    outer class.]
  5. A nested class can also be declared

    static

    ,

    final

    or

    abstract

    , just like any ordinary class.
  6. A nested class is NOT a subclass of the outer class. That is, the nested class does not inherit the variables and methods of the outer class. It is an ordinary self-contained class. [Nonetheless, you could declare it as a subclass of the outer class, via keyword ”

    extends OuterClassName

    “, in the nested class’s definition.]

The usages of nested class are:

  1. To control visibilities (of the member variables and methods) between inner/outer class. The nested class, being defined inside an outer class, can access

    private

    members of the outer class.
  2. To place a piece of class definition codes closer to where it is going to be used, to make the program clearer and easier to understand.
  3. For namespace management.
Example 7: A Named Inner Class as Event Listener (Revisit Example 1 AWTCounter)

A nested class is useful if you need a small class which relies on the enclosing outer class for its private variables and methods. It is ideal in an event-driven environment for implementing event handlers. This is because the event handling methods (in a listener) often require access to the private variables (e.g., a private

TextField

) of the outer class.

In this example (revisit Example 1

AWTCounter

), we define an inner class called

BtnCountListener

, and create an instance of

BtnCountListener

as the

ActionEvent

listener for the

btnCount

. The

BtnCountListener

needs to implement the

ActionListener

interface, and override the

actionPerformed()

handler.

BtnCountListener

needs to be defined as an inner class, as it needs to access private variables (

count

and

tfCount

) of the outer class.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48

import java.awt.*; import java.awt.event.*; // An AWT GUI program inherits from the top-level container java.awt.Frame public class AWTCounter extends Frame { // The event-handler actionPerformed() needs to access these “private” variables private TextField tfCount; private Button btnCount; private int count = 0; // Constructor to setup the GUI components and event handlers public AWTCounter() { setLayout(new FlowLayout()); // “super” Frame sets to FlowLayout add(new Label(“Counter”)); // An anonymous instance of Label tfCount = new TextField(“0”, 10); tfCount.setEditable(false); // read-only add(tfCount); // “super” Frame adds tfCount btnCount = new Button(“Count”); add(btnCount); // “super” Frame adds btnCount // Construct an anonymous instance of BtnCountListener (a named inner class). // btnCount adds this instance as a ActionListener. btnCount.addActionListener(new BtnCountListener()); setTitle(“AWT Counter”); setSize(250, 100); setVisible(true); } // The entry main method public static void main(String[] args) { new AWTCounter(); // Let the constructor do the job } /** * BtnCountListener is a “named inner class” used as ActionListener. * This inner class can access private variables of the outer class. */ private class BtnCountListener implements ActionListener { @Override public void actionPerformed(ActionEvent evt) { ++count; tfCount.setText(count + “”); } } }

Dissecting the Program
  • An inner class named

    BtnCountListener

    is used as the

    ActionListner

    .
  • An anonymous instance of the

    BtnCountListener

    inner class is constructed. The

    btnCount

    source object adds this instance as a listener, as follows:

    btnCount.addActionListener(new BtnCountListener());

  • The inner class can access the

    private

    variable

    tfCount

    and

    count

    of the outer class.
  • The inner class is compiled into

    AWTCount$BtnCountListener.class

    , in the format of

    OuterClassName$InnerClassName.class

    .
(Advanced) Using an Ordinary (Outer) Class as Listener

Try moving the

BtnCountListener

class outside, and define it as an ordinary class. You would need to pass a reference of the

AWTConnter

into the constructor of

BtnCountListener

, and use this reference to access variables

tfCount

and

count

, through

public

getters or granting them to

public

access.

// An ordinary outer class used as ActionListener for the Button public class BtnCountListener implements ActionListener { // private variable AWTCounter frame; // The constructor takes the AWT Frame as its argument public BtnCountListener(AWTCounter frame) { this.frame = frame; } // The event handler can access the private variables thru “frame” @Override public void actionPerformed(ActionEvent evt) { frame.count++; frame.tfCount.setText(frame.count + “”); } }

This code is messy! Inner class provides a much cleaner solution!

Example 8: An Anonymous Inner Class as Event Listener

Instead of using a named inner class (called

BtnCountListner

in the previous example), we shall use an inner class without a name, known as anonymous inner class as the

ActionListener

in this example.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42

import java.awt.*; import java.awt.event.*; // An AWT GUI program inherits from the top-level container java.awt.Frame public class AWTCounterAnonymousInnerClass extends Frame { // The event-handler actionPerformed() needs to access these private variables private TextField tfCount; private Button btnCount; private int count = 0; // Constructor to setup the GUI components and event handlers public AWTCounterAnonymousInnerClass () { setLayout(new FlowLayout()); // “super” Frame sets to FlowLayout add(new Label(“Counter”)); // An anonymous instance of Label tfCount = new TextField(“0”, 10); tfCount.setEditable(false); // read-only add(tfCount); // “super” Frame adds tfCount btnCount = new Button(“Count”); add(btnCount); // “super” Frame adds btnCount // Construct an anonymous instance of an anonymous class. // btnCount adds this instance as a ActionListener. btnCount.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { ++count; tfCount.setText(count + “”); } }); setTitle(“AWT Counter”); setSize(250, 100); setVisible(true); } // The entry main method public static void main(String[] args) { new AWTCounterAnonymousInnerClass(); // Let the constructor do the job } }

Dissecting the Program
  • The anonymous inner class is given a name generated by the compiler, and compiled into

    OuterClassName$n.class

    , whereis a running number of the inner classes of this outer class.
  • An anonymous instance of an anonymous inner class is constructed, and passed as the argument of the

    addActionListener()

    method as follows:

    btnCount.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { ++count; tfCount.setText(count + “”); } });

    The above codes is equivalent to and compiled as:

    private class N implements ActionListener { // N is a running number of the inner classes created @Override public void actionPerformed(ActionEvent evt) { ++count; tfCount.setText(count + “”); } } btnCount.addActionListener(new N()); // Or N n = new N() btnCount.addActionListener(n);

  • From JDK 8, you can write the event handler using “Lambda Expression” in a one-liner as follows:

    btnCount.addActionListener(evt -> tfCount.setText(++count + “”));

Properties of Anonymous Inner Class
  1. The anonymous inner class is define inside a method, instead of a member of the outer class (class member). It is local to the method and cannot be marked with access modifier (such as

    public

    ,

    private

    ) or

    static

    , just like any local variable of a method.
  2. An anonymous inner class must always extend a superclass or implement an interface. The keyword ”

    extends

    ” or ”

    implements

    ” is NOT required in its declaration. An anonymous inner class must implement all the abstract methods in the superclass or in the interface.
  3. An anonymous inner class always uses the default (no-arg) constructor from its superclass to create an instance. If an anonymous inner class implements an interface, it uses the

    java.lang.Object()

    .
  4. An anonymous inner class is compiled into a class named

    OuterClassName$n.class

    , whereis a running number of inner classes within the outer class.
  5. An instance of an anonymous inner class is constructed via this syntax:

    new SuperClassName/InterfaceName() { // extends superclass or implements interface // invoke the default no-arg constructor or Object[] // Implement abstract methods in superclass/interface // More methods if necessary …… }

    The created instance can be assigned to a variable or used as an argument of a method.

Example 9: An Anonymous Inner Class for Each Source

Let’s modify our

AWTCounter

example to include 3 buttons for counting up, counting down, and reset the count, respectively. We shall attach an anonymous inner class as the listener to each of buttons.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59

import java.awt.*; import java.awt.event.*; // An AWT GUI program inherits the top-level container java.awt.Frame public class AWTCounter3ButtonsAnonymousIC extends Frame { private TextField tfCount; private Button btnCountUp, btnCountDown, btnReset; private int count = 0; // Constructor to setup the GUI components and event handlers public AWTCounter3ButtonsAnonymousIC() { setLayout(new FlowLayout()); add(new Label(“Counter”)); // an anonymous instance of Label tfCount = new TextField(“0”, 10); tfCount.setEditable(false); // read-only add(tfCount); // “super” Frame adds tfCount btnCountUp = new Button(“Count Up”); add(btnCountUp); // Construct an anonymous instance of an anonymous inner class. // The source Button adds the anonymous instance as ActionEvent listener btnCountUp.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { ++count; tfCount.setText(count + “”); } }); btnCountDown = new Button(“Count Down”); add(btnCountDown); btnCountDown.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { count–; tfCount.setText(count + “”); } }); btnReset = new Button(“Reset”); add(btnReset); btnReset.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { count = 0; tfCount.setText(“0”); } }); setTitle(“AWT Counter”); setSize(400, 100); setVisible(true); } // The entry main method public static void main(String[] args) { new AWTCounter3ButtonsAnonymousIC(); // Let the constructor do the job } }

Dissecting the Program
  1. Each of the

    Button

    s uses one anonymous instance of an anonymous inner class as its

    ActionEvent

    listener.
Example 10: Using the Same Listener Instance for All the Buttons

If you use the same instance as the listener for all the 3 buttons, you need to determine which button has fired the event. It is because all the 3 buttons trigger the same event-handler method.

Using ActionEvent’s getActionCommand()

In the following example, we use the same instance of a “named” inner class as the listener for all the 3 buttons. The listener needs to determine which button has fired the event. This can be accomplished via the

ActionEvent

‘s

getActionCommonad()

method, which returns the button’s label.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62

import java.awt.*; import java.awt.event.*; // An AWT GUI program inherits the top-level container java.awt.Frame public class AWTCounter3Buttons1Listener extends Frame { private TextField tfCount; private Button btnCountUp, btnCountDown, btnReset; private int count = 0; // Constructor to setup the GUI components and event handlers public AWTCounter3Buttons1Listener () { setLayout(new FlowLayout()); add(new Label(“Counter”)); tfCount = new TextField(“0”, 10); tfCount.setEditable(false); add(tfCount); // Construct Buttons btnCountUp = new Button(“Count Up”); add(btnCountUp); btnCountDown = new Button(“Count Down”); add(btnCountDown); btnReset = new Button(“Reset”); add(btnReset); // Allocate an instance of the “named” inner class BtnListener. AllButtonsListener listener = new AllButtonsListener(); // Use the same listener instance for all the 3 Buttons. btnCountUp.addActionListener(listener); btnCountDown.addActionListener(listener); btnReset.addActionListener(listener); setTitle(“AWT Counter”); setSize(400, 100); setVisible(true); } // The entry main method public static void main(String[] args) { new AWTCounter3Buttons1Listener(); // Let the constructor do the job } /** * AllButtonsListener is an named inner class used as ActionEvent listener for all the Buttons. */ private class AllButtonsListener implements ActionListener { @Override public void actionPerformed(ActionEvent evt) { // Need to determine which button fired the event. // the getActionCommand() returns the Button’s label String btnLabel = evt.getActionCommand(); if (btnLabel.equals(“Count Up”)) { ++count; } else if (btnLabel.equals(“Count Down”)) { –count; } else { count = 0; } tfCount.setText(count + “”); } } }

Using getSource() of EventObject

Besides the

getActionCommand()

, which is only available for

ActionEvent

, you can use the

getSource()

method, which is available to all event objects, to retrieve a reference to the source object that has fired the event.

getSource()

returns a

java.lang.Object

. You may need to downcast it to the proper type of the source object. For example,

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62

import java.awt.*; import java.awt.event.*; public class AWTCounter3ButtonsGetSource extends Frame { private TextField tfCount; private Button btnCountUp, btnCountDown, btnReset; private int count = 0; // Constructor to setup the GUI components and event handlers public AWTCounter3ButtonsGetSource () { setLayout(new FlowLayout()); add(new Label(“Counter”)); tfCount = new TextField(“0”, 10); tfCount.setEditable(false); add(tfCount); // Construct Buttons btnCountUp = new Button(“Count Up”); add(btnCountUp); btnCountDown = new Button(“Count Down”); add(btnCountDown); btnReset = new Button(“Reset”); add(btnReset); // Allocate an instance of inner class BtnListener. AllButtonsListener listener = new AllButtonsListener(); // Use the same listener instance to all the 3 Buttons. btnCountUp.addActionListener(listener); btnCountDown.addActionListener(listener); btnReset.addActionListener(listener); setTitle(“AWT Counter”); setSize(400, 100); setVisible(true); } // The entry main method public static void main(String[] args) { new AWTCounter3ButtonsGetSource(); // Let the constructor do the job } /** * AllButtonsListener is a named inner class used as ActionEvent listener for all the Buttons. */ private class AllButtonsListener implements ActionListener { @Override public void actionPerformed(ActionEvent evt) { // Need to determine which button has fired the event. Button source = (Button)evt.getSource(); // Get a reference of the source that has fired the event. // getSource() returns a java.lang.Object. Downcast back to Button. if (source == btnCountUp) { ++count; } else if (source == btnCountDown) { –count; } else { count = 0; } tfCount.setText(count + “”); } } }

Event Listener’s Adapter Classes

Example 11: WindowAdapter for WindowListener
Using WindowListener Interface

Refer to the

WindowEventDemo

, a

WindowEvent

listener is required to implement the

WindowListener

interface, which declares 7

abstract

methods. Although we are only interested in

windowClosing()

, we need to provide an empty body to the other 6

abstract

methods in order to compile the program. This is tedious, e.g., we can rewrite the

WindowEventDemo

using an inner class implementing

ActionListener

as follows:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54

import java.awt.*; import java.awt.event.*; // An AWT GUI program inherits the top-level container java.awt.Frame public class WindowEventDemoWithInnerClass extends Frame { private TextField tfCount; private Button btnCount; private int count = 0; // Constructor to setup the GUI components and event handlers public WindowEventDemoWithInnerClass () { setLayout(new FlowLayout()); add(new Label(“Counter”)); tfCount = new TextField(“0”, 10); tfCount.setEditable(false); add(tfCount); btnCount = new Button(“Count”); add(btnCount); btnCount.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { ++count; tfCount.setText(count + “”); } }); // Allocate an anonymous instance of an anonymous inner class // that implements WindowListener. // “super” Frame adds this instance as WindowEvent listener. addWindowListener(new WindowListener() { @Override public void windowClosing(WindowEvent evt) { System.exit(0); // terminate the program } // Need to provide an empty body for compilation @Override public void windowOpened(WindowEvent evt) { } @Override public void windowClosed(WindowEvent evt) { } @Override public void windowIconified(WindowEvent evt) { } @Override public void windowDeiconified(WindowEvent evt) { } @Override public void windowActivated(WindowEvent evt) { } @Override public void windowDeactivated(WindowEvent evt) { } }); setTitle(“WindowEvent Demo”); setSize(250, 100); setVisible(true); } // The entry main method public static void main(String[] args) { new WindowEventDemoWithInnerClass(); // Let the constructor do the job } }

Using WindowAdapter Superclass

An adapter class called

WindowAdapter

is therefore provided, which implements the

WindowListener

interface and provides default implementations to all the 7

abstract

methods. You can then derive a subclass from

WindowAdapter

and override only methods of interest and leave the rest to their default implementation. For example,

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47

import java.awt.*; import java.awt.event.*; // An AWT GUI program inherits the top-level container java.awt.Frame public class WindowEventDemoAdapter extends Frame { private TextField tfCount; private Button btnCount; private int count = 0; // Constructor to setup the GUI components and event handlers public WindowEventDemoAdapter () { setLayout(new FlowLayout()); add(new Label(“Counter”)); tfCount = new TextField(“0”, 10); tfCount.setEditable(false); add(tfCount); btnCount = new Button(“Count”); add(btnCount); btnCount.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { ++count; tfCount.setText(count + “”); } }); // Allocate an anonymous instance of an anonymous inner class // that extends WindowAdapter. // “super” Frame adds the instance as WindowEvent listener. addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent evt) { System.exit(0); // Terminate the program } }); setTitle(“WindowEvent Demo”); setSize(250, 100); setVisible(true); } /** The entry main method */ public static void main(String[] args) { new WindowEventDemoAdapter(); // Let the constructor do the job } }

Clearly, the adapter greatly simplifies the codes.

Other Event-Listener Adapter Classes

Similarly, adapter classes such as

MouseAdapter

,

MouseMotionAdapter

,

KeyAdapter

,

FocusAdapter

are available for

MouseListener

,

MouseMotionListener

,

KeyListener

, and

FocusListener

, respectively.

There is no

ActionAdapter

for

ActionListener

, because there is only one

abstract

method (i.e.

actionPerformed()

) declared in the

ActionListener

interface. This method has to be overridden and there is no need for an adapter.

[SKIP] The Legacy “this” Listener

If you read some old books, you may find many examples that use ”

this

” object as the event listener.

For example,

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67

import java.awt.*; // Using AWT containers and components import java.awt.event.*; // Using AWT events classes and listener interfaces // An AWT GUI program inherits the top-level container java.awt.Frame public class ThisListenerDemo extends Frame implements ActionListener, WindowListener { // This class acts as listener for ActionEvent and WindowEvent // A Java class can extend only one superclass, but it can implement multiple interfaces. private TextField tfCount; // Declare a TextField component private Button btnCount; // Declare a Button component private int count = 0; // Counter’s value // Constructor to setup the GUI components and event handlers public ThisListenerDemo() { setLayout(new FlowLayout()); // “super” Frame sets to FlowLayout add(new Label(“Counter”)); // “super” Frame adds an anonymous Label tfCount = new TextField(“0”, 10); // Construct the TextField tfCount.setEditable(false); // read-only add(tfCount); // “super” Frame adds TextField btnCount = new Button(“Count”); // Construct the Button add(btnCount); // “super” Frame adds Button btnCount.addActionListener(this); // btnCount (source object) fires ActionEvent upon clicking // btnCount adds “this” object as an ActionEvent listener addWindowListener(this); // “super” Frame (source object) fires WindowEvent. // “super” Frame adds “this” object as a WindowEvent listener. setTitle(“WindowEvent Demo”); // “super” Frame sets title setSize(250, 100); // “super” Frame sets initial size setVisible(true); // “super” Frame shows } // The entry main() method public static void main(String[] args) { new ThisListenerDemo(); // Let the construct do the job } /* ActionEvent handler */ @Override public void actionPerformed(ActionEvent evt) { ++count; tfCount.setText(count + “”); } /* WindowEvent handlers */ // Called back upon clicking close-window button @Override public void windowClosing(WindowEvent evt) { System.exit(0); // Terminate the program } // Not Used, BUT need to provide an empty body to compile. @Override public void windowOpened(WindowEvent evt) { } @Override public void windowClosed(WindowEvent evt) { } // For Debugging @Override public void windowIconified(WindowEvent evt) { System.out.println(“Window Iconified”); } @Override public void windowDeiconified(WindowEvent evt) { System.out.println(“Window Deiconified”); } @Override public void windowActivated(WindowEvent evt) { System.out.println(“Window Activated”); } @Override public void windowDeactivated(WindowEvent evt) { System.out.println(“Window Deactivated”); } }

There is only ONE class in this code. But this code is much harder to understand and seldom used nowadays. Using inner class is a better solution.

Layout Managers and Panel

A container has a so-called layout manager to arrange its components. The layout managers provide a level of abstraction to map your user interface on all windowing systems, so that the layout can be platform-independent.

AWT provides the following layout managers (in package

java.awt

):

FlowLayout

,

GridLayout

,

BorderLayout

,

GridBagLayout

,

BoxLayout

,

CardLayout

, and others. Swing added more layout manager in package

javax.swing

, to be described later.

Container’s setLayout() method

A container has a

setLayout()

method to set its layout manager:

// java.awt.Container public void setLayout(LayoutManager mgr)

To set up the layout of a

Container

(such as

Frame

,

JFrame

,

Panel

, or

JPanel

), you have to:

  1. Construct an instance of the chosen layout object, via

    new

    and constructor, e.g.,

    new FlowLayout()

    )
  2. Invoke the

    setLayout()

    method of the

    Container

    , with the layout object created as the argument;
  3. Place the GUI components into the

    Container

    using the

    add()

    method in the correct order; or into the correct zones.

For example,

// Allocate a Panel (container) Panel pnl = new Panel(); // Allocate a new Layout object. The Panel container sets to this layout. pnl.setLayout(new FlowLayout()); // The Panel container adds components in the proper order. pnl.add(new JLabel(“One”)); pnl.add(new JLabel(“Two”)); pnl.add(new JLabel(“Three”)); ……

Container’s getLayout() method

You can get the current layout via

Container

‘s

getLayout()

method.

Panel pnl = new Panel(); System.out.println(pnl.getLayout()); // java.awt.FlowLayout[hgap=5,vgap=5,align=center]

Panel’s Initial Layout


Panel

(and Swing’s

JPanel

) provides a constructor to set its initial layout manager. It is because a primary function of

Panel

is to layout a group of component in a particular layout.

public void Panel(LayoutManager layout) // Construct a Panel in the given layout // By default, Panel (and JPanel) has FlowLayout // For example, create a Panel in BorderLayout Panel pnl = new Panel(new BorderLayout());

FlowLayout

In the

java.awt.FlowLayout

, components are arranged from left-to-right inside the container in the order that they are added (via method

aContainer.add(aComponent)

). When one row is filled, a new row will be started. The actual appearance depends on the width of the display window.

Constructors

public FlowLayout(); public FlowLayout(int alignment); public FlowLayout(int alignment, int hgap, int vgap); // alignment: FlowLayout.LEFT (or LEADING), FlowLayout.RIGHT (or TRAILING), or FlowLayout.CENTER // hgap, vgap: horizontal/vertical gap between the components // By default: hgap = 5, vgap = 5, alignment = FlowLayout.CENTER

Example

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36

import java.awt.*; import java.awt.event.*; // An AWT GUI program inherits the top-level container java.awt.Frame public class AWTFlowLayoutDemo extends Frame { private Button btn1, btn2, btn3, btn4, btn5, btn6; // Constructor to setup GUI components and event handlers public AWTFlowLayoutDemo () { setLayout(new FlowLayout()); // “super” Frame sets layout to FlowLayout, which arranges the components // from left-to-right, and flow from top-to-bottom. btn1 = new Button(“Button 1”); add(btn1); btn2 = new Button(“This is Button 2”); add(btn2); btn3 = new Button(“3”); add(btn3); btn4 = new Button(“Another Button 4”); add(btn4); btn5 = new Button(“Button 5”); add(btn5); btn6 = new Button(“One More Button 6”); add(btn6); setTitle(“FlowLayout Demo”); // “super” Frame sets title setSize(280, 150); // “super” Frame sets initial size setVisible(true); // “super” Frame shows } // The entry main() method public static void main(String[] args) { new AWTFlowLayoutDemo(); // Let the constructor do the job } }

GridLayout

In

java.awt.GridLayout

, components are arranged in a grid (matrix) of rows and columns inside the

Container

. Components are added in a left-to-right, top-to-bottom manner in the order they are added (via method

aContainer.add(aComponent)

).

Constructors

public GridLayout(int rows, int columns); public GridLayout(int rows, int columns, int hgap, int vgap); // By default: rows = 1, cols = 0, hgap = 0, vgap = 0

Example

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36

import java.awt.*; import java.awt.event.*; // An AWT GUI program inherits the top-level container java.awt.Frame public class AWTGridLayoutDemo extends Frame { private Button btn1, btn2, btn3, btn4, btn5, btn6; // Constructor to setup GUI components and event handlers public AWTGridLayoutDemo () { setLayout(new GridLayout(3, 2, 3, 3)); // “super” Frame sets layout to 3×2 GridLayout, horizontal and vertical gaps of 3 pixels // The components are added from left-to-right, top-to-bottom btn1 = new Button(“Button 1”); add(btn1); btn2 = new Button(“This is Button 2”); add(btn2); btn3 = new Button(“3”); add(btn3); btn4 = new Button(“Another Button 4”); add(btn4); btn5 = new Button(“Button 5”); add(btn5); btn6 = new Button(“One More Button 6”); add(btn6); setTitle(“GridLayout Demo”); // “super” Frame sets title setSize(280, 150); // “super” Frame sets initial size setVisible(true); // “super” Frame shows } // The entry main() method public static void main(String[] args) { new AWTGridLayoutDemo(); // Let the constructor do the job } }

BorderLayout

In

java.awt.BorderLayout

, the container is divided into 5 zones:

EAST

,

WEST

,

SOUTH

,

NORTH

, and

CENTER

. Components are added using method

aContainer.add(aComponent, zone)

, where

zone

is either

BorderLayout.NORTH

(or

PAGE_START

),

BorderLayout.SOUTH

(or

PAGE_END

),

BorderLayout.WEST

(or

LINE_START

),

BorderLayout.EAST

(or

LINE_END

), or

BorderLayout.CENTER

.

You need not place components to all the 5 zones. The

NORTH

and

SOUTH

components may be stretched horizontally; the

EAST

and

WEST

components may be stretched vertically; the

CENTER

component may stretch both horizontally and vertically to fill any space left over.

Constructors

public BorderLayout(); public BorderLayout(int hgap, int vgap); // By default hgap = 0, vgap = 0

Example

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35

import java.awt.*; import java.awt.event.*; // An AWT GUI program inherits the top-level container java.awt.Frame public class AWTBorderLayoutDemo extends Frame { private Button btnNorth, btnSouth, btnCenter, btnEast, btnWest; // Constructor to setup GUI components and event handlers public AWTBorderLayoutDemo () { setLayout(new BorderLayout(3, 3)); // “super” Frame sets layout to BorderLayout, // horizontal and vertical gaps of 3 pixels // The components are added to the specified zone btnNorth = new Button(“NORTH”); add(btnNorth, BorderLayout.NORTH); btnSouth = new Button(“SOUTH”); add(btnSouth, BorderLayout.SOUTH); btnCenter = new Button(“CENTER”); add(btnCenter, BorderLayout.CENTER); btnEast = new Button(“EAST”); add(btnEast, BorderLayout.EAST); btnWest = new Button(“WEST”); add(btnWest, BorderLayout.WEST); setTitle(“BorderLayout Demo”); // “super” Frame sets title setSize(280, 150); // “super” Frame sets initial size setVisible(true); // “super” Frame shows } // The entry main() method public static void main(String[] args) { new AWTBorderLayoutDemo(); // Let the constructor do the job } }

Using Panels as Sub-Container to Organize Components

An AWT

Panel

is a rectangular pane, which can be used as sub-container to organized a group of related components in a specific layout (e.g.,

FlowLayout

,

BorderLayout

).

Panel

s are secondary containers, which shall be added into a top-level container (such as

Frame

), or another

Panel

.

For example, the following figure shows a

Frame

in

BorderLayout

containing two

Panels



panelResult

in

FlowLayout

and

panelButtons

in

GridLayout

.

panelResult

is added to the

NORTH

, and

panelButtons

is added to the

CENTER

.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59

import java.awt.*; import java.awt.event.*; // An AWT GUI program inherits the top-level container java.awt.Frame public class AWTPanelDemo extends Frame { private Button[] btnNumbers; // Array of 10 numeric Buttons private Button btnHash, btnStar; private TextField tfDisplay; // Constructor to setup GUI components and event handlers public AWTPanelDemo () { // Set up display panel Panel panelDisplay = new Panel(new FlowLayout()); tfDisplay = new TextField(“0”, 20); panelDisplay.add(tfDisplay); // Set up button panel Panel panelButtons = new Panel(new GridLayout(4, 3)); btnNumbers = new Button[10]; // Construct an array of 10 numeric Buttons btnNumbers[1] = new Button(“1”); // Construct Button “1” panelButtons.add(btnNumbers[1]); // The Panel adds this Button btnNumbers[2] = new Button(“2”); panelButtons.add(btnNumbers[2]); btnNumbers[3] = new Button(“3”); panelButtons.add(btnNumbers[3]); btnNumbers[4] = new Button(“4”); panelButtons.add(btnNumbers[4]); btnNumbers[5] = new Button(“5”); panelButtons.add(btnNumbers[5]); btnNumbers[6] = new Button(“6”); panelButtons.add(btnNumbers[6]); btnNumbers[7] = new Button(“7”); panelButtons.add(btnNumbers[7]); btnNumbers[8] = new Button(“8”); panelButtons.add(btnNumbers[8]); btnNumbers[9] = new Button(“9”); panelButtons.add(btnNumbers[9]); // You should use a loop for the above statements!!! btnStar = new Button(“*”); panelButtons.add(btnStar); btnNumbers[0] = new Button(“0”); panelButtons.add(btnNumbers[0]); btnHash = new Button(“#”); panelButtons.add(btnHash); setLayout(new BorderLayout()); // “super” Frame sets to BorderLayout add(panelDisplay, BorderLayout.NORTH); add(panelButtons, BorderLayout.CENTER); setTitle(“BorderLayout Demo”); // “super” Frame sets title setSize(200, 200); // “super” Frame sets initial size setVisible(true); // “super” Frame shows } // The entry main() method public static void main(String[] args) { new AWTPanelDemo(); // Let the constructor do the job } }

GridBagLayout

Reference: Read “How to Use GridBagLayout” @ https://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html.

Example 1

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64

import java.awt.*; import javax.swing.*; @SuppressWarnings(“serial”) public class GridBagLayoutExample extends JPanel { JButton button1, button2, button3, button4, button5; // Constructor public GridBagLayoutExample() { super.setLayout(new GridBagLayout()); // super JPanel GridBagConstraints gbc = new GridBagConstraints(); // The following constraints are applicable to all components // gbc.fill = GridBagConstraints.HORIZONTAL; // Define constraints for individual components button1 = new JButton(“B1”); gbc.gridx = 0; // column 0 (first column) gbc.gridy = 0; // row 0 (first row) // gbc.weightx = 0.5; // weight for distributing extra x-spaces super.add(button1, gbc); // add and apply constraints button2 = new JButton(“B2”); gbc.gridx = 1; // column 1 gbc.gridy = 0; // row 0 // gbc.weightx = 1.0; super.add(button2, gbc); button3 = new JButton(“B3”); gbc.gridx = 2; // column 2 gbc.gridy = 0; // row 0 // gbc.weightx = 0.5; super.add(button3, gbc); button4 = new JButton(“Long-Named Button 4”); gbc.gridx = 0; // column 0 gbc.gridy = 1; // row 1 (second row) gbc.gridwidth = 3; // span 3 columns gbc.ipady = 40; // internal padding-y super.add(button4, gbc); button5 = new JButton(“5”); gbc.gridx = 1; // second column gbc.gridy = 2; // third row gbc.gridwidth = 2; // span 2 columns gbc.ipady = 0; // reset to default gbc.anchor = GridBagConstraints.PAGE_END; // align at bottom of space gbc.insets = new Insets(10, 0, 0, 0); // top margin // gbc.weighty = 1.0; // request any extra vertical space super.add(button5, gbc); } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { JFrame frame = new JFrame(“GridBagLayoutDemo”); frame.setContentPane(new GridBagLayoutExample()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300,300); frame.setVisible(true); } }); } }

Run the program, the output is in (a), where all components have their natural width and height, placed in center (

anchor=CENTER

) with extra x and y spaces at the 4 margins. The

ipady

increases the internal y-padding for button-4 (spans 3 columns). Button 5 (spans second and third columns) has top margin specified by

insets

, and anchor at the bottom-right corner (

anchor=PAGE_END

).

Uncomment the

gbc.fill = GridBagConstraints.HORIZONTAL

(line 14). The output is in (b), where ALL components fill horizontally with equal column width.

Uncomment all

weightx

(lines 20, 26, 32). The output is in (c). The extra x spaces are distributed according to the

weightx

of (0.5, 1.0, 0.5).

Uncomment the

weighty

(line 49). The output is in (d). The extra y spaces are given to row 3, as row 1 and 2 have

weighty

of 0 and non-participating in the distribution of extra y-spaces.

BoxLayout

BoxLayout arrange components in a single row or column. It respects components’ requests on the minimum sizes.

[TODO] Example and diagram

Swing

Introduction

Swing is part of the so-called “Java Foundation Classes (JFC)” (have you heard of MFC?), which was introduced in 1997 after the release of JDK 1.1. JFC was subsequently included as an integral part of JDK since JDK 1.2. JFC consists of:

  • Swing API: for advanced graphical programming.
  • Accessibility API: provides assistive technology for the disabled.
  • Java 2D API: for high quality 2D graphics and images.
  • Pluggable look and feel supports.
  • Drag-and-drop support between Java and native applications.

The goal of Java GUI programming is to allow the programmer to build GUI that looks good on ALL platforms. JDK 1.0’s AWT was awkward and non-object-oriented (using many

event.getSource()

). JDK 1.1’s AWT introduced event-delegation (event-driven) model, much clearer and object-oriented. JDK 1.1 also introduced inner class and JavaBeans – a component programming model for visual programming environment (similar to Visual Basic).

Swing appeared after JDK 1.1. It was introduced into JDK 1.1 as part of an add-on JFC (Java Foundation Classes). Swing is a rich set of easy-to-use, easy-to-understand JavaBean GUI components that can be dragged and dropped as “GUI builders” in visual programming environment. Swing is now an integral part of Java since JDK 1.2.

Swing’s Features

Swing is huge (consists of 18 packages of 737 classes as in JDK 1.8) and has great depth. Compared with AWT, Swing provides a huge and comprehensive collection of reusable GUI components, as shown in the Figure below (extracted form Swing Tutorial).

The main features of Swing are (extracted from the Swing website):

  1. Swing is written in pure Java (except a few classes) and therefore is 100% portable.
  2. Swing components are lightweight. The AWT components are heavyweight (in terms of system resource utilization). Each AWT component has its own opaque native display, and always displays on top of the lightweight components. AWT components rely heavily on the underlying windowing subsystem of the native operating system. For example, an AWT button ties to an actual button in the underlying native windowing subsystem, and relies on the native windowing subsystem for their rendering and processing. Swing components (

    JComponent

    s) are written in Java. They are generally not “weight-down” by complex GUI considerations imposed by the underlying windowing subsystem.
  3. Swing components support pluggable look-and-feel. You can choose between Java look-and-feel and the look-and-feel of the underlying OS (e.g., Windows, UNIX or macOS). If the later is chosen, a Swing button runs on the Windows looks like a Windows’ button and feels like a Window’s button. Similarly, a Swing button runs on the UNIX looks like a UNIX’s button and feels like a UNIX’s button.
  4. Swing supports mouse-less operation, i.e., it can operate entirely using keyboard.
  5. Swing components support “tool-tips”.
  6. Swing components are JavaBeans – a Component-based Model used in Visual Programming (like Visual Basic). You can drag-and-drop a Swing component into a “design form” using a “GUI builder” and double-click to attach an event handler.
  7. Swing application uses AWT event-handling classes (in package

    java.awt.event

    ). Swing added some new classes in package

    javax.swing.event

    , but they are not frequently used.
  8. Swing application uses AWT’s layout manager (such as

    FlowLayout

    and

    BorderLayout

    in package

    java.awt

    ). It added new layout managers, such as

    Springs

    ,

    Struts

    , and

    BoxLayout

    (in package

    javax.swing

    ).
  9. Swing implements double-buffering and automatic repaint batching for smoother screen repaint.
  10. Swing introduces

    JLayeredPane

    and

    JInternalFrame

    for creating Multiple Document Interface (MDI) applications.
  11. Swing supports floating toolbars (in

    JToolBar

    ), splitter control, “undo”.
  12. Others – check the Swing website.
Using Swing API

If you understood the AWT programming (in particular, container/component and event-handling), switching over to Swing (or any other Graphics packages) is straight-forward.

Swing’s Components

Compared with the AWT component classes (in package

java.awt

), Swing component classes (in package

javax.swing

) begin with a prefix

"J"

, e.g.,

JButton

,

JTextField

,

JLabel

,

JPanel

,

JFrame

, or

JApplet

.

The above figure shows the class hierarchy of the swing GUI classes. Similar to AWT, there are two groups of classes: containers and components. A container is used to hold components. A container can also hold containers because it is a (subclass of) component.

As a rule, do not mix heavyweight AWT components and lightweight Swing components in the same program, as the heavyweight components will always be painted on top of the lightweight components.

Swing’s Top-Level and Secondary Containers

Just like AWT application, a Swing application requires a top-level container. There are three top-level containers in Swing:


  1. JFrame

    : used for the application’s main window (with an icon, a title, minimize/maximize/close buttons, an optional menu-bar, and a content-pane), as illustrated.

  2. JDialog

    : used for secondary pop-up window (with a title, a close button, and a content-pane).

  3. JApplet

    : used for the applet’s display-area (content-pane) inside a browser’s window.

Similarly to AWT, there are secondary containers (such as

JPanel

) which can be used to group and layout relevant components.

The Content-Pane of Swing’s Top-Level Container

However, unlike AWT, the

JComponents

shall not be added onto the top-level container (e.g.,

JFrame

,

JApplet

) directly because they are lightweight components. The

JComponents

must be added onto the so-called content-pane of the top-level container. Content-pane is in fact a

java.awt.Container

that can be used to group and layout components.

You could:

  1. get the content-pane via

    getContentPane()

    from a top-level container, and add components onto it. For example,

    public class SwingDemo extends JFrame { // Constructor public SwingDemo() { // Get the content-pane of this JFrame, which is a java.awt.Container // All operations, such as setLayout() and add() operate on the content-pane Container cp = getContentPane(); cp.setLayout(new FlowLayout()); cp.add(new JLabel(“Hello, world!”)); cp.add(new JButton(“Button”)); …… } ……. }

  2. set the content-pane to a

    JPanel

    (the main panel created in your application which holds all your GUI components) via

    JFrame

    ‘s

    setContentPane()

    .

    public class SwingDemo extends JFrame { // Constructor public SwingDemo() { // The “main” JPanel holds all the GUI components JPanel mainPanel = new JPanel(new FlowLayout()); mainPanel.add(new JLabel(“Hello, world!”)); mainPanel.add(new JButton(“Button”)); // Set the content-pane of this JFrame to the main JPanel setContentPane(mainPanel); …… } ……. }

Notes: If a component is added directly into a

JFrame

, it is added into the content-pane of

JFrame

instead, i.e.,

// Suppose that “this” is a JFrame add(new JLabel(“add to JFrame directly”)); // is executed as getContentPane().add(new JLabel(“add to JFrame directly”));

Event-Handling in Swing

Swing uses the AWT event-handling classes (in package

java.awt.event

). Swing introduces a few new event-handling classes (in package

javax.swing.event

) but they are not frequently used.

Writing Swing Applications

In summary, to write a Swing application, you have:

  1. Use the Swing components with prefix

    "J"

    in package

    javax.swing

    , e.g.,

    JFrame

    ,

    JButton

    ,

    JTextField

    ,

    JLabel

    , etc.
  2. A top-level container (typically

    JFrame

    ) is needed. The

    JComponents

    should not be added directly onto the top-level container. They shall be added onto the content-pane of the top-level container. You can retrieve a reference to the content-pane by invoking method

    getContentPane()

    from the top-level container.
  3. Swing applications uses AWT event-handling classes, e.g.,

    ActionEvent/ActionListener

    ,

    MouseEvent/MouseListener

    , etc.
  4. Run the constructor in the Event Dispatcher Thread (instead of Main thread) for thread safety, as shown in the following program template.
Swing Program Template

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45

import java.awt.*; // Using AWT layouts import java.awt.event.*; // Using AWT event classes and listener interfaces import javax.swing.*; // Using Swing components and containers // A Swing GUI application inherits from top-level container javax.swing.JFrame public class SwingTemplate extends JFrame { // Private instance variables // …… // Constructor to setup the GUI components and event handlers public SwingTemplate() { // Retrieve the top-level content-pane from JFrame Container cp = getContentPane(); // Content-pane sets layout cp.setLayout(new ….Layout()); // Allocate the GUI components // ….. // Content-pane adds components cp.add(….); // Source object adds listener // ….. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Exit the program when the close-window button clicked setTitle(“……”); // “super” JFrame sets title setSize(300, 150); // “super” JFrame sets initial size setVisible(true); // “super” JFrame shows } // The entry main() method public static void main(String[] args) { // Run GUI codes in Event-Dispatching thread for thread-safety SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new SwingTemplate(); // Let the constructor do the job } }); } }

I will explain this template in the following Swing example.

Swing Example 1: SwingCounter

Let’s convert the earlier AWT application example into Swing. Compare the two source files and note the changes (which are highlighted). The display is shown below. Note the differences in look and feel between the AWT GUI components and Swing’s.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52

import java.awt.*; // Using AWT layouts import java.awt.event.*; // Using AWT event classes and listener interfaces import javax.swing.*; // Using Swing components and containers // A Swing GUI application inherits from top-level container javax.swing.JFrame public class SwingCounter extends JFrame { // JFrame instead of Frame private JTextField tfCount; // Use Swing’s JTextField instead of AWT’s TextField private JButton btnCount; // Using Swing’s JButton instead of AWT’s Button private int count = 0; // Constructor to setup the GUI components and event handlers public SwingCounter() { // Retrieve the content-pane of the top-level container JFrame // All operations done on the content-pane Container cp = getContentPane(); cp.setLayout(new FlowLayout()); // The content-pane sets its layout cp.add(new JLabel(“Counter”)); tfCount = new JTextField(“0”); tfCount.setEditable(false); cp.add(tfCount); btnCount = new JButton(“Count”); cp.add(btnCount); // Allocate an anonymous instance of an anonymous inner class that // implements ActionListener as ActionEvent listener btnCount.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { ++count; tfCount.setText(count + “”); } }); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Exit program if close-window button clicked setTitle(“Swing Counter”); // “super” JFrame sets title setSize(300, 100); // “super” JFrame sets initial size setVisible(true); // “super” JFrame shows } // The entry main() method public static void main(String[] args) { // Run the GUI construction in the Event-Dispatching thread for thread-safety SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new SwingCounter(); // Let the constructor do the job } }); } }

JFrame’s Content-Pane

The

JFrams

‘s method

getContentPane()

returns the content-pane (which is a

java.awt.Containter

) of the

JFrame

. You can then set its layout (the default layout is

BorderLayout

), and add components into it. For example,

Container cp = getContentPane(); // Get the content-pane of this JFrame cp.setLayout(new FlowLayout()); // content-pane sets to FlowLayout cp.add(new JLabel(“Counter”)); // content-pane adds a JLabel component …… cp.add(tfCount); // content-pane adds a JTextField component …… cp.add(btnCount); // content-pane adds a JButton component

You can also use the

JFrame

‘s

setContentPane()

method to directly set the content-pane to a

JPanel

(or a

JComponent

). For example,

JPanel displayPanel = new JPanel(); setContentPane(displayPanel); // “this” JFrame sets its content-pane to a JPanel directly ….. // The above is different from: getContentPane().add(displayPanel); // Add a JPanel into the content-pane. Appearance depends on the JFrame’s layout.

JFrame’s setDefaultCloseOperation()

Instead of writing a

WindowEvent

listener with a

windowClosing()

handler to process the “close-window” button,

JFrame

provides a method called

setDefaultCloseOperation()

to sets the default operation when the user initiates a “close” on this frame. Typically, we choose the option

JFrame.EXIT_ON_CLOSE

, which terminates the application via a

System.exit()

.

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Running the GUI Construction Codes on the Event-Dispatching Thread

In the previous examples, we invoke the constructor directly in the entry

main()

method to setup the GUI components. For example,

// The entry main method public static void main(String[] args) { // Invoke the constructor (by allocating an instance) to setup the GUI new SwingCounter(); }

The constructor will be executed in the so-called “Main-Program” thread. This may cause multi-threading issues (such as unresponsive user-interface and deadlock).

It is recommended to execute the GUI setup codes in the so-called “Event-Dispatching” thread, instead of “Main-Program” thread, for thread-safe operations. Event-dispatching thread, which processes events, should be used when the codes updates the GUI.

To run the constructor on the event-dispatching thread, invoke

static

method

SwingUtilities.invokeLater()

to asynchronously queue the constructor on the event-dispatching thread. The codes will be run after all pending events have been processed. For example,

public static void main(String[] args) { // Run the GUI codes in the Event-dispatching thread for thread-safety SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new SwingCounter(); // Let the constructor do the job } }); }

Note:

javax.swing.SwingUtilities.invokeLater()

is a cover for

java.awt.EventQueue.invokeLater()

(which is used in the NetBeans’ Visual GUI Builder).

At times, for example in game programming, the constructor or the

main()

may contains non-GUI codes. Hence, it is a common practice to create a dedicated method called

initComponents()

(used in NetBeans visual GUI builder) or

createAndShowGUI()

(used in Swing tutorial) to handle all the GUI codes (and another method called

initGame()

to handle initialization of the game’s objects). This GUI init method shall be run in the event-dispatching thread.

Warning Message “The serialization class does not declare a static final serialVersionUID field of type long”

This warning message is triggered because

java.awt.Frame

(via its superclass

java.awt.Component

) implements the

java.io.Serializable

interface. This interface enables the object to be written out to an output stream serially (via method

writeObject()

); and read back into the program (via method

readObject()

). The serialization runtime uses a number (called

serialVersionUID

) to ensure that the object read into the program is compatible with the class definition, and not belonging to another version.

You have these options:

  1. Simply ignore this warning message. If a

    serializable

    class does not explicitly declare a

    serialVersionUID

    , then the serialization runtime will calculate a default

    serialVersionUID

    value for that class based on various aspects of the class.
  2. Add a

    serialVersionUID

    (Recommended), e.g.

    private static final long serialVersionUID = 1L; // version 1

  3. Suppress this particular warning via annotation

    @SuppressWarmomgs

    (in package

    java.lang

    ) (JDK 1.5):

    @SuppressWarnings(“serial”) public class MyFrame extends JFrame { …… }

Swing Example 2: SwingAccumulator

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54

import java.awt.*; // Using layouts import java.awt.event.*; // Using AWT event classes and listener interfaces import javax.swing.*; // Using Swing components and containers // A Swing GUI application inherits the top-level container javax.swing.JFrame public class SwingAccumulator extends JFrame { private JTextField tfInput, tfOutput; private int sum = 0; // accumulated sum, init to 0 // Constructor to setup the GUI components and event handlers public SwingAccumulator() { // Retrieve the content-pane of the top-level container JFrame // All operations done on the content-pane Container cp = getContentPane(); cp.setLayout(new GridLayout(2, 2, 5, 5)); // The content-pane sets its layout cp.add(new JLabel(“Enter an Integer: “)); tfInput = new JTextField(10); cp.add(tfInput); cp.add(new JLabel(“The Accumulated Sum is: “)); tfOutput = new JTextField(10); tfOutput.setEditable(false); // read-only cp.add(tfOutput); // Allocate an anonymous instance of an anonymous inner class that // implements ActionListener as ActionEvent listener tfInput.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent evt) { // Get the String entered into the input TextField, convert to int int numberIn = Integer.parseInt(tfInput.getText()); sum += numberIn; // accumulate numbers entered into sum tfInput.setText(“”); // clear input TextField tfOutput.setText(sum + “”); // display sum on the output TextField } }); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Exit program if close-window button clicked setTitle(“Swing Accumulator”); // “super” Frame sets title setSize(350, 120); // “super” Frame sets initial size setVisible(true); // “super” Frame shows } // The entry main() method public static void main(String[] args) { // Run the GUI construction in the Event-Dispatching thread for thread-safety SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new SwingAccumulator(); // Let the constructor do the job } }); } }

Using Visual GUI Builder – NetBeans/Eclipse

If you have a complicated layout for your GUI application, you should use a GUI Builder, such as NetBeans or Eclipse to layout your GUI components in a drag-and-drop manner, similar to the popular visual languages such as Visual Basic.

NetBeans

For using NetBeans GUI Builder, read my “Writing Java GUI (AWT/Swing) Application in NetBeans”; or Swing Tutorial’s “Learning Swing with the NetBeans IDE”.

Eclipse

For using Eclipse GUI Builder, read “Writing Swing Applications using Eclipse GUI Builder”.

LINK TO JAVA REFERENCES & RESOURCES

MORE REFERENCES & RESOURCES

  1. “Creating a GUI With JFC/Swing” (aka “The Swing Tutorial”) @ http://docs.oracle.com/javase/tutorial/uiswing/.
  2. JFC Demo (under JDK demo ”

    jfc

    ” directory).
  3. Java2D Tutorial @ http://docs.oracle.com/javase/tutorial/2d/index.html.
  4. JOGL (Java Binding on OpenGL)
  5. Java3D

Introduction to Java Swing

Swing is a Java Foundation Classes [JFC] library and an extension of the Abstract Window Toolkit [AWT]. Java Swing offers much-improved functionality over AWT, new components, expanded components features, and excellent event handling with drag-and-drop support.

Introduction of Java Swing

Swing has about four times the number of User Interface [UI] components as AWT and is part of the standard Java distribution. By today’s application GUI requirements, AWT is a limited implementation, not quite capable of providing the components required for developing complex GUIs required in modern commercial applications. The AWT component set has quite a few bugs and does take up a lot of system resources when compared to equivalent Swing resources. Netscape introduced its Internet Foundation Classes [IFC] library for use with Java. Its Classes became very popular with programmers creating GUI’s for commercial applications.

  • Swing is a Set of API (API- Set of Classes and Interfaces)
  • Swing is Provided to Design Graphical User Interfaces
  • Swing is an Extension library to the AWT (Abstract Window Toolkit) 5:00 – 5:30 pm
  • Includes New and improved Components that have been enhancing the looks and Functionality of GUIs’
  • Swing can be used to build (Develop) The Standalone swing GUI Apps as Servlets and Applets
  • It Employs model/view design architecture.
  • Swing is more portable and more flexible than AWT, the Swing is built on top of the AWT.
  • Swing is Entirely written in Java.
  • Java Swing Components are Platform-independent, and The Swing Components are lightweight.
  • Swing Supports a Pluggable look and feel and Swing provides more powerful components.
  • such as tables, lists, Scrollpanes, Colourchooser, tabbed pane, etc.
  • Further Swing Follows MVC.
Create Your First Java Project using Visual Studio Code 2021 and Java JDK 17
Create Your First Java Project using Visual Studio Code 2021 and Java JDK 17

Java


import


java.awt.*;


class


button {


button()


Frame f =


new


Frame();


Button b1 =


new


Button(


"OK"


);


b1.setBounds(


100


50


50


50


);


f.add(b1);


Button b2 =


new


Button(


"SUBMIT"


);


b2.setBounds(


100


101


50


50


);


f.add(b2);


Button b3 =


new


Button(


"CANCEL"


);


b3.setBounds(


100


150


80


50


);


f.add(b3);


f.setSize(


500


500


);


f.setLayout(


null


);


f.setVisible(


true


);


public


static


void


main(String a[]) {


new


button(); }

Output:
Example 3: Program to Add Checkbox in the Frame

How to Make a GUI in Java with Example

Now in this Java GUI Tutorial, let’s understand how to create a GUI in Java with Swings in Java examples.

Step 1) Copy code into an editorIn first step Copy the following code into an editor.

import javax.swing.*; class gui{ public static void main(String args[]){ JFrame frame = new JFrame(“My First GUI”); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300,300); JButton button = new JButton(“Press”); frame.getContentPane().add(button); // Adds Button to content pane of frame frame.setVisible(true); } }

Step 2) Run the codeNext step, Save, Compile, and Run the code

Step 3) Copy following code into an editorNow let’s Add a Button to our frame. Copy following code into an editor from given Java UI Example

import javax.swing.*; class gui{ public static void main(String args[]){ JFrame frame = new JFrame(“My First GUI”); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300,300); JButton button1 = new JButton(“Press”); frame.getContentPane().add(button1); frame.setVisible(true); } }

Step 4) Execute the code

Next, Execute the code. You will get a big button.

Step 5) Add two buttonsHow about adding two buttons? Copy the following code into an editor.

import javax.swing.*; class gui{ public static void main(String args[]){ JFrame frame = new JFrame(“My First GUI”); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300,300); JButton button1 = new JButton(“Button 1”); JButton button2 = new JButton(“Button 2”); frame.getContentPane().add(button1); frame.getContentPane().add(button2); frame.setVisible(true); } }

Step 6) Save & Run the programNext, Save, Compile, and Run the program.

Step 7) Check outputUnexpected output =? Buttons are getting overlapped.

Learn Java in 14 Minutes (seriously)
Learn Java in 14 Minutes (seriously)

Swing mnemonics

Mnemonics are shortcut keys that activate a component that supports mnemonics. For instance, they can be used with labels, buttons, or menu items.

package com.zetcode; import javax.swing.GroupLayout; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFrame; import java.awt.EventQueue; import java.awt.event.KeyEvent; public class MnemonicEx extends JFrame { public MnemonicEx() { initUI(); } private void initUI() { var btn = new JButton(“Button”); btn.addActionListener((event) -> System.out.println(“Button pressed”)); btn.setMnemonic(KeyEvent.VK_B); createLayout(btn); setTitle(“Mnemonics”); setLocationRelativeTo(null); setDefaultCloseOperation(EXIT_ON_CLOSE); } private void createLayout(JComponent… arg) { var pane = getContentPane(); var gl = new GroupLayout(pane); pane.setLayout(gl); gl.setAutoCreateContainerGaps(true); gl.setHorizontalGroup(gl.createSequentialGroup() .addComponent(arg[0]) .addGap(200) ); gl.setVerticalGroup(gl.createParallelGroup() .addComponent(arg[0]) .addGap(200) ); pack(); } public static void main(String[] args) { EventQueue.invokeLater(() -> { var ex = new MnemonicEx(); ex.setVisible(true); }); } }

We have a button with an action listener. We set a mnemonic for this button. It can be activated with the Alt+B keyboard shortcut.

btn.setMnemonic(KeyEvent.VK_B);

The

setMnemonic()

method sets a keyboard mnemonic for
the button. The mnemonic key is specified with a virtual keycode
from the

KeyEvent

class. The mnemonic is combined with the
look and feel’s mouseless modifier (usually Alt).

At this moment, there are three ways to activate the button: a left mouse button click, the Alt+B shortcut, and the Space key (provided the button has the focus). The Space key binding was automatically created by Swing. (Under Metal look and feel, the focus is visually represented by a small rectangle around the button’s label.)

JFrame icon

In the following example, we are going to display an icon on a frame. It is shown in the left part of the titlebar.

package com.zetcode; import java.awt.EventQueue; import javax.swing.ImageIcon; import javax.swing.JFrame; public class FrameIconEx extends JFrame { public FrameIconEx() { initUI(); } private void initUI() { var webIcon = new ImageIcon(“src/resources/web.png”); setIconImage(webIcon.getImage()); setTitle(“Icon”); setSize(300, 200); setLocationRelativeTo(null); setDefaultCloseOperation(EXIT_ON_CLOSE); } public static void main(String[] args) { EventQueue.invokeLater(() -> { var ex = new FrameIconEx(); ex.setVisible(true); }); } }


ImageIcon

is used to create the icon.
The

web.png

is a small, 22×22 px image file.

var webIcon = new ImageIcon(“src/resources/web.png”);

We create an

ImageIcon

from a PNG file, which
is located in the project root directory.

setIconImage(webIcon.getImage());

The

setIconImage()

sets the image to be displayed as
the icon for this window. The

getImage()

returns the
icon’s

Image

.

Hello World in different programming languages #programming #memes
Hello World in different programming languages #programming #memes

Display the Current Date and Time

The “Date” class is used to read the date and time values. Create a Java file with the following code that displays the current date and time in the dialog box:

import java.text.*;

import java.util.*;

class SwingExample8 {

public static void main(String[] args) {

//Declare frame object

JFrame win = new JFrame();

//Set the title

win.setTitle(“Java Swing Example-8”);

//Set the window size

win.setSize(350, 150);

//Disable the resize option

win.setResizable(false);

//Set window position

win.setLocationRelativeTo(null);

//Define a format object

SimpleDateFormat formatDate = new SimpleDateFormat(“dd MMMM yyyy HH:mm:ss z”);

//Declare the date object

Date dt = new Date();

//Create a label object, set the position, and add to the frame

JLabel lbl = new JLabel(formatDate.format(dt), JLabel.CENTER);

lbl.setBounds(80,20,100,20);

win.add(lbl);

//Make the window visible

win.setVisible(true);

Output:

The following dialog box will appear after executing the Java class file:

Features Of Swing Class

  • Pluggable look and feel.
  • Uses MVC architecture.
  • Lightweight Components
  • Platform Independent
  • Advanced features such as JTable, JTabbedPane, JScollPane, etc.
  • Java is a platform-independent language and runs on any client machine, the GUI look and feel, owned and delivered by a platform-specific O/S, simply does not affect an application’s GUI constructed using Swing components.
  • Lightweight Components: Starting with the JDK 1.1, its AWT-supported lightweight component development. For a component to qualify as lightweight, it must not depend on any non-Java [O/s based) system classes. Swing components have their own view supported by Java’s look and feel classes.
  • Pluggable Look and Feel: This feature enable the user to switch the look and feel of Swing components without restarting an application. The Swing library supports components’ look and feels that remain the same across all platforms wherever the program runs. The Swing library provides an API that gives real flexibility in determining the look and feel of the GUI of an application
  • Highly customizable – Swing controls can be customized in a very easy way as visual appearance is independent of internal representation.
  • Rich controls– Swing provides a rich set of advanced controls like Tree TabbedPane, slider, colorpicker, and table controls.
Java Database Connectivity | JDBC
Java Database Connectivity | JDBC

Create a Simple Menu Bar

The JMenu and the JMenuItem are used to create a menu bar in Java. Create a Java file with the following code to create a Menu bar with three items and two sub-items. The “File” menu contains three items. These are “Open”, “Save”, and “Recent” files. The last menu item contains two sub-items. These are “File 1” and “File 2”.

class SwingExample9 {

public static void main(String[] args) {

//Declare JFrame object

JFrame frame= new JFrame(“Menu Example”);

//Set the window size

frame.setSize(350, 150);

//Disable the resize option

frame.setResizable(false);

//Declare JMenu objects

JMenu menuItem, submenuItem;

//Declare JMenuItem objects

JMenuItem itm1, itm2, itm3, itm4;

//Initialize the JMenuItem objects

itm1=new JMenuItem(“Open”);

itm2=new JMenuItem(“Save”);

itm3=new JMenuItem(“File 1”);

itm4=new JMenuItem(“File 2”);

//Define JMenubar object

JMenuBar mbar=new JMenuBar();

//Initialize the JMenu objects

menuItem=new JMenu(“File”);

submenuItem=new JMenu(“Recent Files”);

//Add menu items

menuItem.add(itm1);

menuItem.add(itm2);

submenuItem.add(itm3);

submenuItem.add(itm4);

menuItem.add(submenuItem);

//Add menu bar item

mbar.add(menuItem);

//Add menu bar to frame

frame.setJMenuBar(mbar);

//Set the window position

frame.setLocationRelativeTo(null);

//Make the window visible

frame.setVisible(true);

Output:

The following dialog box will appear after executing the Java class file:

Java


import


java.awt.*;


import


java.awt.event.*;


import


javax.swing.*;


class


solution


extends


JFrame {


static


JFrame f;


static


JButton b, b1, b2, b3;


static


JLabel l;


public


static


void


main(String[] args)


f =


new


JFrame(


"panel"


);


l =


new


JLabel(


"panel label"


);


b =


new


JButton(


"button1"


);


b1 =


new


JButton(


"button2"


);


b2 =


new


JButton(


"button3"


);


b3 =


new


JButton(


"button4"


);


JPanel p =


new


JPanel();


p.setLayout(


new


BoxLayout(p, BoxLayout.Y_AXIS));


p.add(b);


p.add(b1);


p.add(b2);


p.add(b3);


p.add(l);


p.setBackground(Color.red);


f.add(p);


f.setSize(


300


300


);


f.show();

Output:

Henceforth, we are successfully able to generate buttons in our panel.

Note: In the previous Program, border layout and Box Layout are used. Different other layouts can be used to organize the components in a definite pattern, such as card layout, grid layout, etc.

Feeling lost in the vast world of Backend Development? It’s time for a change! Join our Java Backend Development – Live Course and embark on an exciting journey to master backend development efficiently and on schedule. What We Offer:

  • Comprehensive Course
  • Expert Guidance for Efficient Learning
  • Hands-on Experience with Real-world Projects
  • Proven Track Record with 100,000+ Successful Geeks

Last Updated :
10 Nov, 2021

Like Article

Save Article

Share your thoughts in the comments

Please Login to comment…

Swing (Java)

Swing is a GUI widget toolkit for Java.[1] It is part of Oracle’s Java Foundation Classes (JFC) – an API for providing a graphical user interface (GUI) for Java programs.

Swing was developed to provide a more sophisticated set of GUI components than the earlier Abstract Window Toolkit (AWT). Swing provides a look and feel that emulates the look and feel of several platforms, and also supports a pluggable look and feel that allows applications to have a look and feel unrelated to the underlying platform. It has more powerful and flexible components than AWT. In addition to familiar components such as buttons, check boxes and labels, Swing provides several advanced components such as tabbed panel, scroll panes, trees, tables, and lists.[2]

Unlike AWT components, Swing components are not implemented by platform-specific code. Instead, they are written entirely in Java and therefore are platform-independent.

In December 2008, Sun Microsystems (Oracle’s predecessor) released the CSS / FXML based framework that it intended to be the successor to Swing, called JavaFX.[3]

Java textfield 📛
Java textfield 📛

Architecture[edit]

Swing is a platform-independent, “model–view–controller” GUI framework for Java, which follows a single-threaded programming model.[11] Additionally, this framework provides a layer of abstraction between the code structure and graphic presentation of a Swing-based GUI.

Foundations[edit]

Swing is platform-independent because it is completely written in Java. Complete documentation for all Swing classes can be found in the Java API Guide for Version 6 or the Java Platform Standard Edition 8 API Specification for Version 8.

Extensible[edit]

Swing is a highly modular-based architecture, which allows for the “plugging” of various custom implementations of specified framework interfaces: Users can provide their own custom implementation(s) of these components to override the default implementations using Java’s inheritance mechanism via

LookAndFeel

.

Swing is a component-based framework, whose components are all ultimately derived from the

JComponent

class. Swing objects asynchronously fire events, have bound properties, and respond to a documented set of methods specific to the component. Swing components are JavaBeans components, compliant with the JavaBeans specification.

Configurable[edit]

Swing’s heavy reliance on runtime mechanisms and indirect composition patterns allows it to respond at run time to fundamental changes in its settings. For example, a Swing-based application is capable of hot swapping its user-interface during runtime. Furthermore, users can provide their own look and feel implementation, which allows for uniform changes in the look and feel of existing Swing applications without any programmatic change to the application code.

Lightweight UI[edit]

Swing’s high level of flexibility is reflected in its inherent ability to override the native host operating system (OS)’s GUI controls for displaying itself. Swing “paints” its controls using the Java 2D APIs, rather than calling a native user interface toolkit. Thus, a Swing component does not have a corresponding native OS GUI component, and is free to render itself in any way that is possible with the underlying graphics GUIs.

However, at its core, every Swing component relies on an AWT container, since (Swing’s)

JComponent

extends (AWT’s) Container. This allows Swing to plug into the host OS’s GUI management framework, including the crucial device/screen mappings and user interactions, such as key presses or mouse movements. Swing simply “transposes” its own (OS-agnostic) semantics over the underlying (OS-specific) components. So, for example, every Swing component paints its rendition on the graphic device in response to a call to component.paint(), which is defined in (AWT) Container. But unlike AWT components, which delegated the painting to their OS-native “heavyweight” widget, Swing components are responsible for their own rendering.

This transposition and decoupling is not merely visual, and extends to Swing’s management and application of its own OS-independent semantics for events fired within its component containment hierarchies. Generally speaking, the Swing architecture delegates the task of mapping the various flavors of OS GUI semantics onto a simple, but generalized, pattern to the AWT container. Building on that generalized platform, it establishes its own rich and complex GUI semantics in the form of the

JComponent

model.

Loosely coupled and MVC[edit]

The Swing library makes heavy use of the model–view–controller software design pattern,[12] which conceptually decouples the data being viewed from the user interface controls through which it is viewed. Because of this, most Swing components have associated models (which are specified in terms of Java interfaces), and the programmers can use various default implementations or provide their own. The framework provides default implementations of model interfaces for all of its concrete components. The typical use of the Swing framework does not require the creation of custom models, as the framework provides a set of default implementations that are transparently, by default, associated with the corresponding

JComponent

child class in the Swing library. In general, only complex components, such as tables, trees and sometimes lists, may require the custom model implementations around the application-specific data structures. To get a good sense of the potential that the Swing architecture makes possible, consider the hypothetical situation where custom models for tables and lists are wrappers over DAO and/or EJB services.

Typically, Swing component model objects are responsible for providing a concise interface defining events fired, and accessible properties for the (conceptual) data model for use by the associated JComponent. Given that the overall MVC pattern is a loosely coupled collaborative object relationship pattern, the model provides the programmatic means for attaching event listeners to the data model object. Typically, these events are model centric (ex: a “row inserted” event in a table model) and are mapped by the JComponent specialization into a meaningful event for the GUI component.

For example, the

JTable

has a model called

TableModel

that describes an interface for how a table would access tabular data. A default implementation of this operates on a two-dimensional array.

The view component of a Swing JComponent is the object used to graphically represent the conceptual GUI control. A distinction of Swing, as a GUI framework, is in its reliance on programmatically rendered GUI controls (as opposed to the use of the native host OS’s GUI controls). Prior to Java 6 Update 10, this distinction was a source of complications when mixing AWT controls, which use native controls, with Swing controls in a GUI (see Mixing AWT and Swing components).

Finally, in terms of visual composition and management, Swing favors relative layouts (which specify the positional relationships between components) as opposed to absolute layouts (which specify the exact location and size of components). This bias towards “fluid”‘ visual ordering is due to its origins in the applet operating environment that framed the design and development of the original Java GUI toolkit. (Conceptually, this view of the layout management is quite similar to that which informs the rendering of HTML content in browsers, and addresses the same set of concerns that motivated the former.)

Relationship to AWT[edit]

Since early versions of Java, a portion of the Abstract Window Toolkit (AWT) has provided platform-independent APIs for user interface components. In AWT, each component is rendered and controlled by a native peer component specific to the underlying windowing system.

By contrast, Swing components are often described as lightweight because they do not require allocation of native resources in the operating system’s windowing toolkit. The AWT components are referred to as heavyweight components.[13]

Much of the Swing API is generally a complementary extension of the AWT rather than a direct replacement. In fact, every Swing lightweight interface ultimately exists within an AWT heavyweight component because all of the top-level components in Swing (

JApplet

,

JDialog

,

JFrame

, and

JWindow

) extend an AWT top-level container. Prior to Java 6 Update 10, the use of both lightweight and heavyweight components within the same window was generally discouraged due to Z-order incompatibilities. However, later versions of Java have fixed these issues, and both Swing and AWT components can now be used in one GUI without Z-order issues.

The core rendering functionality used by Swing to draw its lightweight components is provided by Java 2D, another part of JFC.

This section may contain material not related to the topic of the article. (May 2012)

Relationship to SWT[edit]

The Standard Widget Toolkit (SWT) is a competing toolkit originally developed by IBM and now maintained by the Eclipse community. SWT’s implementation has more in common with the heavyweight components of AWT. This confers benefits such as more accurate fidelity with the underlying native windowing toolkit, at the cost of an increased exposure to the native platform in the programming model.

There has been significant debate and speculation about the performance of SWT versus Swing; some hinted that SWT’s heavy dependence on JNI would make it slower when the GUI component and Java need to communicate data, but faster at rendering when the data model has been loaded into the GUI, but this has not been confirmed either way.[14] A fairly thorough set of benchmarks in 2005 concluded that neither Swing nor SWT clearly outperformed the other in the general case.[15]

Form Validation

The form validation is a very important part of the desktop application. Create a Java file with the following code to show the simple form validation task in Java. Here, the form has two fields. The first field takes a string value and the second field takes a numeric value. If the valid data are provided in both fields, a message box with input values is printed in the output.

import javax.swing.*;

class SwingExample5 {

public static void main(String[] args) {

//Declare frame object

JFrame win = new JFrame();

//Set the title

win.setTitle(“Java Swing Example-5”);

//Set the window size

win.setSize(500, 200);

/*Create a label object, set the position, and add to the frame*/

JLabel lbl1 = new JLabel(“Book Name:”, JLabel.LEFT);

lbl1.setBounds(80,20,100,20);

win.add(lbl1);

/*Create text object, set the position, and add to the frame*/

JTextField bname = new JTextField();

bname.setBounds(200,20,200,20);

win.add(bname);

/*Create a label object, set the position, and add to the frame */

JLabel lbl2 = new JLabel(“Book Price:”, JLabel.LEFT);

lbl2.setBounds(80,50,100,20);

win.add(lbl2);

/*Create text object, set the position, and add to the frame*/

JTextField bprice = new JTextField();

bprice.setText(“0.00”);

bprice.setBounds(200,50,50,20);

win.add(bprice);

/*Create a button, set the position, and add to the frame */

JButton btn = new JButton(“Submit”);

btn.setBounds(200, 100, 100, 30);

win.add(btn);

//Set window position

win.setLocationRelativeTo(null);

//Disable the default layout of the frame

win.setLayout(null);

//Make the window visible

win.setVisible(true);

//Check whether the input values are valid or invalid

btn.addActionListener((ActionEvent e) -> {

int valid =1;

String title = bname.getText();

float cost = 0;

if(title.equals(“”))

JOptionPane.showMessageDialog(null, “Book name can’t be empty”);

valid = 0;

try {

cost = Float.parseFloat(bprice.getText());

catch (NumberFormatException eg) {

JOptionPane.showMessageDialog(null, “Price must be a number.”);

valid=0;

if(valid == 1)

String values = “Book Name: ” + title + “\nBook Price: $” + cost;

JOptionPane.showMessageDialog(null, values);

});

Output:

The following dialog box will appear after executing the Java class file:

If the user provides the valid data for both fields, the following similar output will appear:

Java Mysql simple project  in IntelliJ IDEA
Java Mysql simple project in IntelliJ IDEA

Create a Toolbar

The JToolBar class is used to create a toolbar in the Java application. Create a Java file with the following code to create a toolbar with three toolbar buttons. Three images are used here to add the image of the toolbar button. The active listener method is created for each button.

import java.awt.event.ActionEvent;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.*;

import java.awt.event.*;

class SwingExample11 {

public static void main(String[] args) {

//Create a JFrame object

JFrame frame = new JFrame(“Java Swing Example-11”);

//Create a JToolBar object

JToolBar toolbar = new JToolBar();

//Create three toolbar buttons

JButton btnNew = new JButton(new ImageIcon(“/home/fahmida/eclipse-workspace/JavaSwingExamples/src/images/new.jpeg”));

JButton btnOpen = new JButton(new ImageIcon(“/home/fahmida/eclipse-workspace/JavaSwingExamples/src/images/open.png”));

JButton btnSave = new JButton(new ImageIcon(“/home/fahmida/eclipse-workspace/JavaSwingExamples/src/images/save.png”));

//Declare addActionListener methods for three buttons

btnNew.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

JOptionPane.showMessageDialog(frame, “New button is pressed.”);

});

btnOpen.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

JOptionPane.showMessageDialog(frame, “Open button is pressed.”);

});

btnSave.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

JOptionPane.showMessageDialog(frame, “Save button is pressed.”);

});

//Add buttons to the toolbar

toolbar.add(btnNew);

toolbar.add(btnOpen);

toolbar.add(btnSave);

//Set the frame layout

frame.setLayout(new BorderLayout());

//Add toolbar to the frame at the beginning of the frame

frame.getContentPane().add(toolbar, BorderLayout.PAGE_START);

//Set the window size

frame.setSize(500, 250);

//Disable the resize option

frame.setResizable(false);

//Set window position

frame.setLocationRelativeTo(null);

//Make the window visible

frame.setVisible(true);

Output:

The following dialog box will appear after executing the Java class file:

If the user clicks on the “New” button, the following output will appear:

Java Swing first example

The first example shows a basic window on the screen.

package com.zetcode; import java.awt.EventQueue; import javax.swing.JFrame; public class SimpleEx extends JFrame { public SimpleEx() { initUI(); } private void initUI() { setTitle(“Simple example”); setSize(300, 200); setLocationRelativeTo(null); setDefaultCloseOperation(EXIT_ON_CLOSE); } public static void main(String[] args) { EventQueue.invokeLater(() -> { var ex = new SimpleEx(); ex.setVisible(true); }); } }

While this code is very short, the application window can do quite a lot. It can be resized, maximised, or minimised. All the complexity that comes with it has been hidden from the application programmer.

import java.awt.EventQueue; import javax.swing.JFrame;

Here we import Swing classes that will be used in the code example.

public class SimpleEx extends JFrame {


SimpleEx

inherits from the

JFrame

component.

JFrame

is a top-level container. The basic purpose of containers is to hold components of
the application.

public SimpleEx() { initUI(); }

It is a good programming practice not to put the application code into constructors, but delegate the task to a specific method.

setTitle(“Simple example”);

Here we set the title of the window using the

setTitle()

method.

setSize(300, 200);

The

setSize()

resizes the window to be 300 px wide and 200 px tall.

setLocationRelativeTo(null);

This line centers the window on the screen.

setDefaultCloseOperation(EXIT_ON_CLOSE);

This

setDefaultCloseOperation()

closes the window if
we click on the Close button of the titlebar. By default nothing
happens if we click on the button.

EventQueue.invokeLater(() -> { var ex = new SimpleEx(); ex.setVisible(true); });

We create an instance of our code example and make it visible on
the screen. The

invokeLater()

method places
the application on the Swing Event Queue. It is used to ensure
that all UI updates are concurrency-safe. In other words, it
is to prevent GUI from hanging in certain situations.

Create your First Java Project with Netbeans 12.6 | How to Create JFrame Forms using Window Builder
Create your First Java Project with Netbeans 12.6 | How to Create JFrame Forms using Window Builder

Java


import


java.awt.*;


class


Lan {


Lan()


Frame f =


new


Frame();


Label l1 =


new


Label(


"Select known Languages"


);


l1.setBounds(


100


50


120


80


);


f.add(l1);


Checkbox c2 =


new


Checkbox(


"Hindi"


);


c2.setBounds(


100


150


50


50


);


f.add(c2);


Checkbox c3 =


new


Checkbox(


"English"


);


c3.setBounds(


100


200


80


50


);


f.add(c3);


Checkbox c4 =


new


Checkbox(


"marathi"


);


c4.setBounds(


100


250


80


50


);


f.add(c4);


f.setSize(


500


500


);


f.setLayout(


null


);


f.setVisible(


true


);


public


static


void


main(String ar[]) {


new


Lan(); }

Output:

Write a Content into a File

Create a Java file with the following code that saves the string data into a new file using the “Save” dialog box. The string data is stored in the filename that is selected by the user.

import java.nio.file.Files;

import java.nio.file.Path;

import java.nio.file.Paths;

import javax.swing.*;

import javax.swing.filechooser.FileSystemView;

class SwingExample7 {

public static void main(String[] args) {

//Create a JFileChooser object

JFileChooser fc = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());

//Open the Save dialog box

int Val = fc.showSaveDialog(null);

//Check whether the Save button is selected or not

if (Val == JFileChooser.APPROVE_OPTION)

//Set the filename taken from the Save dialog box

File sFile = fc.getSelectedFile();

//Create the path object

Path path = Paths.get(sFile.getAbsolutePath());

//Store the content that will be written in the file

String strVal = “The content of the new file”;

//Convert string to byte array

byte[] strArray = strVal.getBytes();

//Try-catch block to write into the file

try {

//Write the content into the file

Files.write(path, strArray);

catch (IOException ex) {

//Print the error message

System.out.print(“File Path does not exist.”);

Output:

The following dialog box will appear after executing the Java class file. Type the filename that will be created to store the data. Here, the “testingfile.txt” is used as the filename:

The following output shows that the file is created in the desired location:

Java Swing Program Code with Output (Tutorial #11)
Java Swing Program Code with Output (Tutorial #11)

Develop a Simple Login System

Create a Java file with the following code that displays a login form to take the username and password from the user and check whether the user credentials are correct or incorrect. If the “admin” value is taken as the username and the “password” value is taken as the password, the “Authenticated” message is printed. Otherwise, the “Not Authenticated” message is printed. The “Login” button is used to take the input values and the “Cancel” button is used to terminate the program.

import javax.swing.*;

class SwingExample15 {

public static void main(String[] args) {

//Declare frame object

JFrame frame = new JFrame();

//Set the title

frame.setTitle(“Java Swing Example-15”);

//Set the window size

frame.setSize(370, 200);

/*Create a label object, set the position, and add to the frame*/

JLabel lbl1 = new JLabel(“Username:”, JLabel.LEFT);

lbl1.setBounds(50,20,100,20);

frame.add(lbl1);

/*Create text object, set the position, and add to the frame*/

JTextField username = new JTextField();

username.setBounds(150,20,150,20);

frame.add(username);

//Create label object, set the position and add to the frame

JLabel lbl2 = new JLabel(“Password:”, JLabel.LEFT);

lbl2.setBounds(50,60,100,20);

frame.add(lbl2);

/*Create password text object, set the position and add to the frame*/

JPasswordField password = new JPasswordField();

password.setBounds(150,60,150,20);

frame.add(password);

/*Create a button, set the position, and add to the frame */

JButton btn1 = new JButton(“Login”);

btn1.setBounds(120, 100, 90, 30);

frame.add(btn1);

/*Create a button, set the position, and, add to the frame*/

JButton btn2 = new JButton(“Cancel”);

btn2.setBounds(215, 100, 100, 30);

frame.add(btn2);

//Set window position

frame.setLocationRelativeTo(null);

//Disable the default layout of the frame

frame.setLayout(null);

//Make the window visible

frame.setVisible(true);

//Handle the login information

btn1.addActionListener((ActionEvent e) -> {

String un = username.getText();

String ps = new String(password.getPassword());

if(un.equals(“admin”) && ps.equals(“secret”))

JOptionPane.showMessageDialog(null, “Authenticated.”);

else

JOptionPane.showMessageDialog(null, “Not Authenticated.”);

});

//Terminate from the program

btn2.addActionListener((ActionEvent e) -> {

System.exit(0);

});

Output:

The following dialog box will appear after executing the Java class file:

If the “Login” button is pressed by keeping the username and password fields empty or by taking invalid values in these fields, the following output will appear:

If the “Login” button is pressed by taking the valid values in the username and password fields, the following output will appear:

The MVC Connection

The simplest Swing components have capabilities far beyond AWT components as follows:

Java GUI: Full Course ☕ (FREE)
Java GUI: Full Course ☕ (FREE)

Simple Form Design with Label and Button

The JLabel class is used to create a label and the JButton class is used to create a button in Java. Create a Java file with the following code to display a dialog box with a label and a button. The title of the dialog box is “Java Swing Example-2”. The value of the label is “Simple Java Swing application” with a blue font color. The caption of the button is “Close”.

import javax.swing.*;

class SwingExample2 {

public static void main(String[] args) {

//Declare frame object

JFrame win = new JFrame();

//Set the title

win.setTitle(“Java Swing Example-2”);

//Set the window size

win.setSize(400, 200);

//Create label object

JLabel lbl = new JLabel(“Simple Java Swing application”);

//Set label font color

lbl.setForeground(Color.blue);

//Set the label position

lbl.setBounds(100,20,250,100);

//Add label to frame

win.add(lbl);

//Create a button

JButton btn = new JButton(“Close”);

//Set the button position

btn.setBounds(150, 100, 80, 30);

//Add button to frame

win.add(btn);

//Set window position

win.setLocationRelativeTo(null);

//Disable default layout of the frame

win.setLayout(null);

//Make the window visible

win.setVisible(true);

Output:

The following dialog box will appear after executing the Java class file:

Full Stack Web Development Internship Program

Swing in java is part of Java foundation class which is lightweight and platform independent. It is used for creating window based applications. It includes components like button, scroll bar, text field etc. Putting together all these components makes a graphical user interface. In this article, we will go through the concepts involved in the process of building applications using swing in Java. Following are the concepts discussed in this article:

Swing in Java is a lightweight GUI toolkit which has a wide variety of widgets for building optimized window based applications. It is a part of the JFC( Java Foundation Classes). It is build on top of the AWT API and entirely written in java. It is platform independent unlike AWT and has lightweight components.

It becomes easier to build applications since we already have GUI components like button, checkbox etc. This is helpful because we do not have to start from the scratch.

Any class which has other components in it is called as a container class. For building GUI applications at least one container class is necessary.

Following are the three types of container classes:

Panel – It is used to organize components on to a window

Frame – A fully functioning window with icons and titles

Dialog – It is like a pop up window but not fully functional like the frame

AWT SWING

Explanation: All the components in swing like JButton, JComboBox, JList, JLabel are inherited from the JComponent class which can be added to the container classes. Containers are the windows like frame and dialog boxes. Basic swing components are the building blocks of any gui application. Methods like setLayout override the default layout in each container. Containers like JFrame and JDialog can only add a component to itself. Following are a few components with examples to understand how we can use them.

It is used to create a labelled button. Using the ActionListener it will result in some action when the button is pushed. It inherits the AbstractButton class and is platform independent.

Example:

import javax.swing.*; public class example{ public static void main(String args[]) { JFrame a = new JFrame(“example”); JButton b = new JButton(“click me”); b.setBounds(40,90,85,20); a.add(b); a.setSize(300,300); a.setLayout(null); a.setVisible(true); } }

Output:

It inherits the JTextComponent class and it is used to allow editing of single line text.

Example:

import javax.swing.*; public class example{ public static void main(String args[]) { JFrame a = new JFrame(“example”); JTextField b = new JTextField(“edureka”); b.setBounds(50,100,200,30); a.add(b); a.setSize(300,300); a.setLayout(null); a.setVisible(true); } }

Output:

It is used to add scroll bar, both horizontal and vertical.

Example:

import javax.swing.*; class example{ example(){ JFrame a = new JFrame(“example”); JScrollBar b = new JScrollBar(); b.setBounds(90,90,40,90); a.add(b); a.setSize(300,300); a.setLayout(null); a.setVisible(true); } public static void main(String args[]){ new example(); } }

Output:

It inherits the JComponent class and provides space for an application which can attach any other component.

import java.awt.*; import javax.swing.*; public class Example{ Example(){ JFrame a = new JFrame(“example”); JPanel p = new JPanel(); p.setBounds(40,70,200,200); JButton b = new JButton(“click me”); b.setBounds(60,50,80,40); p.add(b); a.add(p); a.setSize(400,400); a.setLayout(null); a.setVisible(true); } public static void main(String args[]) { new Example(); } }

Output:

It inherits the JMenuItem class, and is a pull down menu component which is displayed from the menu bar.

import javax.swing.*; class Example{ JMenu menu; JMenuItem a1,a2; Example() { JFrame a = new JFrame(“Example”); menu = new JMenu(“options”); JMenuBar m1 = new JMenuBar(); a1 = new JMenuItem(“example”); a2 = new JMenuItem(“example1”); menu.add(a1); menu.add(a2); m1.add(menu); a.setJMenuBar(m1); a.setSize(400,400); a.setLayout(null); a.setVisible(true); } public static void main(String args[]) { new Example(); } }

Output:

It inherits JComponent class, the object of JList class represents a list of text items.

import javax.swing.*; public class Example { Example(){ JFrame a = new JFrame(“example”); DefaultListModel

l = new DefaultListModel< >(); l.addElement(“first item”); l.addElement(“second item”); JList

b = new JList< >(l); b.setBounds(100,100,75,75); a.add(b); a.setSize(400,400); a.setVisible(true); a.setLayout(null); } public static void main(String args[]) { new Example(); } }

Output:

It is used for placing text in a container. It also inherits JComponent class.

import javax.swing.*; public class Example{ public static void main(String args[]) { JFrame a = new JFrame(“example”); JLabel b1; b1 = new JLabel(“edureka”); b1.setBounds(40,40,90,20); a.add(b1); a.setSize(400,400); a.setLayout(null); a.setVisible(true); } }

Output:

It inherits the JComponent class and is used to show pop up menu of choices.

import javax.swing.*; public class Example{ JFrame a; Example(){ a = new JFrame(“example”); string courses[] = { “core java”,”advance java”, “java servlet”}; JComboBox c = new JComboBox(courses); c.setBounds(40,40,90,20); a.add(c); a.setSize(400,400); a.setLayout(null); a.setVisible(true); } public static void main(String args[]) { new Example(); } }

Output:

To arrange the components inside a container we use the layout manager. Following are several layout managers:

Border layout

Flow layout

GridBag layout

The default layout manager for every JFrame is BorderLayout. It places components in upto five places which is top, bottom, left, right and center.

FlowLayout simply lays the components in a row one after the other, it is the default layout manager for every JPanel.

GridBagLayout places the components in a grid which allows the components to span more than one cell.

import javax.swing.*; import java.awt.*; class Example { public static void main(String args[]) { JFrame frame = new JFrame(“Chat Frame”); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(400, 400); JMenuBar ob = new JMenuBar(); JMenu ob1 = new JMenu(“FILE”); JMenu ob2 = new JMenu(“Help”); ob.add(ob1); ob.add(ob2); JMenuItem m11 = new JMenuItem(“Open”); JMenuItem m22 = new JMenuItem(“Save as”); ob1.add(m11); ob1.add(m22); JPanel panel = new JPanel(); // the panel is not visible in output JLabel label = new JLabel(“Enter Text”); JTextField tf = new JTextField(10); // accepts upto 10 characters JButton send = new JButton(“Send”); JButton reset = new JButton(“Reset”); panel.add(label); // Components Added using Flow Layout panel.add(label); // Components Added using Flow Layout panel.add(tf); panel.add(send); panel.add(reset); JTextArea ta = new JTextArea(); frame.getContentPane().add(BorderLayout.SOUTH, panel); frame.getContentPane().add(BorderLayout.NORTH, tf); frame.getContentPane().add(BorderLayout.CENTER, ta); frame.setVisible(true); } }

This is a simple example for creating a GUI using swing in Java.

If you’re just beginning, then watch at this Java Tutorial to Understand the Fundamental Java Concepts.

In this article we have discussed swing in Java and hierarchy of Java swing classes. With all the components which comes with swing in Java, it becomes easier to build optimized GUI applications. Java programming language is a structured programming language and with the increasing demand it becomes extremely important to master all the concepts in Java programming. To kick-start your learning and to become an expert in java programming, enroll to Edureka’s Java Certification program.

Got a question for us? please mention this in the comments section of this ‘Swing In Java’ article and we will get back to you as soon as possible.

Course Name Date Details
Java Certification Training Course

Class Starts on 24th February,2024

24th February

SAT&SUN (Weekend Batch)

View Details
Java Certification Training Course

Class Starts on 30th March,2024

30th March

SAT&SUN (Weekend Batch)

View Details

edureka.co

Java Swing Tutorial

Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to create window-based applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely written in java.

Unlike AWT, Java Swing provides platform-independent and lightweight components.

The javax.swing package provides classes for java swing API such as JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.

Difference between AWT and Swing

There are many differences between java awt and swing that are given below.

What is JFC

The Java Foundation Classes (JFC) are a set of GUI components which simplify the development of desktop applications.

Hierarchy of Java Swing classes

The hierarchy of java swing API is given below.

Commonly used Methods of Component class

The methods of Component class are widely used in java swing that are given below.

Java Swing Examples

There are two ways to create a frame:

We can write the code of swing inside the main(), constructor or any other method.

Simple Java Swing Example

Let’s see a simple swing example where we are creating one button and adding it on the JFrame object inside the main() method.

File: FirstSwingExample.java

Example of Swing by Association inside constructor

We can also write all the codes of creating JFrame, JButton and method call inside the java constructor.

File: Simple.java

The setBounds(int xaxis, int yaxis, int width, int height)is used in the above example that sets the position of the button.

Simple example of Swing by inheritance

We can also inherit the JFrame class, so there is no need to create the instance of JFrame class explicitly.

File: Simple2.java

Next TopicJava JButton Class

Back to: Java Tutorials For Beginners and Professionals

Java - Swing Example
Java – Swing Example

Prerequisites:

You have to complete the following task before practicing the examples of this tutorial.

A. Install JDK.Download the latest version of JDK from the following URL address:

https://www.oracle.com/in/java/technologies/downloads/B. Download and install a popular Java editor.Different types of editors exist to write and execute the Java code such as Eclipse, Netbeans, etc. The Eclipse editor is used here. You can check this tutorial to install the Eclipse editor.

Generate a Random Number

The “Random” class is used to generate different types of random numbers. Create a Java file with the following code that generates a random number between 1 to 100 when the button is pressed. The generated random number is displayed in a message dialog box.

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.util.Random;

import javax.swing.*;

class SwingExample14 {

public static void main(String[] args) {

//Declare a Frame object

JFrame frame = new JFrame();

//Disable default frame layout

frame.setLayout(null);

//Create a button object

JButton btn = new JButton(“Generate Number”);

//Set the font type of the button

btn.setFont(new Font(“Verdana”, Font.BOLD, 20));

//Set the button position

btn.setBounds(45, 50, 250, 40);

//Add button to the frame

frame.add(btn);

//Add the action listener for the button

btn.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

//Create a random object

Random num = new Random();

//Generate a random number

int n = num.nextInt(100) + 1;

//Convert integer to string

String rnum = String.valueOf(n);

//Display the random number in the message box

JOptionPane.showMessageDialog(frame, “Generated Number: ” + rnum);

});

//Set the title

frame.setTitle(“Java Swing Example-14”);

//Set the window size

frame.setSize(350, 200);

//Disable the resize option

frame.setResizable(false);

//Set window position

frame.setLocationRelativeTo(null);

//Make the window visible

frame.setVisible(true);

Output:

The following dialog box will appear after executing the Java class file:

A new number is generated when the button is pressed and the following similar dialog box will be displayed. Here, the number 98 is generated as a random number:

Java GUI Tutorial - Make a GUI in 13 Minutes #99
Java GUI Tutorial – Make a GUI in 13 Minutes #99

Display the Tabular Data

The JTable class is used to display the tabular output in Java. Create a Java file with the following code to display the data of a two-dimensional array in tabular form. The JTableHeader class is used here to format the table header.

import java.awt.Color;

import java.awt.Font;

import javax.swing.*;

import javax.swing.table.JTableHeader;

class SwingExample12 {

public static void main(String[] args) {

//Declare the JFrame object

JFrame frame = new JFrame(“Java Swing Example-12”);

//Declare an array of objects

Object[][] Sales = {

{“January”, “Dhanmondi”, 120, 20000},

{“February”, “Mirpur”, 340, 50000},

{“March”, “Mogbazar”, 502, 60793},

{“April”, “Jatrabari”, 444, 55000},

{“May”, “Malibagh”, 390, 48000}

};

//Declare an array to store the table heading

String[] colHeader = {“Month”, “Branch”, “Sales items”, “Sales amount” };

//Declare the JTable object

JTable table = new JTable(Sales, colHeader);

//Set the font color of the table

table.setForeground(Color.GREEN);

//Set the table viewpoint height

table.setFillsViewportHeight(true);

//Declare JTableHeading object

JTableHeader tableHeader = table.getTableHeader();

//Set the background color of the table heading

tableHeader.setBackground(Color.CYAN);

//Set the font color of the table heading

tableHeader.setForeground(Color.blue);

//Declare the label to display table caption

JLabel tblCaption = new JLabel(“Sales details Information”);

//Set font setting for the table caption

tblCaption.setFont(new Font(“Times New Roman”,Font.TRUETYPE_FONT,25));

tblCaption.setForeground(Color.darkGray);

//Declare the JScrollPane object

JScrollPane scrollPane = new JScrollPane(table);

//Set the layout and add the table caption and scroll into the frame content

frame.getContentPane().setLayout(new BorderLayout());

frame.getContentPane().add(tblCaption,BorderLayout.PAGE_START);

frame.getContentPane().add(scrollPane,BorderLayout.CENTER);

//Set the width and height of the frame

frame.setSize(500, 175);

//Disable the resize option

frame.setResizable(false);

//Set window position

frame.setLocationRelativeTo(null);

//Make the frame visible

frame.setVisible(true);

Output:

The following dialog box will appear after executing the Java class file:

Examples[edit]

Hello World[edit]

This example Swing application creates a single window with “Hello, world!” inside:

// Hello.java (Java SE 8) import javax.swing.*; public class Hello extends JFrame { public Hello() { super(“Hello World”); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); add(new JLabel(“Hello, world!”)); pack(); setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(Hello::new); } }

The first

import

includes all the public classes and interfaces from the

javax.swing

package.

The

Hello

class

extends

the

JFrame

class; the

JFrame

class implements a window with a title bar and a close control.

The

Hello()

constructor initializes the frame by first calling the superclass constructor, passing the parameter

"Hello World"

, which is used as the window’s title. It then calls the

setDefaultCloseOperation(int)

method inherited from

JFrame

to set the default operation when the close control on the title bar is selected to

WindowConstants.EXIT_ON_CLOSE

– this causes the

JFrame

to be disposed of when the frame is closed (as opposed to merely hidden), which allows the Java virtual machine to exit and the program to terminate. Next, a

JLabel

is created for the string “Hello, world!” and the

add(Component)

method inherited from the

Container

superclass is called to add the label to the frame. The

pack()

method inherited from the

Window

superclass is called to size the window and lay out its contents. The

setVisible(boolean)

method inherited from the

Component

superclass is called with the boolean parameter

true

, which causes the frame to be displayed.

The

main()

method is called by the Java virtual machine when the program starts. It instantiates a new

Hello

frame. The code uses the

invokeLater(Runnable)

method to invoke the constructor from the AWT event dispatching thread in order to ensure the code is executed in a thread-safe manner. Once the frame is displayed, exiting the

main

method does not cause the program to terminate because the event dispatching thread remains active until all of the Swing top-level windows have been disposed.

Window with Button[edit]

The following is a rather simple Swing-based program. It displays a window (a

JFrame

) containing a label and a button.

import java.awt.FlowLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.WindowConstants; import javax.swing.SwingUtilities; public class SwingExample implements Runnable { private JFrame f; public SwingExample() { // Create the window f = new JFrame(“Hello World!”); // Sets the behavior for when the window is closed f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); // Add a layout manager so that the button is not placed on top of the label f.setLayout(new FlowLayout()); // Add a label and a button f.add(new JLabel(“Hello, world!”)); f.add(new JButton(“Press me!”)); } @Override public void run() { // Arrange the components inside the window f.pack(); // By default, the window is not visible. Make it visible. f.setVisible(true); } public static void main(String[] args) { // Schedules the application to be run at the correct time in the event queue. SwingUtilities.invokeLater(new SwingExample()); } }

Notice how all instantiation and handling of Swing components are done by creating an instance of the class,
which implements the Runnable interface. This is then run on the Event Dispatch Thread by use of the method

SwingUtilities.invokeLater(Runnable)

), created in the main method (see Swing and thread safety). Although Swing code can be run without using this technique (for instance, by not implementing Runnable and moving all commands from the run method to the main method), it is considered to be good form, as Swing is not thread-safe, meaning that invoking resources from multiple threads can result in thread interference and memory consistency errors.[16]

Another example[edit]

In this example let javax.swing.JFrame be super class and add our own widget(s) to it (in this case, a JButton).

import javax.swing.JFrame; import javax.swing.JButton; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class Sample extends JFrame { private final JButton b = new JButton(); public Sample() { super(); this.setTitle(“HelloApp”); this.getContentPane().setLayout(null); this.setBounds(100, 100, 180, 140); this.add(makeButton()); this.setVisible(true); this.setDefaultCloseOperation(EXIT_ON_CLOSE); } private JButton makeButton() { b.setText(“Click me!”); b.setBounds(40, 40, 100, 30); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(b, “Hello World!”); } }); return b; } public static void main(String[] args) throws InvocationTargetException, InterruptedException { // Swing calls must be run by the event dispatching thread. SwingUtilities.invokeAndWait(() -> new Sample()); } }

The layout is set to null using the

Container.setLayout(LayoutManager)

method since JFrame uses java.awt.BorderLayout as its default layout-manager. With BorderLayout anything which is added to the container is placed in the center and stretched to accommodate any other widgets. Of course, most real world GUI applications would prefer to use a layout-manager instead of placing everything on absolute co-ordinates.[17]

Create your First Java Frame using Visual Studio Code | Create Java GUI Forms using VS Code
Create your First Java Frame using Visual Studio Code | Create Java GUI Forms using VS Code

Java


import


java.io.*;


import


javax.swing.*;


class


GFG {


public


static


void


main(String[] args)


JFrame frame =


new


JFrame();


JButton button =


new


JButton(


" GFG WebSite Click"


);


button.setBounds(


150


200


220


50


);


frame.add(button);


frame.setSize(


500


600


);


frame.setLayout(


null


);


frame.setVisible(


true


);

Output:
Example 2: Write a program to create three buttons with caption OK, SUBMIT, CANCEL.

What is JFC?

JFC stands for Java Foundation Classes. JFC is the set of GUI components that simplify desktop Applications. Many programmers think that JFC and Swing are one and the same thing, but that is not so. JFC contains Swing [A UI component package] and quite a number of other items:

Easy Java: JFrame Grades Program For Beginners
Easy Java: JFrame Grades Program For Beginners

Create a Popup Menu

The JPopupMenu class is used to create the popup menu in Java. Create a Java file with the following code that displays a popup menu of three items. The menu items are “New file”, “Open file”, and “Save file”. The action listener method is added here to display a message based on the selected menu item.

import java.awt.event.*;

class SwingExample10 {

public static void main(String[] args) {

//Declare JFrame object

JFrame frame = new JFrame();

//Set the title

frame.setTitle(“Java Popup Menu Example”);

//Set the window size

frame.setSize(350, 250);

//Disable the resize option

frame.setResizable(false);

//Define a JPopupMenu object

JPopupMenu popup = new JPopupMenu();

//Define the first menu item

JMenuItem menuItem = new JMenuItem(“New File”);

//Add listener code for the first menu item

menuItem.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

JOptionPane.showMessageDialog(frame, “New file is clicked!”);

});

//Add the first menu item to the popup menu

popup.add(menuItem);

//Define the second menu item

menuItem = new JMenuItem(“Open File”);

//Add listener code for the second menu item

menuItem.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

JOptionPane.showMessageDialog(frame, “Open File is clicked!”);

});

//Add the second menu item to the popup menu

popup.add(menuItem);

//Define the third menu item

menuItem = new JMenuItem(“Save File”);

//Add listener code for the third menu item

menuItem.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

JOptionPane.showMessageDialog(frame, “Save File is clicked!”);

});

//Add the third menu item to the popup menu

popup.add(menuItem);

//Add mouse listener for the JFrame

frame.addMouseListener(new MouseAdapter() {

@Override

public void mousePressed(MouseEvent e) {

showPopup(e);

@Override

public void mouseReleased(MouseEvent e) {

showPopup(e);

private void showPopup(MouseEvent e) {

if (e.isPopupTrigger()) {

popup.show(e.getComponent(), e.getX(), e.getY());

});

//Set window position

frame.setLocationRelativeTo(null);

//Make the window visible

frame.setVisible(true);

Output:

The following dialog box will appear after executing the Java class file and pressing the right button of the mouse:

The following output will appear if the user selects the “New File” menu item from the popup menu:

Java is a versatile programming language. Many types of applications can be developed easily using this language. The Java Swing toolkit is used to develop desktop applications. Java Swing contains all GUI components to implement the Graphical User Interface (GUI) for the desktop application. The Abstract Window Toolkit (AWT) was used in the earlier version of Java to develop GUI for the desktop application. But AWT contains only the basic GUI components such as labels, textboxes, buttons, etc. for designing the interface of desktop applications. Many advanced-level GUI components such as tab pane, menus, table, scroll bar, etc. have been added to the Java Swing toolkit. The “java.swing” package contains all the components and classes of the Java Swing toolkit. The most basic uses of the Java swing controls to develop the desktop applications are shown in this tutorial using 15 Java swing examples.

Java


import


java.awt.*;


import


java.awt.event.*;


import


javax.swing.*;


class


solution


extends


JFrame {


static


JFrame f;


static


JButton b, b1, b2;


static


JLabel l;


public


static


void


main(String[] args)


f =


new


JFrame(


"panel"


);


l =


new


JLabel(


"panel label"


);


b =


new


JButton(


"button1"


);


b1 =


new


JButton(


"button2"


);


b2 =


new


JButton(


"button3"


);


JPanel p =


new


JPanel();


p.add(b);


p.add(b1);


p.add(b2);


p.add(l);


p.setBackground(Color.red);


f.add(p);


f.setSize(


300


300


);


f.show();

Output:

Example 2:

First Java Swing GUI Application with IntelliJ IDEA IDE (2022)
First Java Swing GUI Application with IntelliJ IDEA IDE (2022)

Java GridBagLayout

It is the more sophisticated of all layouts. It aligns components by placing them within a grid of cells, allowing components to span more than one cell.

Step 8) Create chat frameHow about creating a chat frame like below?

Try to code yourself before looking at the program below.

//Usually you will require both swing and awt packages // even if you are working with just swings. import javax.swing.*; import java.awt.*; class gui { public static void main(String args[]) { //Creating the Frame JFrame frame = new JFrame(“Chat Frame”); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(400, 400); //Creating the MenuBar and adding components JMenuBar mb = new JMenuBar(); JMenu m1 = new JMenu(“FILE”); JMenu m2 = new JMenu(“Help”); mb.add(m1); mb.add(m2); JMenuItem m11 = new JMenuItem(“Open”); JMenuItem m22 = new JMenuItem(“Save as”); m1.add(m11); m1.add(m22); //Creating the panel at bottom and adding components JPanel panel = new JPanel(); // the panel is not visible in output JLabel label = new JLabel(“Enter Text”); JTextField tf = new JTextField(10); // accepts upto 10 characters JButton send = new JButton(“Send”); JButton reset = new JButton(“Reset”); panel.add(label); // Components Added using Flow Layout panel.add(tf); panel.add(send); panel.add(reset); // Text Area at the Center JTextArea ta = new JTextArea(); //Adding Components to the frame. frame.getContentPane().add(BorderLayout.SOUTH, panel); frame.getContentPane().add(BorderLayout.NORTH, mb); frame.getContentPane().add(BorderLayout.CENTER, ta); frame.setVisible(true); } }

Java Swing – JPanel With Examples

JPanel, a part of the Java Swing package, is a container that can store a group of components. The main task of JPanel is to organize components, various layouts can be set in JPanel which provide better organization of components, however, it does not have a title bar.

Constructors of JPanel

  1. JPanel(): creates a new panel with a flow layout
  2. JPanel(LayoutManager l): creates a new JPanel with specified layoutManager
  3. JPanel(boolean isDoubleBuffered): creates a new JPanel with a specified buffering strategy
  4. JPanel(LayoutManager l, boolean isDoubleBuffered): creates a new JPanel with specified layoutManager and a specified buffering strategy

Commonly used Functions of JPanel

  1. add(Component c): Adds a component to a specified container
  2. setLayout(LayoutManager l): sets the layout of the container to the specified layout manager
  3. updateUI(): resets the UI property with a value from the current look and feel.
  4. setUI(PanelUI ui): sets the look and feel of an object that renders this component.
  5. getUI(): returns the look and feel object that renders this component.
  6. paramString(): returns a string representation of this JPanel.
  7. getUIClassID(): returns the name of the Look and feel class that renders this component.
  8. getAccessibleContext(): gets the AccessibleContext associated with this JPanel.

Let us take a sample program in order to illustrate the use of JPanel class by appending sequential execution snapshots of outputs justifying the below program sets as follows:

Example:

References[edit]

Citations[edit]

  1. ^ “What is Java Swing? – Definition from Techopedia”. Techopedia Inc. Retrieved 2018-11-03.
  2. ^ Yap, Chee (2003-04-30). “JAVA SWING GUI TUTORIAL”. New York University (NYU). Retrieved 2018-11-03.
  3. ^ “Developing a basic GUI application using JavaFX in Eclipse”. July 2017.
  4. ^ “Sun and Netscape to jointly develop Java Foundation Classes”. Netscape Communications Corporation. 1997-04-02. Archived from the original on 2012-05-09. Retrieved 2011-08-08.
  5. ^ “SUN DELIVERS NEXT VERSION OF THE JAVA PLATFORM”. Sun Microsystems. August 2007. Archived from the original on August 16, 2007. Retrieved 2012-01-08.

    The Java Foundation Classes are now core to the Java 2 platform and includes:The Project Swing set of GUI components, Drag & Drop, Java 2D API which provides new 2D and AWT graphics capabilities as well as printing support, The Java look and feel interface, A new Accessibility API


    {{cite web}}

    : CS1 maint: unfit URL (link)

  6. ^ “JDK 11 update: JavaFX will be decoupled from the JDK”.
  7. ^ “Developing a basic GUI application using JavaFX in Eclipse”. July 2017.
  8. ^ Smith, Donald (March 7, 2018). “The Future of JavaFX and Other Java Client Roadmap Updates”.
  9. ^ Zakhour, Sharon. “Why is Swing Called Swing?”. The Java Tutorials Blog. Retrieved 24 September 2020.
  10. ^ John, Yu (27 August 2003). “Rich clients emerge as alternatives for Web applications”. ComputerWorld. Retrieved 24 September 2020.
  11. ^ Zukowski, John (August 21, 2007). “Swing threading and the event-dispatch thread”. JavaWorld. Retrieved 2020-07-26.
  12. ^ Fowler, Amy. “A Swing Architecture Overview”. Sun Microsystems. Retrieved 2020-07-26.
  13. ^ Zakhour, Sharon; Petrov, Anthony (April 2010). “Mixing Heavyweight and Lightweight Components”. Oracle. Retrieved 2020-07-26.
  14. ^ Strenn, Stephen (March 3, 2006). “Swing vs. SWT Performance – Have a Look at the Call Stacks”. Javalobby. Archived from the original on 2017-09-17.
  15. ^ Žagar, Klemen; Križnar, Igor (March 3, 2006). “SWT Vs. Swing Performance Comparison” (PDF) (1.4 ed.). Cosylab. Archived from the original (PDF) on 2015-05-26.

    It is hard to give a rule-of-thumb where SWT would outperform Swing, or vice versa. In some environments (e.g., Windows), SWT is a winner. In others (Linux, VMware hosting Windows), Swing and its redraw optimization outperform SWT significantly. Differences in performance are significant: factors of 2 and more are common, in either direction.

  16. ^ http://docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html The Event Dispatch Thread
  17. ^ Eckel, Bruce (2006). Thinking in Java (PDF) (4 ed.). Prentice Hall. p. 942. ISBN 978-0131872486. Archived from the original (PDF) on 14 May 2016. Retrieved 13 May 2016.
  18. ^ “JavaFX Developer Home”. www.oracle.com.

Sources[edit]

  • Matthew Robinson, Pavel Vorobiev: Swing, Second Edition, Manning, ISBN 1-930110-88-X
  • David M. Geary: Graphic Java 2, Volume 2: Swing, Prentice Hall, ISBN 0-13-079667-0
  • John Zukowski: The Definitive Guide to Java Swing, Third Edition, Apress, ISBN 1-59059-447-9
  • James Elliott, Robert Eckstein, Marc Loy, David Wood, Brian Cole: Java Swing, O’Reilly, ISBN 0-596-00408-7
  • Kathy Walrath, Mary Campione, Alison Huml, Sharon Zakhour: The JFC Swing Tutorial: A Guide to Constructing GUIs, Addison-Wesley Professional, ISBN 0-201-91467-0
  • Joshua Marinacci, Chris Adamson: Swing Hacks, O’Reilly, ISBN 0-596-00907-0
  • Ivan Portyankin, Swing, Effective User Interfaces (Russian)., 2nd Ed., 2010, Moscow, “Lory”, ISBN 5-469-00005-2

This article is about Programming

How to Create a GUI with Java

By NIIT Editorial

Published on 27/07/2021

8 minutes

GUI, which stands for Graphical User Interface, is a user-friendly visual experience builder for Java applications. It comprises graphical units like buttons, labels, windows, etc. via which users can connect with an application. Swing and JavaFX are two commonly used applications to create GUIs in Java.

Elements of GUI:

A GUI comprises an array of user interface elements. All these elements are displayed when a user is interacting with an application and they are as follows:

1. Input commands such as buttons, check boxes, dropdown lists and text fields.

2. Informational components like banners, icons, labels or notification dialogs.

3. Navigational units like menus, sidebars and breadcrumbs.

GUI in JAVA: Swing and JavaFX

As mentioned above, to create a GUI in Java, Swing and JavaFX are the most commonly used applications. Swing was designed with a flexible architecture to make the elements customizable and easy to plug-and-play which is why it is the first choice for java developers while creating GUIs.

As far as JavaFX is concerned, it consists of a totally different set of graphic components along with new features and terminologies.

Creating a GUI

The process of creating a GUI in Swing starts with creating a class that represents the main GUI. An article of this class acts as a container which holds all the other components to be displayed.

In most of the projects, the main interface article is a frame, i.e., the JFrame class in javax.swing package. A frame is basically a window which is displayed whenever a user opens an application on his/her computer. It has a title bar and buttons such as minimize, maximize and close along with other features.

The JFrame class consists of simple constructors such as JFrame() and JFrame(String). The JFrame() leaves the frame’s title bar empty, whereas the JFrame(String) places the title bar to a specified text.

Apart from the title, the size of the frame can also be customized. It can be established by incorporating the setSize(int, int) method by inserting the width and height desired for the frame. The size of a frame is always designated in pixels.

For example, calling setSize(550,350) would create a frame that would be 550 pixels wide and 350 pixels tall.

Usually, frames are invisible at the time of their creation. However, a user can make them visible by using the frame’s setVisible(boolean) method by using the word ‘true’ as an argument.

The following are the steps to create GUI in Java

STEP 1: The following code is to be copied into an editor

STEP 2: Save and compile the code as mentioned above and then run it.

STEP 3: Adding buttons to the above frame. To create a component in Java, the user is required to create an object of that component’s class. We have already understood the container class JFrame.

One such component to implement is JButton. This class represents the clickable buttons. In any application or program, buttons trigger user actions. Literally, every action begins with a click; like to close an application, the user would click on the close button.

A swing can also be inserted, which can feature a text, a graphical icon or a combination of both. A user can use the following constructors:

· JButton(String): This button is labelled with a specified text.

· JButton(Icon): This button is labelled with a graphical icon.

· JButton(String,Icon): This button is labelled with a combination of text and icon.

The following code is to be copied into an editor:

STEP 4: The above is to be executed. A big button will appear on the screen.

STEP 5: A user can add two buttons to the frame as well. Copy the code given below into an editor.

STEP 6: Save, compile and run the above code.

STEP 7: Unpredicted output = ? It means that the buttons are getting overlapped.

STEP 8: A user can create chat frames as well. Below is an example of the same:

The following is the code for creating a chat frame:

Conclusion

It can be concluded that creating GUI in Java is a very easy and user-friendly process as the Java applications provide customization according to the requirements of the user. To learn more about Java, and to become an expert in Java development go to NIIT and check out the courses that give great insight on Java.

PGP in Full Stack Product Engineering

Become an Industry-Ready StackRoute Certified Full Stack Product Engineer who can take up Product Development and Digital Transformation projects. Job Assured Program* with a minimum CTC of ₹7LPA*

Job Assured Program*

Easy Financing Options

Java Swing first programs

last modified January 10, 2023

In this chapter, we will program our first Swing programs. We create a first simple application, show how to terminate an application with a Quit button, display a frame icon, display a tooltip, use mnemonics, and display standard colours.

Java Swing components are basic building blocks of a Java Swing application.
In this chapter we will use

JFrame

,

JButton

, and

JLabel

components.

JFrame

is is a top-level window with a title and a border.
It is used to organize other components, commonly referred to as child components.


JButton

is a push button used to perform an action.

JLabel

is a component used to dispay a short text string or an image, or both.

jTree Examples in java swing Netbeans
jTree Examples in java swing Netbeans

Java


import


java.awt.*;


import


java.awt.event.*;


import


javax.swing.*;


class


solution


extends


JFrame {


static


JFrame f;


static


JButton b, b1, b2, b3;


static


JLabel l;


public


static


void


main(String[] args)


f =


new


JFrame(


"panel"


);


l =


new


JLabel(


"panel label"


);


b =


new


JButton(


"button1"


);


b1 =


new


JButton(


"button2"


);


b2 =


new


JButton(


"button3"


);


b3 =


new


JButton(


"button4"


);


JPanel p =


new


JPanel(


new


BorderLayout());


p.add(b, BorderLayout.NORTH);


p.add(b1, BorderLayout.SOUTH);


p.add(b2, BorderLayout.EAST);


p.add(b3, BorderLayout.WEST);


p.add(l, BorderLayout.CENTER);


p.setBackground(Color.red);


f.add(p);


f.setSize(


300


300


);


f.show();

Output:

Example 3:

Working with Image

The ImageIcon class is used to add the image in different Java Swing Controls. Create a Java file with the following code that adds the image in the label and display the label with the image in the output.

import javax.swing.*;

class SwingExample13 {

public static void main(String[] args) {

//Declare a Frame object

JFrame frame = new JFrame();

//Declare a label object

JLabel lbl = new JLabel();

//Set the image for the label using ImageIcon

lbl.setIcon(new ImageIcon(“/home/fahmida/eclipse-workspace/JavaSwingExamples/src/images/flower.jpeg”));

//Declare a dimension object

Dimension size = lbl.getPreferredSize();

//Set the position of the label

lbl.setBounds(50, 30, size.width, size.height);

//Add label to the frame

frame.add(lbl);

//Set the frame title

frame.setTitle(“Java Swing Example-13”);

//Disable the default layout

frame.setLayout(null);

//Set the frame size

frame.setSize(400, 300);

//Disable the resize option

frame.setResizable(false);

//Set frame position

frame.setLocationRelativeTo(null);

//Make the frame visible

frame.setVisible(true);

Output:

The following dialog box will appear after executing the Java class file. The “follower.jpeg” image file is added to the label:

Create button in java using swing #java #frontenddeveloper #fullstack #javatutorial #codewithharry
Create button in java using swing #java #frontenddeveloper #fullstack #javatutorial #codewithharry

Swings in Java with Examples

In this article, I am going to discuss Swings in Java with Examples. Please read our previous article, where we discussed Event Handling in Java. At the end of this article, you will understand the following pointers in detail.

  1. What are Swings in Java
  2. Why do we need Swings in Java?
  3. Difference Between AWT package and SWING package
  4. Common Methods of Swing Component
  5. Understanding WindowPane & JFrame
  6. Multiple Programs to understand Swings in Java
Swings in Java:

Swings are used to develop a better efficient GUI. The Swing component is part of JFC (Java Foundation Classes) which are developed in Java. The Swing components are called lightweight components which will improve the performance of the application because the amount of resources required is very minimum. There are no peer classes for the swing components to interact with the operating system. The swing component supports a pluggable look and feels using which the component can be presented in various fat forms having the same behavior.

Note: Swing is not a replacement for AWT but is an extension of AWT.

Swing is an advanced package compared to the AWT package and also Swing doesn’t depend on peer classes. The swing package follows the MVC architecture model. Here, MVC stands for Model View Controller Architecture.

MVC architecture is for separating presentation logic from controlling and business logic. Here, business logic is nothing but a model. For example, we can take a button as an example if we click on the button the state of the button is changed, i.e. on the button, we will see dotted lines. Internally controller class is responsible to communicates with the model to change the state of the button component and it communicates with a view to updating that state. Here the view is nothing but UI (User Interface).

Difference Between AWT package and SWING package
AWT package
  1. AWT package-based classes must depend on peer classes for creating UI components.
  2. It makes Java platform-dependent.
  3. It doesn’t follow the MVC architecture pattern.
SWING package
  1. It doesn’t depend on peer classes.
  2. It makes Java platform-independent.
  3. It follows the MVC architecture style.
Features of Swing
  1. It provides a lightweight architecture.
  2. It provides support for the look and feels management.
  3. It allows us to add images to the background of UI Components.
  4. It provides advanced classes that support fro latest UI Components creation like Dialog boxes, etc.
Common Methods of Swing Component
  1. public void add(Component c): It is used to add a component to another component.
  2. public void setSize(int width, int height): It is used to set the size of the component.
  3. public void setLayout(LayoutManager m): It is used to set the layout manager for the component.
  4. public void setVisible(boolean b): It is used to set the visibility of the component. By default, the value is set to be false.
Example to understand Swings in Java:

import javax.swing.*; import java.awt.event.*; public class SwingDemo1 { public static void main (String[]args) { JFrame jf = new JFrame (); jf.setSize (100, 100); JButton jb = new JButton (“click”); jb.setMnemonic (‘C’); MyListener ob = new MyListener (); jb.addActionListener (ob); jf.add (jb); jf.setVisible (true); } } class MyListener implements ActionListener { public void actionPerformed (ActionEvent ae) { System.out.println (“Button Clicked”); } }

Output:

In the above application, we defined a keyboard shortcut key for the button component using setMnemonics().

Note: The keyboard shortcut key is an advanced feature provided by Java Swing.

WindowPane

The empty area that is available in a container is which is used for displaying the components is called WindowPane. The windowpane is internally divided into multiple panes.

  1. GlassPane: This is the first pane closer to the window(screen) and it is used for displaying foreground components.
  2. ContentPane: This pane is available behind GlassPane and is used for displaying individual components.
  3. LayeredPane: This pane is available behind the content pane and is used to display a group of components.
  4. RootPane: This pane is available behind the Layered pane and it is used to display background components.

Note: All the four panes are placed on top of one another and they are transpired All the swing components are available in javax.swing package.

JFrame

The javax.swing.JFrame class may be a sort of container which inherits the java.awt.Frame class. JFrame works just like the main window where components like labels, buttons, and text fields are added to make a GUI. Unlike Frame, JFrame has the choice to cover or close the window with the assistance of the setDefaultCloseOperation(int) method.

Syntax : JFrame jf = new JFrame();

JFrame Constructors
  1. JFrame(): It is used to construct a new Frame that is visible initially.
  2. JFrame(GraphicsConfiguration gc): It is used to create a Frame in the specified GraphicsConfiguration of a screen device and a blank title.
  3. JFrame(String title): It is used to create a new, initially invisible Frame with the specified title.
  4. JFrame(String title, GraohicsConfiguration gc): It is used to create a JFrame with the specified title and the specified GraphicsConfiguration of a screen device.
Example to understand JFrame in Java:

import javax.swing.*; public class JFrameDemo { public static void main (String[]args) { JFrame jf = new JFrame (); jf.setVisible (true); jf.setSize (400, 500); jf.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); } }

Output:

In the next article, I am going to discuss Swing Controls in Java with examples. Here, in this article, I try to explain Swings in Java with Examples and I hope you enjoy this Swing in Java with Examples article.

About the Author: Pranaya Rout

Pranaya Rout has published more than 3,000 articles in his 11-year career. Pranaya Rout has very good experience with Microsoft Technologies, Including C#, VB, ASP.NET MVC, ASP.NET Web API, EF, EF Core, ADO.NET, LINQ, SQL Server, MYSQL, Oracle, ASP.NET Core, Cloud Computing, Microservices, Design Patterns and still learning new technologies.

Java Swing Tutorial: How to Create a GUI Application in Java

What is a Container Class?

Container classes are classes that can have other components on it. So for creating a Java Swing GUI, we need at least one container object. There are 3 types of Java Swing containers.

  1. Panel: It is a pure container and is not a window in itself. The sole purpose of a Panel is to organize the components on to a window.
  2. Frame: It is a fully functioning window with its title and icons.
  3. Dialog: It can be thought of like a pop-up window that pops out when a message has to be displayed. It is not a fully functioning window like the Frame.
Create text field and label using java (swing) #java #programming #coding #apnikaksha #javatutorial
Create text field and label using java (swing) #java #programming #coding #apnikaksha #javatutorial

Display a Simple Window

The JFrame is used to create the GUI-based applications in Java. It is used to display the output in a dialog box. Create a Java file with the following code that displays a dialog with the title, “Java Swing Example-1”, at the center of the screen.

class SwingExample1 {

public static void main(String[] args) {

//Declare JFrame object

JFrame frame = new JFrame();

//Set the title

frame.setTitle(“Java Swing Example-1”);

//Set the frame size

frame.setSize(350, 150);

//Disable the resize option

frame.setResizable(false);

//Set frame position to the center of the screen

frame.setLocationRelativeTo(null);

//Make the frame visible

frame.setVisible(true);

Output:

The following dialog box will appear after executing the Java class file:

Open an Existing File

The JFileChooser class is used to open an existing file or save a file. Create a Java file with the following code that opens an existing file for reading. If the selected file contains any content, the content is displayed in the console.

import javax.swing.*;

import javax.swing.filechooser.FileNameExtensionFilter;

import javax.swing.filechooser.FileSystemView;

class SwingExample6 {

public static void main(String[] args) {

//Create a JFileChooser object

JFileChooser fc = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());

//Disable all file types selection

fc.setAcceptAllFileFilterUsed(false);

//Set the filter

FileNameExtensionFilter filter = new FileNameExtensionFilter(“Text Files”, “txt”);

//Apply the filter

fc.addChoosableFileFilter(filter);

//Display open dialog box

int Val = fc.showOpenDialog(null);

//Check Open button is selected or not

if (Val == JFileChooser.APPROVE_OPTION)

BufferedReader buffer = null;

try

//Read the selected file

File sFile = fc.getSelectedFile();

//Read the path

File file = new File(sFile.getAbsolutePath());

//Initialize the BufferedReader object

buffer = new BufferedReader(new FileReader(file));

//Declare variables to store the file content

String storage=””, line;

//Read the file

while ((line = buffer.readLine()) != null)

//Store the file content

storage = storage+line+”\n”;

//Print the file content in the console

System.out.println(storage);

} catch (FileNotFoundException ex) {

System.out.println(“File does not exist.”);

} catch (IOException ex) {

System.out.println(“Unable to access the file.”);

Output:

The file open dialog box will appear after executing the Java class file. Any text file can be selected by browsing the folder here:

Here, the “test.txt” file is selected and the content of this file is printed in the console:

Java Text Area GUI Beginner Program
Java Text Area GUI Beginner Program

List of Java Swing Examples

  1. Display a Simple Window
  2. Simple Form Design with Label and Button
  3. Form Design with Basic Controls
  4. Display the Different Types of Dialog Boxes
  5. Form Validation
  6. Open an Existing File
  7. Write a Content into a File
  8. Display the Current Data and Time
  9. Create a Simple Menu Bar
  10. Create a Popup Menu
  11. Create Toolbar
  12. Display Tabular Data
  13. Working with Image
  14. Generate a Random Number
  15. Develop a Simple Login System

Keywords searched by users: java swing programs examples with output

15 Java Swing Examples
15 Java Swing Examples
Java Swing Tutorial | A Quick Glance Of Self Guide To Learn Java Swing
Java Swing Tutorial | A Quick Glance Of Self Guide To Learn Java Swing
Java Swing Tutorial For Beginners
Java Swing Tutorial For Beginners
Graphics Programming Exercises - Java Programming Tutorial
Graphics Programming Exercises – Java Programming Tutorial
Java Swing: Definition, Classes & Methods - Video & Lesson Transcript |  Study.Com
Java Swing: Definition, Classes & Methods – Video & Lesson Transcript | Study.Com
Java Swing Gridlayout Tutorial With Examples
Java Swing Gridlayout Tutorial With Examples
Java Swing | Jtextarea - Geeksforgeeks
Java Swing | Jtextarea – Geeksforgeeks
○.. My B.Tech ..○ 2K8618.Blogspot.Com - 2K8Cse: Phonebook - Java Swing -  Jtable Example - Netbeans - Internet & Web Programming Lab
○.. My B.Tech ..○ 2K8618.Blogspot.Com – 2K8Cse: Phonebook – Java Swing – Jtable Example – Netbeans – Internet & Web Programming Lab
Swing Program In Java | A Brief Overview Of Swing Program In Java
Swing Program In Java | A Brief Overview Of Swing Program In Java
Student Grade Calculator Using Java Swing - Geeksforgeeks
Student Grade Calculator Using Java Swing – Geeksforgeeks
A Simple Jframe Gui And Opening A File In Java - Youtube
A Simple Jframe Gui And Opening A File In Java – Youtube
Gui Programming - Java Programming Tutorial
Gui Programming – Java Programming Tutorial
Java Swing Tutorial: How To Create A Gui Application In Java
Java Swing Tutorial: How To Create A Gui Application In Java
Java Swing Layout | A Concise Guide To Swing Layout In Java
Java Swing Layout | A Concise Guide To Swing Layout In Java
Swing Dialog Boxes In Java With Examples - Dot Net Tutorials
Swing Dialog Boxes In Java With Examples – Dot Net Tutorials
Java Eclipse Gui Tutorial 1 # Creating First Gui Project In Eclipse -  Youtube
Java Eclipse Gui Tutorial 1 # Creating First Gui Project In Eclipse – Youtube

See more here: kientrucannam.vn

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *