JOption Pane
JOption Pane
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:
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:
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
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
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]);
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:
// 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,
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
JButton b1;
Demo()
this.setLayout(null);
this.add(b1);
b1.addActionListener(this);
// Override Method
if (evt.getSource() == b1)
class MessageDialogs1 {
// Driver code
f.setResizable(false);
Output :
Java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
Demo()
this.setLayout(null);
this.add(b1);
b1.addActionListener(this);
}
// Override Method
if (evt.getSource() == b1) {
"WARNING", JOptionPane.WARNING_MESSAGE);
class MessageDialogs2 {
// Driver code
f.setResizable(false);
f.setVisible(true);
Output :
Java
// Java program to show QUESTION_MESSAGE
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
JButton b1;
Demo()
this.setLayout(null);
this.add(b1);
b1.addActionListener(this);
// Override Method
if (evt.getSource() == b1)
"Question", JOptionPane.QUESTION_MESSAGE);
}
class MessageDialogs3 {
// Driver code
f.setResizable(false);
f.setVisible(true);
}
Output :
Java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
JButton b1;
// Constructor of Demo class
Demo()
this.setLayout(null);
this.add(b1);
b1.addActionListener(this);
}
// Override Method
if (evt.getSource() == b1)
"INFORMATION",
JOptionPane.INFORMATION_MESSAGE);
class MessageDialogs4 {
// Driver code
{
// Creating Object of demo class.
f.setResizable(false);
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;
// frame
JFrame f;
// Table
JTable j;
// Constructor
JTableExamples()
// Frame initialization
f = new JFrame();
// Frame Title
f.setTitle("JTable Example");
String[][] data = {
};
// Column Names
// adding it to JScrollPane
f.add(sp);
// Frame Size
f.setSize(500, 200);
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,
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;
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
}
};
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;
}
});
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.