Swing
Java's standard GUI toolkit. Provides rich UI components through lightweight component architecture. Features appearance customization via Look & Feel, mature APIs, and extensive documentation. Widely used in legacy applications.
GitHub Overview
openjdk/jdk
JDK main-line development https://openjdk.org/projects/jdk
Topics
Star History
Desktop Framework
Swing
Overview
Swing is Java's standard GUI (Graphical User Interface) toolkit, bundled with Java SE (Standard Edition) as the framework for desktop application development. Introduced in 1997, it has served as the core of Java desktop application development for many years.
Details
As of 2025, Swing continues to be supported in the latest Java versions including Java 21 LTS, and remains an important technology in enterprise environments. Swing is a rich UI component library built on top of AWT (Abstract Window Toolkit).
Key features of Swing:
- 100% Pure Java: Platform-independent pure Java implementation
- Rich Components: Diverse UI components like JButton, JLabel, JTable, JTree, JList, etc.
- Pluggable Look & Feel: Multiple appearance themes including Metal, Nimbus, and system native
- MVC Architecture: Adoption of Model-View-Controller design pattern
- Event-Driven Model: Comprehensive event handling with ActionListener, MouseListener, etc.
- Layout Managers: Flexible layout systems like BorderLayout, GridLayout, FlowLayout
- Customizability: Ability to create custom components and renderers
In enterprise development, Swing is utilized in the following areas:
- Business management systems (ERP, CRM)
- Development tools (IDEs, database management tools)
- Scientific computing applications
- Financial system frontends
- Embedded system GUIs
While adoption for new projects has decreased due to modern UI/UX trends, the prevalence of web technologies, and JavaFX promotion, it remains an important technology for maintaining and extending existing systems.
Pros and Cons
Pros
- Standard inclusion: Bundled with Java SE, no additional installation or licensing required
- Stability: Extremely stable operation guaranteed by over 25 years of usage history
- Platform independence: Complete realization of "Write Once, Run Anywhere"
- Rich components: Over 100 standard UI components provided
- Enterprise track record: Long-term operational experience in large corporations and financial institutions
- Learning resources: Massive collection of books, tutorials, and sample code
- Customizability: Advanced customization of Look & Feel and custom components
- Debugging environment: Excellent IDE support and Java debugging capabilities
Cons
- Classical design: Difficult to support modern flat design and material design
- Performance: Heavier operation compared to native applications
- High DPI support: Display issues on 4K and high-resolution displays
- Development efficiency: Verbose code writing compared to modern UI frameworks
- Reduced priority: Stagnation of new feature development in Oracle/OpenJDK community
- Talent market: Tendency to avoid learning and adoption among young developers
- Mobile incompatibility: No support for mobile devices like smartphones and tablets
Reference Links
- Oracle Swing Tutorial
- Java 21 Swing API Documentation
- OpenJDK Swing Project
- Java Desktop Application Development Guide
- Swing Design Guidelines
- Oracle Java SE Downloads
Code Examples
Basic Swing Application
// HelloWorldSwing.java - Basic Swing application
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class HelloWorldSwing extends JFrame {
private JLabel statusLabel;
private int clickCount = 0;
public HelloWorldSwing() {
initializeGUI();
}
private void initializeGUI() {
// Frame basic settings
setTitle("Hello World - Swing Application");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
// Header panel
JPanel headerPanel = new JPanel();
headerPanel.setBackground(new Color(70, 130, 180));
headerPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
JLabel titleLabel = new JLabel("Hello, Swing World!", SwingConstants.CENTER);
titleLabel.setFont(new Font("Arial", Font.BOLD, 24));
titleLabel.setForeground(Color.WHITE);
headerPanel.add(titleLabel);
// Main content panel
JPanel mainPanel = new JPanel(new GridLayout(3, 1, 10, 10));
mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
// System information display
JPanel infoPanel = new JPanel(new GridLayout(3, 2, 5, 5));
infoPanel.setBorder(BorderFactory.createTitledBorder("System Information"));
infoPanel.add(new JLabel("Java Version:"));
infoPanel.add(new JLabel(System.getProperty("java.version")));
infoPanel.add(new JLabel("OS:"));
infoPanel.add(new JLabel(System.getProperty("os.name")));
infoPanel.add(new JLabel("Look & Feel:"));
infoPanel.add(new JLabel(UIManager.getLookAndFeel().getName()));
// Button panel
JPanel buttonPanel = new JPanel(new FlowLayout());
buttonPanel.setBorder(BorderFactory.createTitledBorder("Actions"));
JButton helloButton = new JButton("Say Hello");
helloButton.setPreferredSize(new Dimension(120, 30));
helloButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
clickCount++;
JOptionPane.showMessageDialog(
HelloWorldSwing.this,
"Hello! This is the " + clickCount + " time(s) clicked.",
"Greeting",
JOptionPane.INFORMATION_MESSAGE
);
updateStatus("Hello button clicked (" + clickCount + " times)");
}
});
JButton exitButton = new JButton("Exit");
exitButton.setPreferredSize(new Dimension(120, 30));
exitButton.addActionListener(e -> {
int result = JOptionPane.showConfirmDialog(
this,
"Do you want to exit the application?",
"Confirmation",
JOptionPane.YES_NO_OPTION
);
if (result == JOptionPane.YES_OPTION) {
System.exit(0);
}
});
buttonPanel.add(helloButton);
buttonPanel.add(exitButton);
// Status panel
statusLabel = new JLabel("Ready");
statusLabel.setBorder(BorderFactory.createLoweredBevelBorder());
// Layout arrangement
mainPanel.add(infoPanel);
mainPanel.add(buttonPanel);
add(headerPanel, BorderLayout.NORTH);
add(mainPanel, BorderLayout.CENTER);
add(statusLabel, BorderLayout.SOUTH);
// Window size and position
setSize(500, 400);
setLocationRelativeTo(null);
setResizable(true);
// Initial state setup
updateStatus("Application started");
}
private void updateStatus(String message) {
statusLabel.setText(message);
// Return to default message after 3 seconds
Timer timer = new Timer(3000, e -> statusLabel.setText("Ready"));
timer.setRepeats(false);
timer.start();
}
public static void main(String[] args) {
// Set system Look & Feel
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeel());
} catch (Exception e) {
e.printStackTrace();
}
// Execute on EDT (Event Dispatch Thread)
SwingUtilities.invokeLater(() -> {
new HelloWorldSwing().setVisible(true);
});
}
}
Advanced Layout Management and MVC Pattern
// DataManagementApp.java - MVC pattern and layout management implementation
import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;
public class DataManagementApp extends JFrame {
private PersonTableModel tableModel;
private JTable table;
private JTextField nameField, ageField, departmentField;
private JLabel statusLabel;
public DataManagementApp() {
initializeGUI();
setupData();
}
private void initializeGUI() {
setTitle("Data Management Application - Swing MVC Example");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
// Create menu bar
createMenuBar();
// Create main panel
JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
// Top: Input form
JPanel inputPanel = createInputPanel();
// Center: Data table
JPanel tablePanel = createTablePanel();
// Bottom: Status bar
statusLabel = new JLabel("Ready");
statusLabel.setBorder(BorderFactory.createLoweredBevelBorder());
mainPanel.add(inputPanel, BorderLayout.NORTH);
mainPanel.add(tablePanel, BorderLayout.CENTER);
add(mainPanel, BorderLayout.CENTER);
add(statusLabel, BorderLayout.SOUTH);
setSize(800, 600);
setLocationRelativeTo(null);
}
private void createMenuBar() {
JMenuBar menuBar = new JMenuBar();
// File menu
JMenu fileMenu = new JMenu("File");
fileMenu.add(createMenuItem("New", e -> clearForm()));
fileMenu.add(createMenuItem("Export Data", e -> exportData()));
fileMenu.addSeparator();
fileMenu.add(createMenuItem("Exit", e -> System.exit(0)));
// Edit menu
JMenu editMenu = new JMenu("Edit");
editMenu.add(createMenuItem("Select All", e -> table.selectAll()));
editMenu.add(createMenuItem("Clear Selection", e -> table.clearSelection()));
// View menu
JMenu viewMenu = new JMenu("View");
JCheckBoxMenuItem showGridMenuItem = new JCheckBoxMenuItem("Show Grid", true);
showGridMenuItem.addActionListener(e -> table.setShowGrid(showGridMenuItem.isSelected()));
viewMenu.add(showGridMenuItem);
menuBar.add(fileMenu);
menuBar.add(editMenu);
menuBar.add(viewMenu);
setJMenuBar(menuBar);
}
private JMenuItem createMenuItem(String text, java.awt.event.ActionListener listener) {
JMenuItem item = new JMenuItem(text);
item.addActionListener(listener);
return item;
}
private JPanel createInputPanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createTitledBorder("Employee Information Input"));
// Input fields panel
JPanel fieldsPanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(5, 5, 5, 5);
gbc.anchor = GridBagConstraints.WEST;
// Name field
gbc.gridx = 0; gbc.gridy = 0;
fieldsPanel.add(new JLabel("Name:"), gbc);
gbc.gridx = 1; gbc.fill = GridBagConstraints.HORIZONTAL;
nameField = new JTextField(15);
fieldsPanel.add(nameField, gbc);
// Age field
gbc.gridx = 2; gbc.fill = GridBagConstraints.NONE;
fieldsPanel.add(new JLabel("Age:"), gbc);
gbc.gridx = 3; gbc.fill = GridBagConstraints.HORIZONTAL;
ageField = new JTextField(5);
fieldsPanel.add(ageField, gbc);
// Department field
gbc.gridx = 4; gbc.fill = GridBagConstraints.NONE;
fieldsPanel.add(new JLabel("Department:"), gbc);
gbc.gridx = 5; gbc.fill = GridBagConstraints.HORIZONTAL;
departmentField = new JTextField(10);
fieldsPanel.add(departmentField, gbc);
// Button panel
JPanel buttonPanel = new JPanel(new FlowLayout());
JButton addButton = new JButton("Add");
addButton.addActionListener(this::addPerson);
JButton updateButton = new JButton("Update");
updateButton.addActionListener(this::updatePerson);
JButton deleteButton = new JButton("Delete");
deleteButton.addActionListener(this::deletePerson);
JButton clearButton = new JButton("Clear");
clearButton.addActionListener(e -> clearForm());
buttonPanel.add(addButton);
buttonPanel.add(updateButton);
buttonPanel.add(deleteButton);
buttonPanel.add(clearButton);
panel.add(fieldsPanel, BorderLayout.CENTER);
panel.add(buttonPanel, BorderLayout.SOUTH);
return panel;
}
private JPanel createTablePanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createTitledBorder("Employee Data"));
// Create table model
tableModel = new PersonTableModel();
table = new JTable(tableModel);
// Table settings
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.getTableHeader().setReorderingAllowed(false);
table.setRowHeight(25);
// Cell renderer settings (right-align age column)
DefaultTableCellRenderer rightRenderer = new DefaultTableCellRenderer();
rightRenderer.setHorizontalAlignment(SwingConstants.RIGHT);
table.getColumnModel().getColumn(1).setCellRenderer(rightRenderer); // Age column
// Column width adjustment
table.getColumnModel().getColumn(0).setPreferredWidth(150); // Name
table.getColumnModel().getColumn(1).setPreferredWidth(60); // Age
table.getColumnModel().getColumn(2).setPreferredWidth(120); // Department
// Table selection event
table.getSelectionModel().addListSelectionListener(e -> {
if (!e.getValueIsAdjusting()) {
int selectedRow = table.getSelectedRow();
if (selectedRow >= 0) {
Person person = tableModel.getPersonAt(selectedRow);
nameField.setText(person.getName());
ageField.setText(String.valueOf(person.getAge()));
departmentField.setText(person.getDepartment());
}
}
});
JScrollPane scrollPane = new JScrollPane(table);
panel.add(scrollPane, BorderLayout.CENTER);
return panel;
}
private void addPerson(ActionEvent e) {
try {
String name = nameField.getText().trim();
String ageText = ageField.getText().trim();
String department = departmentField.getText().trim();
if (name.isEmpty() || ageText.isEmpty() || department.isEmpty()) {
showError("Please fill in all fields.");
return;
}
int age = Integer.parseInt(ageText);
if (age < 0 || age > 150) {
showError("Please enter an age between 0 and 150.");
return;
}
Person person = new Person(name, age, department);
tableModel.addPerson(person);
clearForm();
updateStatus("Added new employee: " + name);
} catch (NumberFormatException ex) {
showError("Please enter a valid number for age.");
}
}
private void updatePerson(ActionEvent e) {
int selectedRow = table.getSelectedRow();
if (selectedRow < 0) {
showError("Please select a row to update.");
return;
}
try {
String name = nameField.getText().trim();
String ageText = ageField.getText().trim();
String department = departmentField.getText().trim();
if (name.isEmpty() || ageText.isEmpty() || department.isEmpty()) {
showError("Please fill in all fields.");
return;
}
int age = Integer.parseInt(ageText);
Person person = new Person(name, age, department);
tableModel.updatePerson(selectedRow, person);
clearForm();
updateStatus("Updated employee information: " + name);
} catch (NumberFormatException ex) {
showError("Please enter a valid number for age.");
}
}
private void deletePerson(ActionEvent e) {
int selectedRow = table.getSelectedRow();
if (selectedRow < 0) {
showError("Please select a row to delete.");
return;
}
Person person = tableModel.getPersonAt(selectedRow);
int result = JOptionPane.showConfirmDialog(
this,
"Delete \"" + person.getName() + "\"?",
"Delete Confirmation",
JOptionPane.YES_NO_OPTION
);
if (result == JOptionPane.YES_OPTION) {
tableModel.removePerson(selectedRow);
clearForm();
updateStatus("Deleted employee: " + person.getName());
}
}
private void clearForm() {
nameField.setText("");
ageField.setText("");
departmentField.setText("");
table.clearSelection();
}
private void exportData() {
StringBuilder sb = new StringBuilder();
sb.append("Name,Age,Department\n");
for (Person person : tableModel.getAllPersons()) {
sb.append(person.getName()).append(",")
.append(person.getAge()).append(",")
.append(person.getDepartment()).append("\n");
}
JTextArea textArea = new JTextArea(sb.toString());
textArea.setEditable(false);
textArea.setFont(new Font("Monospaced", Font.PLAIN, 12));
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setPreferredSize(new Dimension(500, 300));
JOptionPane.showMessageDialog(this, scrollPane, "Export Data", JOptionPane.INFORMATION_MESSAGE);
}
private void setupData() {
// Add sample data
tableModel.addPerson(new Person("John Smith", 30, "Development"));
tableModel.addPerson(new Person("Jane Doe", 28, "Sales"));
tableModel.addPerson(new Person("Bob Johnson", 35, "Planning"));
tableModel.addPerson(new Person("Alice Brown", 32, "HR"));
updateStatus("Sample data loaded");
}
private void showError(String message) {
JOptionPane.showMessageDialog(this, message, "Error", JOptionPane.ERROR_MESSAGE);
}
private void updateStatus(String message) {
statusLabel.setText(message);
Timer timer = new Timer(3000, e -> statusLabel.setText("Ready"));
timer.setRepeats(false);
timer.start();
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeel());
} catch (Exception e) {
e.printStackTrace();
}
SwingUtilities.invokeLater(() -> {
new DataManagementApp().setVisible(true);
});
}
}
// Person class - Data model
class Person {
private String name;
private int age;
private String department;
public Person(String name, int age, String department) {
this.name = name;
this.age = age;
this.department = department;
}
// Getters
public String getName() { return name; }
public int getAge() { return age; }
public String getDepartment() { return department; }
// Setters
public void setName(String name) { this.name = name; }
public void setAge(int age) { this.age = age; }
public void setDepartment(String department) { this.department = department; }
}
// PersonTableModel - Table model (MVC Model)
class PersonTableModel extends AbstractTableModel {
private final String[] columnNames = {"Name", "Age", "Department"};
private final List<Person> persons = new ArrayList<>();
@Override
public int getRowCount() {
return persons.size();
}
@Override
public int getColumnCount() {
return columnNames.length;
}
@Override
public String getColumnName(int column) {
return columnNames[column];
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Person person = persons.get(rowIndex);
switch (columnIndex) {
case 0: return person.getName();
case 1: return person.getAge();
case 2: return person.getDepartment();
default: return null;
}
}
@Override
public Class<?> getColumnClass(int columnIndex) {
switch (columnIndex) {
case 0: return String.class;
case 1: return Integer.class;
case 2: return String.class;
default: return Object.class;
}
}
public void addPerson(Person person) {
persons.add(person);
fireTableRowsInserted(persons.size() - 1, persons.size() - 1);
}
public void removePerson(int rowIndex) {
persons.remove(rowIndex);
fireTableRowsDeleted(rowIndex, rowIndex);
}
public void updatePerson(int rowIndex, Person person) {
persons.set(rowIndex, person);
fireTableRowsUpdated(rowIndex, rowIndex);
}
public Person getPersonAt(int rowIndex) {
return persons.get(rowIndex);
}
public List<Person> getAllPersons() {
return new ArrayList<>(persons);
}
}
Event Handling
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class EventHandlingExample {
private JLabel counterLabel;
private int counter = 0;
public EventHandlingExample() {
createGUI();
}
private void createGUI() {
JFrame frame = new JFrame("Event Handling Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
// Counter display label
counterLabel = new JLabel("Counter: 0");
counterLabel.setFont(new Font("Arial", Font.BOLD, 16));
// Increment button
JButton incrementButton = new JButton("Increment");
incrementButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
counter++;
updateCounterLabel();
}
});
// Decrement button (using lambda)
JButton decrementButton = new JButton("Decrement");
decrementButton.addActionListener(e -> {
counter--;
updateCounterLabel();
});
// Reset button (using method reference)
JButton resetButton = new JButton("Reset");
resetButton.addActionListener(this::resetCounter);
// Add components
frame.add(counterLabel);
frame.add(incrementButton);
frame.add(decrementButton);
frame.add(resetButton);
frame.setSize(300, 150);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private void updateCounterLabel() {
counterLabel.setText("Counter: " + counter);
}
private void resetCounter(ActionEvent e) {
counter = 0;
updateCounterLabel();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new EventHandlingExample());
}
}
Data Display (JTable)
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
public class TableExample {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Table Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create table model
String[] columnNames = {"ID", "Name", "Age", "Department"};
Object[][] data = {
{1, "John Smith", 30, "Development"},
{2, "Jane Doe", 28, "Sales"},
{3, "Bob Johnson", 35, "Planning"},
{4, "Alice Brown", 32, "HR"}
};
DefaultTableModel tableModel = new DefaultTableModel(data, columnNames);
JTable table = new JTable(tableModel);
// Table settings
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.getTableHeader().setReorderingAllowed(false);
// Place in scroll pane
JScrollPane scrollPane = new JScrollPane(table);
// Button panel
JPanel buttonPanel = new JPanel(new FlowLayout());
JButton addButton = new JButton("Add");
addButton.addActionListener(e -> {
Object[] newRow = {tableModel.getRowCount() + 1, "New User", 25, "TBD"};
tableModel.addRow(newRow);
});
JButton deleteButton = new JButton("Delete");
deleteButton.addActionListener(e -> {
int selectedRow = table.getSelectedRow();
if (selectedRow != -1) {
tableModel.removeRow(selectedRow);
}
});
buttonPanel.add(addButton);
buttonPanel.add(deleteButton);
// Layout
frame.setLayout(new BorderLayout());
frame.add(scrollPane, BorderLayout.CENTER);
frame.add(buttonPanel, BorderLayout.SOUTH);
frame.setSize(500, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}
Custom Dialog
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class DialogExample {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Dialog Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridLayout(4, 1, 5, 5));
// Message dialog button
JButton messageButton = new JButton("Message Dialog");
messageButton.addActionListener(e -> {
JOptionPane.showMessageDialog(frame, "This is a message", "Information", JOptionPane.INFORMATION_MESSAGE);
});
// Confirmation dialog button
JButton confirmButton = new JButton("Confirm Dialog");
confirmButton.addActionListener(e -> {
int result = JOptionPane.showConfirmDialog(frame, "Are you sure you want to delete?", "Confirmation", JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION) {
JOptionPane.showMessageDialog(frame, "Deleted");
}
});
// Input dialog button
JButton inputButton = new JButton("Input Dialog");
inputButton.addActionListener(e -> {
String input = JOptionPane.showInputDialog(frame, "Please enter your name:", "Input", JOptionPane.QUESTION_MESSAGE);
if (input != null && !input.trim().isEmpty()) {
JOptionPane.showMessageDialog(frame, "Hello, " + input + "!");
}
});
// Custom dialog button
JButton customButton = new JButton("Custom Dialog");
customButton.addActionListener(e -> {
showCustomDialog(frame);
});
panel.add(messageButton);
panel.add(confirmButton);
panel.add(inputButton);
panel.add(customButton);
frame.add(panel);
frame.setSize(300, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
private static void showCustomDialog(JFrame parent) {
JDialog dialog = new JDialog(parent, "Custom Dialog", true);
dialog.setLayout(new BorderLayout());
// Input fields
JPanel inputPanel = new JPanel(new GridLayout(2, 2, 5, 5));
inputPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
inputPanel.add(new JLabel("Name:"));
JTextField nameField = new JTextField();
inputPanel.add(nameField);
inputPanel.add(new JLabel("Age:"));
JTextField ageField = new JTextField();
inputPanel.add(ageField);
// Button panel
JPanel buttonPanel = new JPanel(new FlowLayout());
JButton okButton = new JButton("OK");
JButton cancelButton = new JButton("Cancel");
okButton.addActionListener(e -> {
String name = nameField.getText();
String age = ageField.getText();
JOptionPane.showMessageDialog(dialog, "Name: " + name + ", Age: " + age);
dialog.dispose();
});
cancelButton.addActionListener(e -> dialog.dispose());
buttonPanel.add(okButton);
buttonPanel.add(cancelButton);
dialog.add(inputPanel, BorderLayout.CENTER);
dialog.add(buttonPanel, BorderLayout.SOUTH);
dialog.setSize(300, 150);
dialog.setLocationRelativeTo(parent);
dialog.setVisible(true);
}
}
File Operations
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
public class FileOperationExample {
private JTextArea textArea;
private JFrame frame;
public FileOperationExample() {
createGUI();
}
private void createGUI() {
frame = new JFrame("File Operation Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create menu bar
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenuItem openItem = new JMenuItem("Open");
openItem.addActionListener(this::openFile);
JMenuItem saveItem = new JMenuItem("Save");
saveItem.addActionListener(this::saveFile);
JMenuItem exitItem = new JMenuItem("Exit");
exitItem.addActionListener(e -> System.exit(0));
fileMenu.add(openItem);
fileMenu.add(saveItem);
fileMenu.addSeparator();
fileMenu.add(exitItem);
menuBar.add(fileMenu);
frame.setJMenuBar(menuBar);
// Text area
textArea = new JTextArea();
textArea.setFont(new Font("Monospaced", Font.PLAIN, 14));
JScrollPane scrollPane = new JScrollPane(textArea);
frame.add(scrollPane);
frame.setSize(600, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private void openFile(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new FileNameExtensionFilter("Text Files", "txt"));
int result = fileChooser.showOpenDialog(frame);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
textArea.setText("");
String line;
while ((line = reader.readLine()) != null) {
textArea.append(line + "\n");
}
} catch (IOException ex) {
JOptionPane.showMessageDialog(frame, "File read error: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
private void saveFile(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new FileNameExtensionFilter("Text Files", "txt"));
int result = fileChooser.showSaveDialog(frame);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
if (!file.getName().endsWith(".txt")) {
file = new File(file.getAbsolutePath() + ".txt");
}
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
writer.write(textArea.getText());
JOptionPane.showMessageDialog(frame, "File saved successfully", "Save Complete", JOptionPane.INFORMATION_MESSAGE);
} catch (IOException ex) {
JOptionPane.showMessageDialog(frame, "File save error: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
public static void main(String[] args) {
// Use system look and feel
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeel());
} catch (Exception e) {
e.printStackTrace();
}
SwingUtilities.invokeLater(() -> new FileOperationExample());
}
}