CS F213 Objected Oriented Programming Labsheet 14

Spring 2024

Java Swing

Swing API is a set of extensible GUI Components to ease the developer's life to create JAVA based Front End/GUI Applications. It is build on top of AWT API and acts as a replacement of AWT API, since it has almost every control corresponding to AWT controls. Swing component follows a Model-View-Controller architecture to fulfill the following criterias.

MVC Architecture

Swing API architecture follows loosely based MVC architecture in the following manner.

  • Model represents component's data.

  • View represents visual representation of the component's data.

  • Controller takes the input from the user on the view and reflects the changes in Component's data.

  • Swing component has Model as a seperate element, while the View and Controller part are clubbed in the User Interface elements. Because of which, Swing has a pluggable look-and-feel architecture.

Swing Controls

Every SWING controls inherits properties from the following Component class hiearchy.

  1. Component: A Component is the abstract base class for the non menu user-interface controls of SWING. Component represents an object with graphical representation

  2. Container: A Container is a component that can contain other SWING components

  3. 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 SWING container

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

Method
Description

public void add(Component c)

add a component on another component.

public void setSize(int width,int height)

sets size of the component.

public void setLayout(LayoutManager m)

sets the layout manager for the component.

public void setVisible(boolean b)

sets the visibility of the component. It is by default false.

SWING UI Elements

Following is the list of commonly used JComponents while designing GUI using SWING.

#
Component
Description

1

JLabel

A JLabel object is a component for placing text in a container.

2

JButton

This class creates a labeled button.

3

JCheckBox

A JCheckBox is a graphical component that can be in either an on (true) or off (false) state.

4

JRadioButton

The JRadioButton class is a graphical component that can be in either an on (true) or off (false) state. in a group.

5

JList

A JList component presents the user with a scrolling list of text items.

6

JComboBox

A JComboBox component presents the user with a to show up menu of choices.

7

JTextField

A JTextField object is a text component that allows for the editing of a single line of text.

8

JPasswordField

A JPasswordField object is a text component specialized for password entry.

9

JTextArea

A JTextArea object is a text component that allows editing of a multiple lines of text.

10

JScrollbar

A Scrollbar control represents a scroll bar component in order to enable the user to select from range of values.

Java JFrame

The javax.swing.JFrame class is a type of container which inherits the java.awt.Frame class. JFrame works like the main window where components like labels, buttons, textfields are added to create a GUI.

Java Jpanel

The JPanel is a simplest container class. It provides space in which an application can attach any other component. It inherits the JComponents class.

It doesn't have title bar

Example

import java.awt.FlowLayout;  
import javax.swing.JButton;  
import javax.swing.JFrame;  
import javax.swing.JLabel;  
import javax.swing.JPanel;  
public class JFrameExample {  
    public static void main(String s[]) {  
        JFrame frame = new JFrame("JFrame Example");  
        JPanel panel = new JPanel();  
        panel.setLayout(new FlowLayout());  
        JLabel label = new JLabel("JFrame By Example");  
        JButton button = new JButton();  
        button.setText("Button");  
        panel.add(label);  
        panel.add(button);  
        frame.add(panel);  
        frame.setSize(200, 300);  
        frame.setLocationRelativeTo(null);  
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
        frame.setVisible(true);  
    }  
}  

Output

Java JButton

The JButton class is used to create a labeled button that has platform independent implementation. The application result in some action when the button is pushed. It inherits AbstractButton class.

Example

import javax.swing.*;    
public class ButtonExample {  
public static void main(String[] args) {  
    JFrame f=new JFrame("Button Example");  
    JButton b=new JButton("Hello");  
    b.setBounds(50,100,95,30);  
    f.add(b);  
    f.setSize(400,400);  
    f.setLayout(null);  
    f.setVisible(true);   
}  
}  

Output

Java JButton Example with ActionListener

import java.awt.event.*;  
import javax.swing.*;    
public class ButtonExample {  
public static void main(String[] args) {  
    JFrame f=new JFrame("Button Example");  
    final JTextField tf=new JTextField();  
    tf.setBounds(50,50, 250,20);  
    JButton b=new JButton("Click Here");  
    b.setBounds(50,100,195,30);  
    b.addActionListener(new ActionListener(){  
public void actionPerformed(ActionEvent e){  
            tf.setText("Author of labsheet here :)");  
        }  
    });  
    f.add(b);f.add(tf);  
    f.setSize(400,400);  
    f.setLayout(null);  
    f.setVisible(true);   
}  
}  

Output after clicking the button

Java JTextField

The object of a JTextField class is a text component that allows the editing of a single line text. It inherits JTextComponent class.

JFrame f= new JFrame("TextField Example");  
JTextField t1,t2;  
t1=new JTextField("Hi, Author again");  
t1.setBounds(50,100, 200,30);  
t2=new JTextField("ATB for Compre ;)");  
t2.setBounds(50,150, 200,30); 

Java JCheckBox

The JCheckBox class is used to create a checkbox. It is used to turn an option on (true) or off (false). Clicking on a CheckBox changes its state from "on" to "off" or from "off" to "on ".It inherits JToggleButton class.

JFrame f= new JFrame("CheckBox Example");  
JCheckBox checkBox1 = new JCheckBox("C++");  
checkBox1.setBounds(100,100, 50,50);  
JCheckBox checkBox2 = new JCheckBox("Java", true);  
checkBox2.setBounds(100,150, 50,50);  
f.add(checkBox1);  
f.add(checkBox2); 

Java JComboBox

The object of Choice class is used to show popup menu of choices. Choice selected by user is shown on the top of a menu. It inherits JComponent class.

JFrame f=new JFrame("ComboBox Example");    
String country[]={"India","Aus","U.S.A","England","Newzealand"};        
JComboBox cb=new JComboBox(country);    
cb.setBounds(50, 50,90,20);    
f.add(cb);

Java JRadioButton

The JRadioButton class is used to create a radio button. It is used to choose one option from multiple options. It is widely used in exam systems or quiz.

It should be added in ButtonGroup to select one radio button only.

JFrame f=new JFrame();     
JRadioButton r1=new JRadioButton("A) Male");    
JRadioButton r2=new JRadioButton("B) Female");    
r1.setBounds(75,50,100,30);    
r2.setBounds(75,100,100,30);    
ButtonGroup bg=new ButtonGroup();    
bg.add(r1);bg.add(r2);    
f.add(r1);f.add(r2); 

Calculator Example

Let's write a basic code using the concepts we learnt to make a calculator using Java Swing

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Calculator extends JFrame {
    private JPanel panel;
    private JTextField numField1, numField2, resultField;
    private JComboBox<String> operatorBox;
    private JButton calculateButton;

    public Calculator() {
        setTitle("Calculator");
        setSize(300, 200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        panel = new JPanel();
        panel.setLayout(new GridLayout(4, 2));

        numField1 = new JTextField();
        numField2 = new JTextField();
        resultField = new JTextField();
        resultField.setEditable(false);

        String[] operators = {"+", "-", "*", "/"};
        operatorBox = new JComboBox<>(operators);

        calculateButton = new JButton("Calculate");
        calculateButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                calculate();
            }
        });

        panel.add(new JLabel("Number 1:"));
        panel.add(numField1);
        panel.add(new JLabel("Number 2:"));
        panel.add(numField2);
        panel.add(new JLabel("Operator:"));
        panel.add(operatorBox);
        panel.add(new JLabel("Result:"));
        panel.add(resultField);

        add(panel, BorderLayout.CENTER);
        add(calculateButton, BorderLayout.SOUTH);
    }

    private void calculate() {
        try {
            double num1 = Double.parseDouble(numField1.getText());
            double num2 = Double.parseDouble(numField2.getText());
            String operator = (String) operatorBox.getSelectedItem();
            double result;

            switch (operator) {
                case "+":
                    result = num1 + num2;
                    break;
                case "-":
                    result = num1 - num2;
                    break;
                case "*":
                    result = num1 * num2;
                    break;
                case "/":
                    if (num2 == 0) {
                        resultField.setText("Error: Division by zero!");
                        return;
                    }
                    result = num1 / num2;
                    break;
                default:
                    resultField.setText("Error: Invalid operator!");
                    return;
            }

            resultField.setText(String.valueOf(result));
        } catch (NumberFormatException ex) {
            resultField.setText("Error: Invalid input!");
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new Calculator().setVisible(true);
            }
        });
    }
}

Output

Now you have an idea how Java Swing works, you can add multiple things like JTable, JList, JScrollBar, JSlider, JProgressBar, JScrollPane etc to make your GUI more attractive and functional.

Exercises

Create a Java Swing application that allows users to order food items. The application should include:

  • A JFrame as the main window.

  • A JPanel to organize the components.

  • Radio buttons to select the type of food (e.g., Pizza, Burger, Sandwich).

  • Checkboxes to select toppings or extra items.

  • Buttons to submit the order and reset the selections.

Requirements:

  • When the user selects a type of food using radio buttons, the corresponding toppings or extra items should be displayed as checkboxes.

  • The user should be able to select multiple checkboxes for toppings or extra items.

  • Implement functionality for submitting the order. When the user clicks the "Order" button, display a message showing the selected food type along with the selected toppings or extra items.

  • Implement functionality for resetting the selections. When the user clicks the "Reset" button, clear the selection of radio buttons and checkboxes.

Expected Output

Last updated