Genesis & Structure of Java: Topic 02
Genesis & Structure of Java: Topic 02
java
TOPIC 02
Topics covered
GUI and Swing
Basic Swing Based program in java
Adding Controls
Adding Events
Introduction
Swing
→ Swing is a principal GUI toolkit for the Java programming language.
→ It is a part of the JFC (Java Foundation Classes), which is an API for providing a
graphical user interface for Java programs.
→ It is completely written in Java.
The main characteristics of the Swing toolkit
→ platform independent
→ customizable
→ extensible
→ configurable
→ lightweight
Our first example
package com.bit;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
→ In our first example, we will show a basic window on the screen.
public class SimpleExample extends JFrame {
→ The code is shown here c
→ public this
While SimpleExample() { short, the application window can do quite a lot. It can be
code is very
setTitle("Simple
resized, example");
maximized, minimized. All the complexity that comes with it has been hidden
setSize(300, 200);
from the application programmer.
setLocationRelativeTo(null);
import javax.swing.JFrame;
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
import javax.swing.SwingUtilities;
→ publicwe
Here static void main(String[]
import Swing classesargs) that
{ will be used in the code example.
public class Example extendsRunnable()
SwingUtilities.invokeLater(new JFrame { {
→ @Override class inherits from the JFrame widget. JFrame is a toplevel container. In
The Example
public void run() {
the container, we put other widgets.
SimpleExample ex = new SimpleExample();
setTitle("Simple example");
ex.setVisible(true);
}
→ Here
}); we set the title of the window using the setTitle() method.
}
}
Our first example
setSize(300, 200);
→ This code will resize the window to be 300px wide and 200px tall.
setLocationRelativeTo(null);
→ This line will center the window on the screen.
setDefaultCloseOperation(EXIT_ON_CLOSE);
→ This method will close the window, if we click on the close button of the titlebar. By
default nothing happens.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
SimpleExample ex = new SimpleExample();
ex.setVisible(true);
}
});
→ We create an instance of our code example and make it visible on the screen.
(advanced topic and we should not worry right now about it.)
We position a JButton on the window. We will add an action listener to this button.
package com.bit;
import java.awt.event.*;