Site icon Software Test Tips

Java Swing Tutorial: Examples to create GUI

Java Swing Tutorial_ Examples to create GUI

One of the most admired and often used programming languages for developing web applications in Java. You can write down the code on one platform in the Java programming language and run it anywhere on any platform. It follows the principle of the WORA (Write Once, Run Anywhere). The Java programming language is one of the most flexible, class-based, and object-oriented languages. This post will see the Java Swing tutorial, which will help you design the graphical user interface for any website application. 

What is Java Swing?

A Graphical User Interface (GUI) toolkit for the Java programming language is the Java Swing. You can build the graphical user interface in Java using Java Swing. The Java Swing toolkit belongs to Oracle’s Java Foundation Classes (JFC). The Java Foundation Class (JFC) is an application program interface (API) that offers GUI for building Java applications. 

Earlier, the Java language used Abstract Window Toolkit (AWT) for developing the graphical user interface of web applications. Like the Swing toolkit, the abstract Window Toolkit also belongs to Oracle’s Java Foundation Class (JFC). The Java Swing toolkit is a more flexible and enhanced toolkit than the abstract window toolkit for developing GUI. The components present in the Java Swing toolkit are more manageable and robust than the AWT toolkit. 

One of the primary differences between Java Swing and AWT is the Java Swing components are platform-independent and are wholly coded in Java. On the contrary, the AWT components are not platform-independent; instead, they are coded in the platform-specific code. The other difference between Java Swing and AWT is the Java Swing toolkit offers some additional components than AWT toolkit, like trees, tables, scroll panes, and tabbed panels. 

Java Swing is based on the Model-View-Controller architecture. The fundamental idea of this architecture is it categorizes Java Swing components into three different elements. These elements are Model, View, and Controller. 

The first element, Model, contains the data of a particular Java Swing component. Next, the view element displays the visual representation of the data present in the Model element. Lastly, the controller allows users to enter input on the view element, and the result is reflected on this element. The model element of the MVC is present separately, whereas view and controller elements are combined. 

Features of Java Swing

The following are some significant characteristics of Java Swing.

  1. Platform-independent:

Java Swing components are platform-independent. They do not require any specific code to be run on a particular platform. Therefore, you can use Java Swing GUI components on any platform from anywhere. 

  1. Lightweight:

Another characteristic of Java Swing components is they are lightweight. Hence, the graphical user interface of any web application also becomes lightweight. All elements of Java Swing are coded in the Java language. 

  1. Model-View-Controller (MVC):

All components of Java Swing are grouped into three elements, Model, View, and Controller. The MVC architecture is exceptionally beneficial and advantageous. If you desire to modify one single component, it will not affect the other members. Hence, such architecture is referred to as loosely-coupled architecture. 

  1. Customizable:

Java Swing components are customizable. In other words, you can change components as per your needs. You can also change the appearance of components with ease. Another advantage of Java Swing is you can change the look and feel at runtime. 

  1. Manageable and Accessible:

Java Swing is highly flexible and manageable. It allows any modifications during the run time. You can modify the graphical user interface without performing any changes in the application code. 

Difference between Java Swing and Abstract Window Toolkit

Let us see how the Java Swing and Abstract Window Toolkit differ from each other. 

Java SwingJava Abstract Window Toolkit
All components in the Java Swing toolkit are platform-independent. Components present in the Abstract Window Toolkit are not platform-independent. They are implemented in the platform-specific code. 
Components of the Java Swing toolkit are light in weight. The Abstract Window Toolkit has relatively heavier components than Java Swing. 
Java Swing components are present in the javax.swing package. Abstract Window Toolkit components are present in the java.awt package. 
Java Swing components provide a pluggable look and feel of the GUI. Components of the Abstract Window Toolkit do not offer any pluggable look and feel for the GUI. 
It has a more advanced and flexible component set, like tables, lists, tabbed panes, etc. This toolkit has limited components. 
Java Swing is based on the Model View Controller (MVC) pattern. The Abstract Window Toolkit does not support the MVC pattern. 
Java Swing components take less time for execution. Abstract Window Toolkit Components take relatively more time than Java Swing for execution. 
This toolkit’s components occupy less memory space. These components occupy less memory space. 

So far, we have seen Java Swing, its features, and the difference between two java toolkits for GUI implementation. The implementation of these toolkits is possible only if you have a complete Java set-up on your desktop. The following section will help you in setting up the Java environment on our Windows 2000/XP desktops. 

Setting Up the Java Path for Windows 2000/XP

Firstly, you need to download the Java SE from the link Oracle Java Archive. You must choose the Java SE version that is compatible with your operating system. After downloading the Java SE, you need to run the .exe file and install Java on the Windows desktop. But, you can run any code using these steps. You need to set the environmental variables’ path to the Java executable. The following steps will mentor you in setting up the Java path for Windows. 

Suppose you have installed Java SE, and it is present in the directory,  c:\Program Files\java\jdk. Start setting up the path for Java. 

  1. On your desktop screen, select ‘My Computer.’ After that, click right on the mouse and select ‘Properties.’ 
  2. Later, click on the ‘Advanced System Settings,’ and a screen displays a field for ‘Environmental variables.’
  3. In the ‘Environmental variables,’ select ‘Path.’ You will notice some other default path in that field. You need to change it. 
  4. Suppose the current path is ‘C:\WINDOWS\SYSTEM2,’ you have to change it to ‘C:\WINDOWS\SYSTEM2;c:\Program Files\java\jdk\bin.’

Your path is set, and you can run any Java code comfortably on your desktop using the command prompt.  

How to Run the Java Program on Windows?

Once you set the path for the environmental variables, your set up for running any Java code is ready. How to run Java code after setting up environmental variables? 

  1. Write your Java code in text editors, like Notepad, Netbeans, and Eclipse, and save your file with the .java extension. 
  2. The most significant thing you must remember while saving your Java file is that the file’s name and public class should have the same name mentioned in your code. 
  3. After you write the code and save your file, go to the directory where you saved your file and open the command prompt
  4. Now, you need to compile your file code using the ‘javac’ keyword. Enter ‘javac filename.java.’ If there are errors, it displays immediately. Or else, you need to run the code. 
  5. For running the java file, you have to enter ‘java filename.java.’
  6. The result of your code will be displayed on the screen. If your code involves GUI, a separate tab gets opened, showing the GUI. 

Aspects of Java GUI

The Java graphical user interface has three significant aspects, as follows:

  1. UI Elements:

User Interface elements are the components that are required to develop the GUI of any web application. UI elements depict the visual representation of code. Several Java UI elements are present in the Java Swing, like tables, lists, tabbed panes, etc. 

  1. Layout:

This aspect of the Java GUI implies how the UI elements should be placed on the screen. In other words, how will the GUI of any web application look? 

  1. Behavior:

Behavior is the event caused when the user clicks on any UI element. For example, if a button has ‘Sign in’ text on it, you sign in to a particular website whenever you click on that button. 

Classes in Java Swing GUI

The package to be included in any java code for creating the GUI of any web application is javax.swing package. It contains all classes and UI elements required for creating the GUI. Let us see some significant classes of the Java Swing. 

  1. Component Class:

The component class of the Java Swing is the superclass of the Abstract Window Toolkit’s non-menu related components. There are two different kinds of components, lightweight and heavyweight. The lightweight component is present on its native window, whereas the heavyweight component is not present on the native window. Let us know how the component class is declared. 

public abstract class Component
      extends Object
implements ImageObserver, MenuContainer, Serializable

You can create a new component using the constructor class, called protected Component(). 

  1. Container Class:

A container is a combination of all components. You can see two different container types, top-level containers, and low-level containers. In the low-level container, components present are heavier in weight, like JPanel, JFrame, JDialog, JApplet, and JWindow. The top-level container has components, like JPanel, which is lightweight. The below syntax shows you how the container is declared.

public class Container
extends Component

The constructor class used to create a new Container is Container().

There are three primary components of the container class, JFrame, JApplet, and JPanel. 

The JFrame class is the component of the top-level container of the Java Swing. It acts as a screen for all other low-level components, like buttons, textfield, labels, radiobuttons, etc. Whenever you need to create a new frame, you have to use JFrame(). 

Applets are programs that can be run on web browsers. Every applet in Java has a life cycle consisting of init, start, stop, destroy, and paint methods. Applets can be written in any other programming language and run on the Java Virtual Machine (JVM). The JApplet class is used to represent the Applet function. 

Another primary component of the Container class is JPanel. This component is used to handle and organize all other components and layouts. The function JPanel() is used to create a new panel in the Java Swing GUI. 

  1. JComponent Class:

The most fundamental class in the Java Swing is the JComponent Class. It includes all Java Swing components, except all components present in the top-level container. In other words, components starting their names with J are descendants of the JComponent class. Some examples of the JComponent class are  JButton, JScroolPane, JTable, etc. The following lines of code display the declaration of the JComponent class.

public abstract class JComponent
extends Container
implements Serializable

The constructor class used to create the JComponent class is JComponent(). 

Java Swing GUI Sample Code for creating Frame

We shall see a Java code that will create a Frame. 

import javax.swing.*;
class guiframe{
    public static void main(String args[]){
      JFrame frame = new JFrame("This is an example of creating Frame");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setSize(400,400);
      frame.setVisible(true);
    }
}

The frame of width 400 and length 400 gets created. The title of the frame is “This is an example of creating Frame.” You can add any other low-level components into the frame. 

Output:

Java Swing GUI Components

Several Java Swing GUI components are present in the container class. The below article segment will mentor you about how to make a GUI in Java with components. Let us look at each low-level Java Swing GUI component in detail with examples. 

  1. JLabel:

We use the JLabel component for displaying the text or image on the frame. By default, the text we enter for the label is aligned vertically at the center position. The JLabel() constructor is used to create a label. 

JLabel Declaration:

public class JLabel
extends JComponent
implements SwingConstants,  Accessible 

Java Sample Code User Interface Window using JLabel:

import javax.swing.*; 
class JavaLabel 
{ 
public static void main(String args[]) 
    { 
    JFrame f= new JFrame("Java Swing Label"); 
    JLabel la1,la2; 
    la1=new JLabel("Java Programming"); 
    la1.setBounds(70, 70, 120, 50); 
    la2=new JLabel("Java Swing"); 
    la2.setBounds(70,120, 120, 50); 
    f.add(la1); f.add(la2); 
    f.setSize(700,700); 
    f.setLayout(null); 
    f.setVisible(true); 
    } 
    }  

Output:

  1. JButton:

Another component is JButton, which creates buttons on the screen. You can also label a button and add an event to perform a specific function whenever it is clicked. The constructor used to create a new button is JButton(). 

JButton Declaration:

public class JButton
extends AbstractButton
implements Accessible

Java Sample Code User Interface Window using JButton:

import javax.swing.*;   
public class JavaButton { 
public static void main(String[] args) { 
    JFrame f=new JFrame("Creating Java Button"); 
    JButton bt=new JButton("Sign in"); 
    bt.setBounds(70,120,115,50); 
    f.add(bt); 
    f.setSize(500,500); 
    f.setLayout(null); 
    f.setVisible(true);  
} 
}  

Output:

  1. JColorChooser:

The JColorChooser component is used to change or select a color from the color palette. It creates a dialog box. If you use the constructor, JColorChooser(), the default color is white. For using the specified color, you can use the JColorChooser( Color initialColor) constructor. 

JColorChooser Declaration:

public class JColorChooser
extends JComponent
implements Accessible

Java Sample Code User Interface Window using JColorChooser:

import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
  public class JavaColorChooser extends
      JFrame implements ActionListener {
    JButton bt = new JButton("color");
    Container ct = getContentPane();
    JavaColorChooser()
    {
        ct.setLayout(new FlowLayout());
        bt.addActionListener(this)
        ct.add(bt);
    }
    public void actionPerformed(ActionEvent e)
    {
        Color initialcolor = Color.RED;
  Color color = JColorChooser.showDialog(this, "Select any color", initialcolor);
        ct.setBackground(color);
    }
    public static void main(String[] args)
    {
        JavaColorChooser cch = new JavaColorChooser();
        cch.setSize(500, 500);
        cch.setVisible(true);
        cch.setDefaultCloseOperation(EXIT_ON_CLOSE);
    }
} 

Output:

When you click on the button named ‘color,’ the second window displaying colors appear. 

  1. JCheckBox:

JCheckBox is another Java Swing GUI component, which enables users to select and deselect multiple choices. It has a state called ‘on’ or ‘off.’ When the user clicks right on the checkbox, the state changes to ‘on.’ The constructor class used to create checkboxes is JCheckBox(). You can select multiple checkboxes as per your requirement. 

JCheckBox Declaration:

public class JCheckBox
extends JToggleButton
implements Accessible

Java Sample Code User Interface Window using JCheckBox:

import javax.swing.*; 
public class JavaCheckBox 
{ 
    JavaCheckBox(){ 
        JFrame f= new JFrame("Java Swing CheckBox"); 
        JCheckBox cb1 = new JCheckBox("C Programming"); 
        cb1.setBounds(100,100, 50,50); 
        JCheckBox cb2 = new JCheckBox("Java Programming", true); 
        cb2.setBounds(120,170, 70,70); 
        f.add(cb1); 
        f.add(cb2); 
        f.setSize(500,500); 
        f.setLayout(null); 
        f.setVisible(true); 
    } 
public static void main(String args[]) 
    { 
    new JavaCheckBox(); 
    }}  

Output:

  1. JRadioButton:

We see radiobuttons in many forms or applications. It is specially used for selecting gender, female, or male. When only one option is to be picked out of multiple possibilities, the radiobutton is used. The constructor class to create radiobuttons is JRadioButton(). You can choose only one radiobutton at a time. 

JRadioButton Declaration:

public class JRadioButton
extends JToggleButton
implements Accessible

Java Sample Code User Interface Window using JRadioButton:

import javax.swing.*;   
public class JavaRadioButton {   
JFrame f;   
JavaRadioButton(){   
f=new JFrame("Java Swing RadiButton Example");    
JRadioButton rb1=new JRadioButton("1) Male");   
JRadioButton rb2=new JRadioButton("2) Female");   
rb1.setBounds(80,50,90,30);   
rb2.setBounds(80,100,90,30);   
ButtonGroup btg=new ButtonGroup();   
btg.add(rb1);btg.add(rb2);   
f.add(rb1);f.add(rb2);     
f.setSize(300,300);   
f.setLayout(null);   
f.setVisible(true);   
}   
public static void main(String[] args) {   
    new JavaRadioButton();   
}   
}    

Output:

  1. JList:

Another Java Swing GUI component is the JList. If you desire to display a list of items, you need to use the JList component. Like the JCheckbox, the JList component enables users to choose multiple items from the list. The JList() constructor is used to create an empty list. Another constructor, JList(Object[] listData), creates a list of the array elements. 

JList Declaration:

public class JList
extends JComponent
implements Scrollable, Accessible

Java Sample Code User Interface Window using JList:

import javax.swing.*; 
public class JavaList
{ 
    JavaList(){ 
        JFrame f= new JFrame(); 
        DefaultListModel<String> jl1 = new DefaultListModel<>(); 
          jl1.addElement("Java"); 
          jl1.addElement("C++"); 
          jl1.addElement("C"); 
          jl1.addElement("JavaScript"); 
          JList<String> list = new JList<>(jl1); 
          list.setBounds(100,100, 75,75); 
          f.add(list); 
          f.setSize(500,500); 
          f.setLayout(null); 
          f.setVisible(true); 
    } 
public static void main(String args[]) 
    { 
  new JavaList(); 
    }}  

Output:

  1. JComboBox:

Many times there is a need to include a drop-down list. The JCombBox is a combination of an editable field and a list. When the user chooses one thing from the drop-down list, it gets reflected in an editable area. Only one thing from the list can be selected. The constructor JComboBox(Object[] items) creates a drop-down list with the array elements. 

JComboBox Declaration:

public class JComboBox
extends JComponent
implements ItemSelectable, ListDataListener ActionListener, Accessible

Java Sample Code User Interface Window using JComboBox:

import javax.swing.*;   
public class JavaComboBox {    
JavaComboBox(){   
    JFrame f=new JFrame("Java Swing");   
    String language[]={"C","C++","Python","Java","HTML"};       
    JComboBox cb1=new JComboBox(language);   
    cb1.setBounds(50, 50,90,20);   
    f.add(cb1);       
    f.setLayout(null);   
    f.setSize(500,500);   
    f.setVisible(true);        
}   
public static void main(String[] args) {   
    new JavaComboBox();        
}   
}   

Output:

  1. JTextField:

The JTextField component of the Java Swing GUI enables users to modify or edit a single text line. It is present on several forms and is generally used to enter names in a single bar. The constructor, JTextField() creates an empty bar or textfield. If you desire to have some words on your text bar, you can use the constructor, JTextField(String text). 

JTextField Declaration:

public class JTextField
extends JComponent
implements SwingConstants

Java Sample Code User Interface Window using JTextFeild:

import javax.swing.*; 
class JavaTextField 
{ 
public static void main(String args[]) 
    { 
    JFrame f= new JFrame("Java Swing TextField"); 
    JTextField tf1,tf2; 
    tf1=new JTextField("Welcome to Java Programing"); 
    tf1.setBounds(50,100, 200,30); 
    tf2=new JTextField("Java Swing GUI"); 
    tf2.setBounds(50,150, 200,30); 
    f.add(tf1); f.add(tf2); 
    f.setSize(700,700); 
    f.setLayout(null); 
    f.setVisible(true); 
    } 
    }  

Output:

  1. JTextArea:

The JTextArea Java Swing GUI component is similar to the JTextField component. When you need to enter multiple text lines, the JTextArea component is utilized. On the contrary, the JTextField component allows only a single line text to enter. If you wish to create an empty textarea, use the constructor, JTextArea(). 

JTextArea Declaration:

public class JTextArea
extends JComponent

Java Sample Code User Interface Window using JTextArea:

import javax.swing.*; 
public class JavaTextArea 
{ 
    JavaTextArea(){ 
        JFrame f= new JFrame(); 
        JTextArea ta=new JTextArea("Welcome to Java Programming"); 
        ta.setBounds(10,30, 200,200); 
        f.add(ta); 
        f.setSize(300,300); 
        f.setLayout(null); 
        f.setVisible(true); 
    } 
public static void main(String args[]) 
    { 
  new JavaTextArea(); 
    }} 

Output:

  1. JPasswordField:

One of the unique and extraordinary components of the Java Swing GUI is the JPasswordField component. Passwords are required everywhere these days, while signing in to any website, accessing any application, etc. Hence, the JPasswordField incorporates a password function. The default constructor used to create password fields is JPasswordField(). 

JPasswordField Declaration:

public class JPasswordField
extends JTextField

Java Sample Code User Interface Window using JPasswordField:

import javax.swing.*;   
public class JavaPasswordField { 
    public static void main(String[] args) {   
    JFrame f=new JFrame("Java Password Field ");   
    JPasswordField value = new JPasswordField();  
    JLabel la1=new JLabel("Enter Password:");   
        la1.setBounds(20,100, 80,30);   
        value.setBounds(100,100,100,30);   
            f.add(value);  f.add(la1); 
            f.setSize(400,400);   
            f.setLayout(null);   
            f.setVisible(true);    
} 
}  

Output:

  1. JScrollBar:

The JScrollBar component in the Java Swing GUI is used for scrolling purposes. Users can insert the scrollbar vertically and horizontally. The constructor used to create the scrollbar with initial values is JScrollBar(). If you want to change the orientation, you need to specify it, like JScrollBar(int orientation). 

JScrollBar Declaration:

public class JScrollBar
extends JComponent
implements Adjustable, Accessible

Java Sample Code User Interface Window using JScrollBar:

import javax.swing.*; 
class JavaScrollBar 
{ 
JavaScrollBar(){ 
    JFrame f= new JFrame("Java Swing Scrollbar"); 
JScrollBar sb=new JScrollBar(); 
sb.setBounds(100,100, 50,100); 
f.add(sb); 
f.setSize(400,400); 
f.setLayout(null); 
f.setVisible(true); 
} 
public static void main(String args[]) 
{ 
new JavaScrollBar(); 
}}  

Output:

  1. JProgressBar:

Another Java Swing component present in the Container class is JProgressBar. It displays the progress in percentage. One of the common examples of using the JProgressBar component is to show the battery percentage of mobile phones. JProgressBar(int min, int max) is a constructor that generates a horizontal bar with a specified least and maximum values. 

JProgressBar Declaration:

public class JProgressBar
extends JComponent
implements SwingConstants, Accessible

Java Sample Code User Interface Window using JProgressBar:

import javax.swing.*;   
public class JavaProgressBar extends JFrame{   
JProgressBar jpb;   
int i=0,num=0;    
JavaProgressBar(){   
jpb=new JProgressBar(0,1500);   
jpb.setBounds(40,40,160,30);        
jpb.setValue(0);   
jpb.setStringPainted(true);   
add(jpb);   
setSize(250,150);   
setLayout(null);   
}   
public void iterate(){   
while(i<=1500){   
  jpb.setValue(i);   
  i=i+10;   
  try{Thread.sleep(130);}catch(Exception e){}   
}   
}   
public static void main(String[] args) {   
    JavaProgressBar m=new JavaProgressBar();   
    m.setVisible(true);   
    m.iterate();   
}   
}    

Output:

  1. JSlider:

JSlider component of the Java Swing GUI generates a horizontal slider used to select the value between the specified range value. The JSlider() constructor produces a slider with default values ranging from 0 t0 100, and the initial value is 50. 

JSlider Declaration:

public class JSlider
extends JComponent
implements SwingConstants, Accessible

Java Sample Code User Interface Window using JSlider:

import javax.swing.*; 
public class JavaSlider extends JFrame{ 
public JavaSlider() { 
JSlider js = new JSlider(JSlider.HORIZONTAL, 0, 50, 25); 
JPanel jp=new JPanel(); 
jp.add(js); 
add(jp); 
} 
public static void main(String s[]) { 
JavaSlider frame=new JavaSlider(); 
frame.pack(); 
frame.setVisible(true); 
} 
}  

Output:

  1. JSpinner:

Another Java Swing component to choose values between the specified range is the JSpinner. This component creates a spinner that enables users to select any particular amount between the specified boundaries. JSpinner() generates a spinner with values ranging from 0 to no limit. 

JSpinner Declaration:

public class JSpinner
extends JComponent
implements Accessible

Java Sample Code User Interface Window using JSpinner:

import javax.swing.*;   
public class JavaSpinner { 
    public static void main(String[] args) {   
    JFrame f=new JFrame("Java Swing Spinner");   
    SpinnerModel sm = 
            new SpinnerNumberModel(5, //initial value 
                0, //minimum value 
                7, //maximum value 
                1); //step 
    JSpinner js = new JSpinner(sm);  
            js.setBounds(100,100,50,30);   
            f.add(js);   
            f.setSize(500,500);   
            f.setLayout(null);   
            f.setVisible(true);    
} 
}  

Output:

  1. JOptionPane:

If you want a dialog box to pop-up on the screen after clicking any button, the JOPtionPane component is used. When you use the JOptionPane component, a dialog box appears with a message specified. The JOptionPane constructor creates a dialog box with a text box. To add a particular note in the dialog box, use JOptionPane(Object message). 

JOptionPane Declaration:

public class JOptionPane
extends JComponent
implements Accessible

Java Sample Code User Interface Window using JOptionPane:

import javax.swing.*; 
public class JavaOptionPane { 
JFrame f; 
JavaOptionPane(){ 
    f=new JFrame("Java Swing OptionPane"); 
    JOptionPane.showMessageDialog(f,"Hi, Welcome Here."); 
} 
public static void main(String[] args) { 
    new JavaOptionPane(); 
} 
}  

Output:

Conclusion

Java is the flexible and platform-independent programming language. Java Swing package is used to build the graphical user interface of any web application or website. We discussed the Java Swing package, its features, and the difference between the Abstract Windows Toolkit (AWT) and Java Swing. 

Later, we saw three distinct Java Swing classes, Component Class, Container Class, and JComponent Class. The Java sample code for the JFrame class shows how to create frames in Java.

Lastly, we have gone through some significant Java Swing GUI elements, their declarations, and their respective examples. Each Java Swing GUI component is explained well with a detailed example. This article is a complete guide for Java Swing beginners. 

Recommended Articles

Exit mobile version