0% found this document useful (0 votes)
14 views30 pages

JOption Pane

JOptionPane in Java Swing is used to create various types of dialog boxes for user interaction, including message dialogs, confirm dialogs, input dialogs, and option dialogs. Each dialog type serves a specific purpose, such as displaying messages, confirming actions, collecting user input, or presenting options. The document provides examples and methods for implementing these dialog types effectively in Java applications.

Uploaded by

singhruchi3968
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views30 pages

JOption Pane

JOptionPane in Java Swing is used to create various types of dialog boxes for user interaction, including message dialogs, confirm dialogs, input dialogs, and option dialogs. Each dialog type serves a specific purpose, such as displaying messages, confirming actions, collecting user input, or presenting options. The document provides examples and methods for implementing these dialog types effectively in Java applications.

Uploaded by

singhruchi3968
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

JOptionPane:-

In Java Swing, you can use JOptionPane to create a message box. It provides various methods to show
different types of dialog boxes, such as information, warning, error, or custom messages.

n Java Swing, JOptionPane provides several types of dialog boxes to interact with the user.
These include:

1. Message Dialog: Displays a simple message to the user.


2. Confirm Dialog: Asks the user to confirm a decision (e.g., Yes/No, OK/Cancel).
3. Input Dialog: Asks the user to input some text.
4. Option Dialog: Allows the user to choose from a set of options (e.g., Yes, No, Cancel).

Here’s a breakdown of each type of dialog box and how to use them:

1. Message Dialog

Displays a simple message to the user. It can show different types of messages such as
information, warning, or error.

Example:

JOptionPane.showMessageDialog(null, "This is an information message.",


"Information",
JOptionPane.INFORMATION_MESSAGE);

 Message Types:
o JOptionPane.INFORMATION_MESSAGE: Displays an informational message.
o JOptionPane.WARNING_MESSAGE: Displays a warning message.
o JOptionPane.ERROR_MESSAGE: Displays an error message.
o JOptionPane.PLAIN_MESSAGE: Displays a plain message without any icons.
o JOptionPane.QUESTION_MESSAGE: Displays a message with a question icon.

2. Confirm Dialog

Asks the user to confirm an action, typically with options like "Yes", "No", or "Cancel."

Example:

java
Copy
int response = JOptionPane.showConfirmDialog(null, "Do you want to
continue?",
"Confirm",
JOptionPane.YES_NO_OPTION);

if (response == JOptionPane.YES_OPTION) {
System.out.println("User selected YES.");
} else if (response == JOptionPane.NO_OPTION) {
System.out.println("User selected NO.");
}

 Options:
o JOptionPane.YES_NO_OPTION: Shows "Yes" and "No" buttons.
o JOptionPane.YES_NO_CANCEL_OPTION: Shows "Yes", "No", and "Cancel"
buttons.
o JOptionPane.OK_CANCEL_OPTION: Shows "OK" and "Cancel" buttons.

3. Input Dialog

Asks the user for input, typically a text field.

Example:

java
Copy
String name = JOptionPane.showInputDialog(null, "Enter your name:",
"Input",
JOptionPane.PLAIN_MESSAGE);
if (name != null) {
System.out.println("User entered: " + name);
}

 This dialog box allows the user to type input and return it as a String.

4. Option Dialog

Displays a set of options for the user to choose from.

Example:

java
Copy
Object[] options = {"Option 1", "Option 2", "Option 3"};
int choice = JOptionPane.showOptionDialog(null, "Choose an option:",
"Option Dialog",
JOptionPane.DEFAULT_OPTION,
JOptionPane.INFORMATION_MESSAGE,
null, options, options[0]);

System.out.println("User chose: " + options[choice]);

 Options: You can define a custom list of options and set the dialog to display them. The
user can choose one of the options.
Summary of JOptionPane Dialogs:

Dialog Type Method Example Usage


Message Dialog showMessageDialog() Display a simple message.
Confirm Dialog showConfirmDialog() Ask for user confirmation (Yes/No/Cancel).
Input Dialog showInputDialog() Ask for user input (text).
Option Dialog showOptionDialog() Present custom options to the user.

Full Example Code with All Dialog Types:


java
Copy
import javax.swing.*;

public class DialogExample {


public static void main(String[] args) {
// Message Dialogs
JOptionPane.showMessageDialog(null, "This is an informational
message.",
"Information",
JOptionPane.INFORMATION_MESSAGE);

// Confirm Dialog
int confirmResponse = JOptionPane.showConfirmDialog(null, "Do you
want to save changes?",
"Confirm Save",
JOptionPane.YES_NO_OPTION);
if (confirmResponse == JOptionPane.YES_OPTION) {
System.out.println("User confirmed to save.");
}

// Input Dialog
String userName = JOptionPane.showInputDialog(null, "Enter your
name:", "User Input", JOptionPane.PLAIN_MESSAGE);
if (userName != null && !userName.isEmpty()) {
System.out.println("Hello, " + userName + "!");
}

// Option Dialog
Object[] options = {"Red", "Green", "Blue"};
int selectedColor = JOptionPane.showOptionDialog(null, "Choose a
color:",
"Color Choice",
JOptionPane.DEFAULT_OPTION,

JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);


System.out.println("User selected: " + options[selectedColor]);
}
}
Message dialogs provide information to the user. Message dialogs are
created with the JOptionPane.showMessageDialog() method.

We call the static showMessageDialog() method of the JOptionPane class


to create a message dialog. We provide the dialog’s parent, message text,
title, and message type. The message type is one of the following constants
:
1. ERROR_MESSAGE
2. WARNING_MESSAGE
3. QUESTION_MESSAGE
4. INFORMATION_MESSAGE
Methods Used :
1. setLayout(…): method helps us to set the layout of the container, often a
JPanel, to say FlowLayout, BorderLayout, GridLayout, null layout, or
whatever layout we want to add on container.
2. setBounds(…): method is used to set the location and size of
components like JButton, and is only useful if null layout is used in
JFrame.
3. setVisible(…): method is used to set the Visibility status of JFrame.
1. setVisible(true) will set JFrame visible to user.
2. setVisible(false) will set JFrame not visible to user.
4. getSource(): An event object contains a reference to the component that
generated the event. To extract that reference from the event object we
use getSource() Method.
5. add(): It is used to add components like JButton etc, to the container of
JFrame.
Below is the implementation of above discussed method to show
Message Dialogs :
 Java

// Java program to show ERROR_MESSAGE dialog

// in Java. Importing different Package.

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

class Demo extends JFrame implements ActionListener

// Declaration of object of JButton class.

JButton b1;

// Constructor of Demo class

Demo()

// Setting layout as null of JFrame.

this.setLayout(null);

// Initialization of object of "JButton" class.


b1 = new JButton("Button 1");

// Setting Bounds of a JButton.

b1.setBounds(130, 05, 100, 50);

//"this" keyword in java refers to current object.

// Adding JButton on JFrame.

this.add(b1);

// Adding Listener toJButton.

b1.addActionListener(this);

// Override Method

public void actionPerformed(ActionEvent evt)

if (evt.getSource() == b1)

// Code To popup an ERROR_MESSAGE Dialog.

JOptionPane.showMessageDialog(this, "Enter a valid Number",


"ERROR", JOptionPane.ERROR_MESSAGE);

class MessageDialogs1 {

// Driver code

public static void main(String args[])

// Creating Object of demo class.

Demo f = new Demo();

// Setting Bounds of a Frame.

f.setBounds(200, 200, 400, 300);

// Setting Resizable status of frame as false

f.setResizable(false);

// Setting Visible status of frame as true.


f.setVisible(true);

Output :

 Java

// Java program to show WARNING_MESSAGE dialog

// in Java. Importing different Package.

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

class Demo extends JFrame implements ActionListener

// Declaration of object of JButton class.


JButton b1;

// Constructor of Demo class

Demo()

// Setting layout as null of JFrame.

this.setLayout(null);

// Initialization of object of "JButton" class.

b1 = new JButton("Button 2");

// Setting Bounds of a JButton.

b1.setBounds(130, 05, 100, 50);

//"this" keyword in java refers to current object.

// Adding JButton on JFrame.

this.add(b1);

// Adding Listener toJButton.

b1.addActionListener(this);
}

// Override Method

public void actionPerformed(ActionEvent evt)

if (evt.getSource() == b1) {

// Code To popup an WARNING_MESSAGE Dialog.

JOptionPane.showMessageDialog(this, "Enter a valid String",

"WARNING", JOptionPane.WARNING_MESSAGE);

class MessageDialogs2 {

// Driver code

public static void main(String args[])

// Creating Object of demo class.


Demo f = new Demo();

// Setting Bounds of a Frame.

f.setBounds(200, 200, 400, 300);

// Setting Resizable status of frame as false

f.setResizable(false);

// Setting Visible status of frame as true.

f.setVisible(true);

Output :

 Java
// Java program to show QUESTION_MESSAGE

// dialog in Java. Importing different Package.

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

class Demo extends JFrame implements ActionListener

// Declaration of object of JButton class.

JButton b1;

// Constructor of Demo class

Demo()

// Setting layout as null of JFrame.

this.setLayout(null);

// Initialization of object of "JButton" class.

b1 = new JButton("Button 3");


// Setting Bounds of a JButton.

b1.setBounds(130, 05, 100, 50);

//"this" keyword in java refers to current object.

// Adding JButton on JFrame.

this.add(b1);

// Adding Listener toJButton.

b1.addActionListener(this);

// Override Method

public void actionPerformed(ActionEvent evt)

if (evt.getSource() == b1)

// Code TO popup a QUESTION_MESSAGE Dialog.

JOptionPane.showMessageDialog(this, "Do you want to quit",

"Question", JOptionPane.QUESTION_MESSAGE);
}

class MessageDialogs3 {

// Driver code

public static void main(String args[])

// Creating Object of demo class.

Demo f = new Demo();

// Setting Bounds of a Frame.

f.setBounds(200, 200, 400, 300);

// Setting Resizable status of frame as false

f.setResizable(false);

// Setting Visible status of frame as true.

f.setVisible(true);
}

Output :

 Java

// Java program to show INFORMATION_MESSAGE

// dialog in Java. Importing different Package.

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

class Demo extends JFrame implements ActionListener

// Declaration of object of JButton class.

JButton b1;
// Constructor of Demo class

Demo()

// Setting layout as null of JFrame.

this.setLayout(null);

// Initialization of object of "JButton" class.

b1 = new JButton("Button 4");

// Setting Bounds of a JButton.

b1.setBounds(130, 05, 100, 50);

//"this" keyword in java refers to current object.

// Adding JButton on JFrame.

this.add(b1);

// Adding Listener toJButton.

b1.addActionListener(this);

}
// Override Method

public void actionPerformed(ActionEvent evt)

if (evt.getSource() == b1)

// Code To popup an INFORMATION_MESSAGE Dialog.

JOptionPane.showMessageDialog(this, "You Pressed Button FOUR",

"INFORMATION",

JOptionPane.INFORMATION_MESSAGE);

class MessageDialogs4 {

// Driver code

public static void main(String args[])

{
// Creating Object of demo class.

Demo f = new Demo();

// Setting Bounds of a Frame.

f.setBounds(200, 200, 400, 300);

// Setting Resizable status of frame as false

f.setResizable(false);

// Setting Visible status of frame as true.

f.setVisible(true);

Output :
JTable:-
The JTable class is a part of Java Swing Package and is generally used to
display or edit two-dimensional data that is having both rows and columns. It
is similar to a spreadsheet. This arranges data in a tabular form.
Constructors in JTable:
1. JTable(): A table is created with empty cells.
2. JTable(int rows, int cols): Creates a table of size rows * cols.
3. JTable(Object[][] data, Object []Column): A table is created with the
specified name where []Column defines the column names.
Functions in JTable:
1. addColumn(TableColumn []column) : adds a column at the end of the
JTable.
2. clearSelection() : Selects all the selected rows and columns.
3. editCellAt(int row, int col) : edits the intersecting cell of the column
number col and row number row programmatically, if the given indices are
valid and the corresponding cell is editable.
4. setValueAt(Object value, int row, int col) : Sets the cell value as ‘value’
for the position row, col in the JTable.
Below is the program to illustrate the various methods of JTable:

 Java

// Packages to import

import javax.swing.JFrame;

import javax.swing.JScrollPane;
import javax.swing.JTable;

public class JTableExamples {

// frame

JFrame f;

// Table

JTable j;

// Constructor

JTableExamples()

// Frame initialization

f = new JFrame();

// Frame Title

f.setTitle("JTable Example");

// Data to be displayed in the JTable

String[][] data = {

{ "Kundan Kumar Jha", "4031", "CSE" },


{ "Anand Jha", "6014", "IT" }

};

// Column Names

String[] columnNames = { "Name", "Roll Number", "Department" };

// Initializing the JTable

j = new JTable(data, columnNames);

j.setBounds(30, 40, 200, 300);

// adding it to JScrollPane

JScrollPane sp = new JScrollPane(j);

f.add(sp);

// Frame Size

f.setSize(500, 200);

// Frame Visible = true

f.setVisible(true);

// Driver method
public static void main(String[] args)

new JTableExamples();

Output:

JTable:-

In Java Swing, a JTable is a component that displays data in a tabular format (rows and columns).
It is part of the javax.swing package and can be used to create tables to display and manipulate
data.
Basic Structure of JTable

A JTable is often used in conjunction with a TableModel that holds the data for the table. The
JTable component is used to display that data, and it can be customized to handle editing, sorting,

and other behaviors.

Basic Example of a JTable in Swing:

Step-by-step Breakdown:

1. Create a JTable: You define the data (rows and columns) and the table itself.
2. Set Table Model: The JTable can take a TableModel which determines how the data is
represented in the table.
3. Place the JTable in a JScrollPane: Since tables can be large, they are often placed inside
a JScrollPane to allow scrolling.

Example Code:

java
Copy
import javax.swing.*;
import javax.swing.table.DefaultTableModel;

public class JTableExample {


public static void main(String[] args) {
// Create column names
String[] columnNames = {"ID", "Name", "Age"};

// Create data for the table


Object[][] data = {
{1, "Alice", 22},
{2, "Bob", 24},
{3, "Charlie", 23},
{4, "Diana", 21}
};
// Create a DefaultTableModel with the data and column names
DefaultTableModel model = new DefaultTableModel(data, columnNames);

// Create a JTable with the model


JTable table = new JTable(model);

// Place the JTable inside a JScrollPane


JScrollPane scrollPane = new JScrollPane(table);

// Create a JFrame to display the table


JFrame frame = new JFrame("JTable Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.add(scrollPane); // Add the JScrollPane containing the JTable
frame.setVisible(true);
}
}

Key Components:

1. JTable: The main table component that is used to display data in rows and columns.
2. DefaultTableModel: A class that implements the TableModel interface. It holds the data
in the form of a two-dimensional array (rows and columns).
3. JScrollPane: A container for the JTable to provide scrolling capabilities if the table
content exceeds the visible area.
4. JFrame: The window that contains the JTable.

Customizing JTable:

1. Editable Cells:

By default, JTable allows editing of cells. If you want to prevent editing in certain columns or
cells, you can override the isCellEditable() method of the TableModel:

java
Copy
DefaultTableModel model = new DefaultTableModel(data, columnNames) {
@Override
public boolean isCellEditable(int row, int column) {
return column == 1; // Only allow editing of the "Name" column
}
};

2. Setting Cell Renderers:

You can customize how the data is displayed in the cells using TableCellRenderer:

java
Copy
table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {
@Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean
hasFocus,
int row, int column) {
// Customize cell rendering (e.g., set background color)
Component c = super.getTableCellRendererComponent(table, value,
isSelected, hasFocus, row, column);
if (value instanceof Integer && (Integer) value > 23) {
c.setBackground(Color.YELLOW); // Highlight values > 23
} else {
c.setBackground(Color.WHITE);
}
return c;
}
});

3. Adding Row and Column Data:

You can dynamically add rows or columns to the table:

java
Copy
// Adding a new row
model.addRow(new Object[]{5, "Eve", 25});

// Removing a row
model.removeRow(2); // Removes the 3rd row (index starts from 0)

Handling Events:

You can also add event listeners to the JTable for handling user actions such as selecting a row
or editing a cell. For example:

java
Copy
// Adding a listener for row selection
table.getSelectionModel().addListSelectionListener(e -> {
int selectedRow = table.getSelectedRow();
if (selectedRow != -1) {
Object selectedData = table.getValueAt(selectedRow, 1); // Get data
from "Name" column
System.out.println("Selected Name: " + selectedData);
}
});

Advanced Customization:

You can also use TableColumnModel for more advanced features, such as hiding columns, setting
column widths, and more. You can also use JTable's built-in sorting capabilities, or you can
implement custom sorting with a TableRowSorter.

Example of Sorting:

java
Copy
TableRowSorter<TableModel> sorter = new TableRowSorter<>(model);
table.setRowSorter(sorter);

Summary:
 JTable is used to display tabular data in a Swing GUI.
 DefaultTableModel provides the structure to manage rows and columns of data.
 The table is often placed inside a JScrollPane to provide scroll functionality.
 You can customize the appearance and behavior of the table by overriding methods or
using event listeners.

You might also like