0% found this document useful (0 votes)
4 views

What is Java Swing

Java Swing is a part of Java Foundation Classes (JFC) used for creating window-based applications with a rich set of GUI components. It allows developers to create interactive user interfaces using components like buttons, labels, text fields, and more, while also providing event handling capabilities. The document includes examples of creating basic windows, adding components, and handling events in Java Swing applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

What is Java Swing

Java Swing is a part of Java Foundation Classes (JFC) used for creating window-based applications with a rich set of GUI components. It allows developers to create interactive user interfaces using components like buttons, labels, text fields, and more, while also providing event handling capabilities. The document includes examples of creating basic windows, adding components, and handling events in Java Swing applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

What is Java Swing?

Swing is a part of Java Foundation Classes (JFC) used to create window-based


applications. It is built on top of AWT (Abstract Window Toolkit) but provides more
powerful and flexible GUI components.

JFRAME

We can add and desing the components on the frame

The frame is called as main object

We sub objects like

Button

Label

Textbox

Radio button

Checkbox

Dropdownbox

Jtable

JfileChooser

Steps to design

1)firsr declare the objects like frame lables textbox

2)add objects to frame

3)add event handler to the objects

4)define event method and write the logic for events

Click

Double click
Mouseup

Mouse down

Keyboardevents

Getting Started
1. Creating a Basic Window (JFrame)
import javax.swing.JFrame;

public class BasicWindow {


public static void main(String[] args) {
JFrame frame = new JFrame("My First Swing App");
frame.setSize(400, 300); // width, height
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true); // Show the frame
}
}

Adding Components
2. Adding a Button (JButton)
import javax.swing.*;

public class ButtonExample {


public static void main(String[] args) {
JFrame frame = new JFrame("Button Example");
JButton button = new JButton("Click Me");

button.setBounds(130, 100, 100, 40); // x, y, width, height

frame.add(button);
frame.setSize(400, 300);
frame.setLayout(null); // No layout manager
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Event Handling
. Responding to Button Clicks
import javax.swing.*;
import java.awt.event.*;

public class ButtonClick {


public static void main(String[] args) {
JFrame frame = new JFrame("Event Handling");
JButton button = new JButton("Click Me");

button.setBounds(120, 100, 120, 40);

button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "Button Clicked!");
}
});

frame.add(button);
frame.setSize(400, 300);
frame.setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

More Components
4. Using TextField and Label
import javax.swing.*;

public class TextFieldExample {


public static void main(String[] args) {
JFrame frame = new JFrame("TextField Example");

JLabel label = new JLabel("Enter Name:");


label.setBounds(50, 50, 100, 30);

JTextField textField = new JTextField();


textField.setBounds(150, 50, 150, 30);

frame.add(label);
frame.add(textField);
frame.setSize(400, 200);
frame.setLayout(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
🧩 Layout Managers
5. Using FlowLayout
import javax.swing.*;
import java.awt.*;

public class FlowLayoutExample {


public static void main(String[] args) {
JFrame frame = new JFrame("FlowLayout Example");
frame.setLayout(new FlowLayout());

frame.add(new JButton("1"));
frame.add(new JButton("2"));
frame.add(new JButton("3"));

frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

📚 Summary of Common Swing Components


Component Class Name Description
Window JFrame Top-level window
Button JButton A push button
Label JLabel A text label
TextBox JTextField Single-line text input
TextArea JTextArea Multi-line text area
Panel JPanel A container to group components
ComboBox JComboBox Dropdown list
List JList Selectable list
Menu JMenu, JMenuBar Menu bar

Here's a complete set of Java Swing examples demonstrating how to use:

 ✅ Check Box
 🔘 Radio Button
 🔽 Drop-down Box (ComboBox)
 📋 List Box (JList)
 ⚠️Alert Box (JOptionPane)
Each example is minimal, functional, and can be copied directly into your IDE (like IntelliJ
or Eclipse).

✅ 1. Check Box Example


import javax.swing.*;

public class CheckBoxExample {


public static void main(String[] args) {
JFrame frame = new JFrame("CheckBox Example");

JCheckBox java = new JCheckBox("Java");


java.setBounds(50, 50, 100, 30);

JCheckBox python = new JCheckBox("Python");


python.setBounds(50, 80, 100, 30);

frame.add(java);
frame.add(python);

frame.setSize(300, 200);
frame.setLayout(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

🔘 2. Radio Button Example


import javax.swing.*;

public class RadioButtonExample {


public static void main(String[] args) {
JFrame frame = new JFrame("RadioButton Example");

JRadioButton male = new JRadioButton("Male");


male.setBounds(50, 50, 100, 30);

JRadioButton female = new JRadioButton("Female");


female.setBounds(50, 80, 100, 30);

ButtonGroup group = new ButtonGroup(); // Only one can be selected


group.add(male);
group.add(female);

frame.add(male);
frame.add(female);

frame.setSize(300, 200);
frame.setLayout(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

🔽 3. Drop-down Box (JComboBox) Example


import javax.swing.*;

public class ComboBoxExample {


public static void main(String[] args) {
JFrame frame = new JFrame("ComboBox Example");

String[] languages = {"Java", "Python", "C++", "JavaScript"};


JComboBox<String> comboBox = new JComboBox<>(languages);
comboBox.setBounds(50, 50, 150, 30);

frame.add(comboBox);

frame.setSize(300, 200);
frame.setLayout(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

📋 4. List Box (JList) Example


import javax.swing.*;

public class ListBoxExample {


public static void main(String[] args) {
JFrame frame = new JFrame("ListBox Example");

String[] courses = {"BCA", "BBA", "B.Tech", "MBA"};


JList<String> list = new JList<>(courses);
list.setBounds(50, 50, 100, 100);

frame.add(list);

frame.setSize(300, 200);
frame.setLayout(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

⚠️5. Alert Box (JOptionPane) Example


import javax.swing.*;

public class AlertBoxExample {


public static void main(String[] args) {
JFrame frame = new JFrame("Alert Box Example");

JButton button = new JButton("Show Alert");


button.setBounds(100, 100, 150, 40);

button.addActionListener(e -> {
JOptionPane.showMessageDialog(frame, "This is an alert box!",
"Alert", JOptionPane.WARNING_MESSAGE);
});

frame.add(button);

frame.setSize(350, 250);
frame.setLayout(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

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

public class FullFormExample {


public static void main(String[] args) {
JFrame frame = new JFrame("Full Swing Form");

// ===== Checkboxes =====


JLabel langLabel = new JLabel("Languages Known:");
langLabel.setBounds(20, 20, 150, 25);

JCheckBox javaCB = new JCheckBox("Java");


javaCB.setBounds(20, 50, 100, 25);

JCheckBox pythonCB = new JCheckBox("Python");


pythonCB.setBounds(120, 50, 100, 25);

// ===== Radio Buttons =====


JLabel genderLabel = new JLabel("Gender:");
genderLabel.setBounds(20, 90, 150, 25);

JRadioButton maleRB = new JRadioButton("Male");


maleRB.setBounds(20, 120, 100, 25);

JRadioButton femaleRB = new JRadioButton("Female");


femaleRB.setBounds(120, 120, 100, 25);
ButtonGroup genderGroup = new ButtonGroup();
genderGroup.add(maleRB);
genderGroup.add(femaleRB);

// ===== ComboBox (Dropdown) =====


JLabel countryLabel = new JLabel("Select Country:");
countryLabel.setBounds(20, 160, 150, 25);

String[] countries = {"India", "USA", "UK", "Canada"};


JComboBox<String> countryCombo = new JComboBox<>(countries);
countryCombo.setBounds(20, 190, 150, 25);

// ===== ListBox =====


JLabel courseLabel = new JLabel("Select Course:");
courseLabel.setBounds(20, 230, 150, 25);

String[] courses = {"BCA", "BBA", "B.Tech", "MBA"};


JList<String> courseList = new JList<>(courses);
JScrollPane listScroll = new JScrollPane(courseList);
listScroll.setBounds(20, 260, 150, 60);

// ===== Submit Button =====


JButton submitBtn = new JButton("Submit");
submitBtn.setBounds(100, 340, 100, 30);

// ===== Button Action =====


submitBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
StringBuilder message = new StringBuilder();

// Get languages
message.append("Languages Known: ");
if (javaCB.isSelected()) message.append("Java ");
if (pythonCB.isSelected()) message.append("Python ");
message.append("\n");

// Gender
message.append("Gender: ");
if (maleRB.isSelected()) message.append("Male\n");
else if (femaleRB.isSelected()) message.append("Female\n");

// Country
message.append("Country:
").append(countryCombo.getSelectedItem()).append("\n");
// Course
message.append("Course: ").append(courseList.getSelectedValue()).append("\
n");

// Show alert
JOptionPane.showMessageDialog(frame, message.toString(), "Submitted Info",
JOptionPane.INFORMATION_MESSAGE);
}
});

// ===== Add to Frame =====


frame.add(langLabel);
frame.add(javaCB);
frame.add(pythonCB);

frame.add(genderLabel);
frame.add(maleRB);
frame.add(femaleRB);

frame.add(countryLabel);
frame.add(countryCombo);

frame.add(courseLabel);
frame.add(listScroll);

frame.add(submitBtn);

// ===== Frame Settings =====


frame.setSize(400, 450);
frame.setLayout(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Full example with event handling

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

public class FullFormExample {

public static void main(String[] args) {

JFrame frame = new JFrame("Full Swing Form");

// ===== Checkboxes =====

JLabel langLabel = new JLabel("Languages Known:");

langLabel.setBounds(20, 20, 150, 25);

JCheckBox javaCB = new JCheckBox("Java");

javaCB.setBounds(20, 50, 100, 25);

JCheckBox pythonCB = new JCheckBox("Python");

pythonCB.setBounds(120, 50, 100, 25);

// ===== Radio Buttons =====

JLabel genderLabel = new JLabel("Gender:");

genderLabel.setBounds(20, 90, 150, 25);

JRadioButton maleRB = new JRadioButton("Male");

maleRB.setBounds(20, 120, 100, 25);

JRadioButton femaleRB = new JRadioButton("Female");

femaleRB.setBounds(120, 120, 100, 25);


ButtonGroup genderGroup = new ButtonGroup();

genderGroup.add(maleRB);

genderGroup.add(femaleRB);

// ===== ComboBox (Dropdown) =====

JLabel countryLabel = new JLabel("Select Country:");

countryLabel.setBounds(20, 160, 150, 25);

String[] countries = {"India", "USA", "UK", "Canada"};

JComboBox<String> countryCombo = new JComboBox<>(countries);

countryCombo.setBounds(20, 190, 150, 25);

// ===== ListBox =====

JLabel courseLabel = new JLabel("Select Course:");

courseLabel.setBounds(20, 230, 150, 25);

String[] courses = {"BCA", "BBA", "B.Tech", "MBA"};

JList<String> courseList = new JList<>(courses);

JScrollPane listScroll = new JScrollPane(courseList);

listScroll.setBounds(20, 260, 150, 60);

// ===== Submit Button =====

JButton submitBtn = new JButton("Submit");

submitBtn.setBounds(100, 340, 100, 30);


// ===== Button Action =====

submitBtn.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

StringBuilder message = new StringBuilder();

// Get languages

message.append("Languages Known: ");

if (javaCB.isSelected()) message.append("Java ");

if (pythonCB.isSelected()) message.append("Python ");

message.append("\n");

// Gender

message.append("Gender: ");

if (maleRB.isSelected()) message.append("Male\n");

else if (femaleRB.isSelected()) message.append("Female\n");

// Country

message.append("Country: ").append(countryCombo.getSelectedItem()).append("\n");

// Course

message.append("Course: ").append(courseList.getSelectedValue()).append("\n");

// Show alert

JOptionPane.showMessageDialog(frame, message.toString(), "Submitted Info",


JOptionPane.INFORMATION_MESSAGE);
}

});

// ===== Add to Frame =====

frame.add(langLabel);

frame.add(javaCB);

frame.add(pythonCB);

frame.add(genderLabel);

frame.add(maleRB);

frame.add(femaleRB);

frame.add(countryLabel);

frame.add(countryCombo);

frame.add(courseLabel);

frame.add(listScroll);

frame.add(submitBtn);

// ===== Frame Settings =====

frame.setSize(400, 450);

frame.setLayout(null);

frame.setVisible(true);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

Calculator app

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class CalculatorSwingApp {

// Frame components

JFrame frame;

JTextField textField;

double first, second, result;

String operator;

public CalculatorSwingApp() {

frame = new JFrame("Swing Calculator");

textField = new JTextField();

textField.setEditable(false);

textField.setFont(new Font("Arial", Font.BOLD, 20));

// Button labels

String[] buttonLabels = {
"7", "8", "9", "/",

"4", "5", "6", "*",

"1", "2", "3", "-",

"0", ".", "=", "+"

};

// Panel for buttons

JPanel panel = new JPanel();

panel.setLayout(new GridLayout(4, 4, 10, 10));

for (String label : buttonLabels) {

JButton button = new JButton(label);

button.setFont(new Font("Arial", Font.BOLD, 18));

button.addActionListener(new ButtonClickListener());

panel.add(button);

// Frame layout

frame.setLayout(new BorderLayout());

frame.add(textField, BorderLayout.NORTH);

frame.add(panel, BorderLayout.CENTER);

frame.setSize(300, 400);

frame.setVisible(true);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

// Event handling logic

private class ButtonClickListener implements ActionListener {

public void actionPerformed(ActionEvent e) {

String command = e.getActionCommand();

if ((command.charAt(0) >= '0' && command.charAt(0) <= '9') || command.equals(".")) {

textField.setText(textField.getText() + command);

} else if (command.equals("=")) {

try {

second = Double.parseDouble(textField.getText());

switch (operator) {

case "+":

result = first + second;

break;

case "-":

result = first - second;

break;

case "*":

result = first * second;

break;

case "/":

if (second == 0) {
JOptionPane.showMessageDialog(frame, "Cannot divide by zero!");

textField.setText("");

return;

result = first / second;

break;

textField.setText("" + result);

} catch (NumberFormatException ex) {

JOptionPane.showMessageDialog(frame, "Invalid input!");

textField.setText("");

} else {

try {

first = Double.parseDouble(textField.getText());

operator = command;

textField.setText("");

} catch (NumberFormatException ex) {

JOptionPane.showMessageDialog(frame, "Enter a number first");

textField.setText("");

}
}

public static void main(String[] args) {

new CalculatorSwingApp();

Example

Here's a simple Java Swing example that adds two numbers entered by the user and
displays the result when a button is clicked.

🧮 Java Swing Example: Addition of Two Numbers


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

public class AddTwoNumbers {


public static void main(String[] args) {
// Create a new frame
JFrame frame = new JFrame("Addition of Two Numbers");

// Create components
JLabel label1 = new JLabel("Enter First Number:");
label1.setBounds(30, 40, 150, 30);

JTextField textField1 = new JTextField();


textField1.setBounds(180, 40, 150, 30);

JLabel label2 = new JLabel("Enter Second Number:");


label2.setBounds(30, 80, 150, 30);

JTextField textField2 = new JTextField();


textField2.setBounds(180, 80, 150, 30);

JButton button = new JButton("Add");


button.setBounds(120, 130, 100, 30);

JLabel resultLabel = new JLabel("Result:");


resultLabel.setBounds(30, 180, 300, 30);
// Add action listener to button
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
int num1 = Integer.parseInt(textField1.getText());
int num2 = Integer.parseInt(textField2.getText());
int sum = num1 + num2;
resultLabel.setText("Result: " + sum);
} catch (NumberFormatException ex) {
resultLabel.setText("Please enter valid numbers.");
}
}
});

// Add components to the frame


frame.add(label1);
frame.add(textField1);
frame.add(label2);
frame.add(textField2);
frame.add(button);
frame.add(resultLabel);

// Frame settings
frame.setSize(400, 300);
frame.setLayout(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

You might also like