SWT (Standard Widget Toolkit)
Java GUI toolkit developed by Eclipse Foundation. Leverages native widgets for each platform to achieve OS-optimized performance and appearance. Also used as foundation technology for Eclipse IDE.
Framework
SWT (Standard Widget Toolkit)
Overview
SWT (Standard Widget Toolkit) is a Java GUI toolkit developed by the Eclipse project. It achieves platform-specific look and feel and performance by directly utilizing native OS widgets. Developed as the foundation technology for Eclipse IDE, it continues to be used in many Eclipse-based applications today.
Details
As of 2025, SWT continues to be actively developed under the Eclipse Foundation and serves as the foundation for the latest Eclipse RCP (Rich Client Platform) applications, including Eclipse IDE 2025 editions. SWT takes a fundamentally different approach from Java's Swing by leveraging native operating system widgets directly.
Key features of SWT:
- Native Widgets: Direct use of Win32 API on Windows, Cocoa on macOS, and GTK+ on Linux
- High Performance: High-speed rendering through OS native rendering engines
- Explicit Resource Management: dispose() pattern to prevent memory leaks and resource exhaustion
- Platform Integration: Complete integration with standard widgets and behaviors of each OS
- Eclipse RCP: Rich plugin architecture and professional workbench framework support
- OSGi Support: Full support for modular application development and dynamic loading
- Threading Model: Sophisticated UI thread management with Display and UI thread separation
Enterprise usage areas:
- Eclipse IDE (the most famous and comprehensive use case)
- IBM Watson Studio, IBM Notes, and IBM development tools
- SAP Development Tools and SAP GUI components
- Scientific and technical applications (NASA, research institutions, engineering software)
- Financial desktop applications and trading platforms
- Industrial control software and manufacturing systems
- Government and defense applications requiring native OS integration
However, compared to Swing and JavaFX, SWT has higher learning costs due to explicit resource management requirements, platform-specific native library dependencies, and more complex deployment scenarios. Mobile support is also limited, and the community size is relatively smaller compared to other Java GUI frameworks.
Pros and Cons
Pros
- Native performance: High-speed operation using OS native widgets with minimal overhead
- Platform integration: Natural reproduction of each OS's look, feel, and behavior patterns
- Memory efficiency: Lightweight operation with proper explicit resource management
- Eclipse RCP integration: Rich plugin architecture and professional application framework
- Enterprise track record: Proven long-term operational experience in large corporations and financial institutions
- Native functionality: Direct access to OS-specific APIs and deep system integration capabilities
- OSGi modularity: Support for sophisticated modular application architecture and dynamic loading
- Professional development: Rich development tools, debugging support, and mature ecosystem through Eclipse
- Threading model: Robust UI thread management and event handling mechanisms
- Stability: Mature, battle-tested codebase with decades of production use
Cons
- Complex resource management: Explicit dispose() required for all widgets to avoid memory leaks
- High learning cost: More complex programming model and concepts compared to Swing
- Large dependencies: Platform-specific native libraries required for deployment
- Limited community: Smaller community and fewer third-party resources compared to Swing/JavaFX
- Debugging difficulty: Complex debugging of native parts and platform-specific issues
- Distribution complexity: Platform-specific library distribution and deployment challenges
- Eclipse dependency: Strong coupling with Eclipse ecosystem and development patterns
- Mobile incompatibility: No support for mobile devices like smartphones and tablets
- Documentation gaps: Some areas lack comprehensive documentation or have outdated examples
- Deployment overhead: Additional complexity in packaging and distributing native dependencies
Reference Pages
- Eclipse SWT Official Site
- SWT Developer Guide
- SWT Snippets
- Eclipse RCP Documentation
- SWT API Reference
- Eclipse Platform Project
Code Examples
Hello World
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.SWT;
public class HelloWorldSWT {
public static void main(String[] args) {
// Create display and shell
Display display = new Display();
Shell shell = new Shell(display);
shell.setText("Hello World - SWT Application");
shell.setLayout(new FillLayout());
// Create label with styling
Label label = new Label(shell, SWT.CENTER);
label.setText("Hello, SWT World!");
label.setBackground(display.getSystemColor(SWT.COLOR_WHITE));
// Set shell size and show
shell.setSize(400, 300);
shell.open();
// Event loop - essential for SWT applications
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
// Resource cleanup - critical for preventing memory leaks
display.dispose();
}
}
Advanced Layout Management and Professional Application Structure
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.events.*;
import org.eclipse.swt.SWT;
public class ProfessionalSWTApplication {
private Display display;
private Shell shell;
private Label statusLabel;
private Text textArea;
private Table dataTable;
private int counter = 0;
public static void main(String[] args) {
new ProfessionalSWTApplication().run();
}
public void run() {
display = new Display();
createShell();
shell.open();
// Professional event loop with error handling
while (!shell.isDisposed()) {
try {
if (!display.readAndDispatch()) {
display.sleep();
}
} catch (Exception e) {
System.err.println("Error in event loop: " + e.getMessage());
e.printStackTrace();
}
}
// Cleanup
dispose();
}
private void createShell() {
shell = new Shell(display);
shell.setText("Professional SWT Application - Data Management");
shell.setLayout(new BorderLayout());
shell.setSize(800, 600);
// Create menu bar
createMenuBar();
// Create toolbar
createToolBar();
// Create main content area
createMainContent();
// Create status bar
createStatusBar();
// Center the window
Monitor primary = display.getPrimaryMonitor();
Rectangle bounds = primary.getBounds();
Rectangle rect = shell.getBounds();
int x = bounds.x + (bounds.width - rect.width) / 2;
int y = bounds.y + (bounds.height - rect.height) / 2;
shell.setLocation(x, y);
// Add close listener for proper resource cleanup
shell.addShellListener(new ShellAdapter() {
@Override
public void shellClosed(ShellEvent e) {
// Confirm exit if there are unsaved changes
MessageBox messageBox = new MessageBox(shell, SWT.ICON_QUESTION | SWT.YES | SWT.NO);
messageBox.setMessage("Are you sure you want to exit?");
messageBox.setText("Confirm Exit");
int result = messageBox.open();
e.doit = (result == SWT.YES);
}
});
}
private void createMenuBar() {
Menu menuBar = new Menu(shell, SWT.BAR);
shell.setMenuBar(menuBar);
// File menu
MenuItem fileMenuItem = new MenuItem(menuBar, SWT.CASCADE);
fileMenuItem.setText("&File");
Menu fileMenu = new Menu(shell, SWT.DROP_DOWN);
fileMenuItem.setMenu(fileMenu);
MenuItem newMenuItem = new MenuItem(fileMenu, SWT.PUSH);
newMenuItem.setText("&New\tCtrl+N");
newMenuItem.setAccelerator(SWT.CTRL + 'N');
newMenuItem.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
newDocument();
}
});
MenuItem openMenuItem = new MenuItem(fileMenu, SWT.PUSH);
openMenuItem.setText("&Open\tCtrl+O");
openMenuItem.setAccelerator(SWT.CTRL + 'O');
openMenuItem.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
openDocument();
}
});
MenuItem saveMenuItem = new MenuItem(fileMenu, SWT.PUSH);
saveMenuItem.setText("&Save\tCtrl+S");
saveMenuItem.setAccelerator(SWT.CTRL + 'S');
saveMenuItem.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
saveDocument();
}
});
new MenuItem(fileMenu, SWT.SEPARATOR);
MenuItem exitMenuItem = new MenuItem(fileMenu, SWT.PUSH);
exitMenuItem.setText("E&xit");
exitMenuItem.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
shell.close();
}
});
// Data menu
MenuItem dataMenuItem = new MenuItem(menuBar, SWT.CASCADE);
dataMenuItem.setText("&Data");
Menu dataMenu = new Menu(shell, SWT.DROP_DOWN);
dataMenuItem.setMenu(dataMenu);
MenuItem addRecordMenuItem = new MenuItem(dataMenu, SWT.PUSH);
addRecordMenuItem.setText("&Add Record");
addRecordMenuItem.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
addDataRecord();
}
});
MenuItem deleteRecordMenuItem = new MenuItem(dataMenu, SWT.PUSH);
deleteRecordMenuItem.setText("&Delete Record");
deleteRecordMenuItem.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
deleteSelectedRecord();
}
});
}
private void createToolBar() {
ToolBar toolBar = new ToolBar(shell, SWT.HORIZONTAL | SWT.FLAT);
toolBar.setLayoutData(BorderData.NORTH);
ToolItem newToolItem = new ToolItem(toolBar, SWT.PUSH);
newToolItem.setText("New");
newToolItem.setToolTipText("Create new document");
newToolItem.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
newDocument();
}
});
ToolItem openToolItem = new ToolItem(toolBar, SWT.PUSH);
openToolItem.setText("Open");
openToolItem.setToolTipText("Open existing document");
openToolItem.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
openDocument();
}
});
ToolItem saveToolItem = new ToolItem(toolBar, SWT.PUSH);
saveToolItem.setText("Save");
saveToolItem.setToolTipText("Save current document");
saveToolItem.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
saveDocument();
}
});
new ToolItem(toolBar, SWT.SEPARATOR);
ToolItem addToolItem = new ToolItem(toolBar, SWT.PUSH);
addToolItem.setText("Add Record");
addToolItem.setToolTipText("Add new data record");
addToolItem.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
addDataRecord();
}
});
ToolItem deleteToolItem = new ToolItem(toolBar, SWT.PUSH);
deleteToolItem.setText("Delete");
deleteToolItem.setToolTipText("Delete selected record");
deleteToolItem.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
deleteSelectedRecord();
}
});
}
private void createMainContent() {
// Create splitter for resizable panes
SashForm sashForm = new SashForm(shell, SWT.HORIZONTAL);
sashForm.setLayoutData(BorderData.CENTER);
// Left pane - Text editing area
Composite leftComposite = new Composite(sashForm, SWT.NONE);
leftComposite.setLayout(new GridLayout());
Label textLabel = new Label(leftComposite, SWT.NONE);
textLabel.setText("Text Content:");
textLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
textArea = new Text(leftComposite, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
textArea.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
textArea.setText("Enter your text content here...\n\nThis is a professional SWT application demonstrating:\n" +
"- Menu bar and toolbar\n" +
"- Split pane layout\n" +
"- Data table management\n" +
"- Proper resource management\n" +
"- Event handling\n" +
"- Status updates");
// Right pane - Data table
Composite rightComposite = new Composite(sashForm, SWT.NONE);
rightComposite.setLayout(new GridLayout());
Label tableLabel = new Label(rightComposite, SWT.NONE);
tableLabel.setText("Data Records:");
tableLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
dataTable = new Table(rightComposite, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI);
dataTable.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
dataTable.setHeaderVisible(true);
dataTable.setLinesVisible(true);
// Create table columns
TableColumn idColumn = new TableColumn(dataTable, SWT.LEFT);
idColumn.setText("ID");
idColumn.setWidth(50);
TableColumn nameColumn = new TableColumn(dataTable, SWT.LEFT);
nameColumn.setText("Name");
nameColumn.setWidth(120);
TableColumn valueColumn = new TableColumn(dataTable, SWT.RIGHT);
valueColumn.setText("Value");
valueColumn.setWidth(80);
TableColumn statusColumn = new TableColumn(dataTable, SWT.LEFT);
statusColumn.setText("Status");
statusColumn.setWidth(100);
// Add selection listener
dataTable.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
updateStatusForSelection();
}
});
// Set splitter weights (60% left, 40% right)
sashForm.setWeights(new int[]{60, 40});
// Add some sample data
addSampleData();
}
private void createStatusBar() {
statusLabel = new Label(shell, SWT.BORDER);
statusLabel.setLayoutData(BorderData.SOUTH);
statusLabel.setText("Ready - Professional SWT Application");
}
private void addSampleData() {
String[][] sampleData = {
{"1", "Sample Record 1", "100", "Active"},
{"2", "Sample Record 2", "250", "Inactive"},
{"3", "Sample Record 3", "175", "Active"},
{"4", "Sample Record 4", "300", "Pending"}
};
for (String[] row : sampleData) {
TableItem item = new TableItem(dataTable, SWT.NONE);
item.setText(row);
}
updateStatus("Sample data loaded - " + sampleData.length + " records");
}
private void newDocument() {
textArea.setText("");
updateStatus("New document created");
}
private void openDocument() {
FileDialog dialog = new FileDialog(shell, SWT.OPEN);
dialog.setFilterExtensions(new String[]{"*.txt", "*.*"});
dialog.setFilterNames(new String[]{"Text Files (*.txt)", "All Files (*.*)"});
String fileName = dialog.open();
if (fileName != null) {
try {
java.nio.file.Path path = java.nio.file.Paths.get(fileName);
String content = java.nio.file.Files.readString(path);
textArea.setText(content);
updateStatus("Opened: " + fileName);
} catch (Exception e) {
MessageBox errorBox = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
errorBox.setMessage("Error reading file: " + e.getMessage());
errorBox.setText("File Error");
errorBox.open();
updateStatus("Error opening file");
}
}
}
private void saveDocument() {
FileDialog dialog = new FileDialog(shell, SWT.SAVE);
dialog.setFilterExtensions(new String[]{"*.txt", "*.*"});
dialog.setFilterNames(new String[]{"Text Files (*.txt)", "All Files (*.*)"});
String fileName = dialog.open();
if (fileName != null) {
try {
java.nio.file.Path path = java.nio.file.Paths.get(fileName);
java.nio.file.Files.writeString(path, textArea.getText());
updateStatus("Saved: " + fileName);
} catch (Exception e) {
MessageBox errorBox = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
errorBox.setMessage("Error saving file: " + e.getMessage());
errorBox.setText("Save Error");
errorBox.open();
updateStatus("Error saving file");
}
}
}
private void addDataRecord() {
// Create custom dialog for data entry
Shell dialog = new Shell(shell, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);
dialog.setText("Add New Record");
dialog.setLayout(new GridLayout(2, false));
dialog.setSize(300, 200);
// Center dialog relative to parent
Rectangle parentBounds = shell.getBounds();
Rectangle dialogBounds = dialog.getBounds();
int x = parentBounds.x + (parentBounds.width - dialogBounds.width) / 2;
int y = parentBounds.y + (parentBounds.height - dialogBounds.height) / 2;
dialog.setLocation(x, y);
// Name field
new Label(dialog, SWT.NONE).setText("Name:");
Text nameText = new Text(dialog, SWT.BORDER);
nameText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
// Value field
new Label(dialog, SWT.NONE).setText("Value:");
Text valueText = new Text(dialog, SWT.BORDER);
valueText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
// Status field
new Label(dialog, SWT.NONE).setText("Status:");
Combo statusCombo = new Combo(dialog, SWT.DROP_DOWN | SWT.READ_ONLY);
statusCombo.setItems(new String[]{"Active", "Inactive", "Pending"});
statusCombo.select(0);
statusCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
// Buttons
Composite buttonComposite = new Composite(dialog, SWT.NONE);
buttonComposite.setLayout(new GridLayout(2, true));
buttonComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));
Button okButton = new Button(buttonComposite, SWT.PUSH);
okButton.setText("OK");
okButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
okButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
String name = nameText.getText().trim();
String value = valueText.getText().trim();
String status = statusCombo.getText();
if (name.isEmpty() || value.isEmpty()) {
MessageBox errorBox = new MessageBox(dialog, SWT.ICON_WARNING | SWT.OK);
errorBox.setMessage("Please fill in all fields.");
errorBox.setText("Validation Error");
errorBox.open();
return;
}
// Add to table
TableItem item = new TableItem(dataTable, SWT.NONE);
item.setText(new String[]{
String.valueOf(dataTable.getItemCount()),
name,
value,
status
});
updateStatus("Added new record: " + name);
dialog.dispose();
}
});
Button cancelButton = new Button(buttonComposite, SWT.PUSH);
cancelButton.setText("Cancel");
cancelButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
cancelButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
dialog.dispose();
}
});
dialog.open();
}
private void deleteSelectedRecord() {
int[] selectionIndices = dataTable.getSelectionIndices();
if (selectionIndices.length == 0) {
MessageBox infoBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
infoBox.setMessage("Please select one or more records to delete.");
infoBox.setText("No Selection");
infoBox.open();
return;
}
MessageBox confirmBox = new MessageBox(shell, SWT.ICON_QUESTION | SWT.YES | SWT.NO);
confirmBox.setMessage("Delete " + selectionIndices.length + " selected record(s)?");
confirmBox.setText("Confirm Deletion");
if (confirmBox.open() == SWT.YES) {
// Remove items in reverse order to maintain indices
for (int i = selectionIndices.length - 1; i >= 0; i--) {
dataTable.remove(selectionIndices[i]);
}
updateStatus("Deleted " + selectionIndices.length + " record(s)");
}
}
private void updateStatusForSelection() {
int selectionCount = dataTable.getSelectionCount();
if (selectionCount == 0) {
updateStatus("Ready");
} else if (selectionCount == 1) {
TableItem item = dataTable.getSelection()[0];
updateStatus("Selected: " + item.getText(1) + " (Value: " + item.getText(2) + ")");
} else {
updateStatus(selectionCount + " records selected");
}
}
private void updateStatus(String message) {
if (statusLabel != null && !statusLabel.isDisposed()) {
statusLabel.setText(message);
}
}
private void dispose() {
if (display != null && !display.isDisposed()) {
display.dispose();
}
}
}
Event Handling and Widget Management
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.events.*;
import org.eclipse.swt.SWT;
public class EventHandlingExample {
private int counter = 0;
private Label counterLabel;
private Display display;
private Shell shell;
public static void main(String[] args) {
new EventHandlingExample().run();
}
public void run() {
display = new Display();
createShell();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
private void createShell() {
shell = new Shell(display);
shell.setText("SWT Event Handling Example");
shell.setLayout(new GridLayout(2, false));
shell.setSize(400, 300);
// Counter display label
counterLabel = new Label(shell, SWT.NONE);
counterLabel.setText("Counter: 0");
counterLabel.setFont(display.getSystemFont());
GridData labelData = new GridData(SWT.CENTER, SWT.CENTER, true, false, 2, 1);
counterLabel.setLayoutData(labelData);
// Increment button with SelectionListener
Button incrementButton = new Button(shell, SWT.PUSH);
incrementButton.setText("Increment");
incrementButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
counter++;
updateCounterLabel();
updateStatus("Counter incremented to " + counter);
}
});
// Decrement button with anonymous listener
Button decrementButton = new Button(shell, SWT.PUSH);
decrementButton.setText("Decrement");
decrementButton.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
counter--;
updateCounterLabel();
updateStatus("Counter decremented to " + counter);
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
// Handle default selection (e.g., double-click)
widgetSelected(e);
}
});
// Reset button
Button resetButton = new Button(shell, SWT.PUSH);
resetButton.setText("Reset");
resetButton.addSelectionListener(e -> {
counter = 0;
updateCounterLabel();
updateStatus("Counter reset");
});
GridData resetData = new GridData(SWT.CENTER, SWT.CENTER, true, false, 2, 1);
resetButton.setLayoutData(resetData);
// Mouse and keyboard event handling
Text inputText = new Text(shell, SWT.BORDER);
inputText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));
inputText.setMessage("Type here and press Enter...");
inputText.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
if (e.keyCode == SWT.CR || e.keyCode == SWT.KEYPAD_CR) {
String text = ((Text) e.widget).getText();
if (!text.isEmpty()) {
MessageBox messageBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
messageBox.setMessage("You entered: " + text);
messageBox.setText("Input Received");
messageBox.open();
((Text) e.widget).setText("");
}
}
}
@Override
public void keyReleased(KeyEvent e) {
// Handle key release events if needed
}
});
inputText.addMouseListener(new MouseAdapter() {
@Override
public void mouseDoubleClick(MouseEvent e) {
((Text) e.widget).selectAll();
updateStatus("Text selected");
}
});
// Create status bar
Label statusBar = new Label(shell, SWT.BORDER);
statusBar.setText("Ready");
statusBar.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));
// Store reference for updates
shell.setData("statusBar", statusBar);
// Center window
Monitor primary = display.getPrimaryMonitor();
Rectangle bounds = primary.getBounds();
Rectangle rect = shell.getBounds();
int x = bounds.x + (bounds.width - rect.width) / 2;
int y = bounds.y + (bounds.height - rect.height) / 2;
shell.setLocation(x, y);
}
private void updateCounterLabel() {
counterLabel.setText("Counter: " + counter);
}
private void updateStatus(String message) {
Label statusBar = (Label) shell.getData("statusBar");
if (statusBar != null && !statusBar.isDisposed()) {
statusBar.setText(message);
}
}
}
Table and Data Display with Advanced Features
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.SWT;
public class AdvancedTableExample {
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setText("Advanced Table Example");
shell.setLayout(new GridLayout());
shell.setSize(700, 500);
// Create table with advanced features
Table table = new Table(shell, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI | SWT.CHECK);
table.setHeaderVisible(true);
table.setLinesVisible(true);
GridData tableData = new GridData(SWT.FILL, SWT.FILL, true, true);
tableData.heightHint = 300;
table.setLayoutData(tableData);
// Create columns with different alignments and features
TableColumn idColumn = new TableColumn(table, SWT.LEFT);
idColumn.setText("ID");
idColumn.setWidth(60);
idColumn.setResizable(true);
TableColumn nameColumn = new TableColumn(table, SWT.LEFT);
nameColumn.setText("Employee Name");
nameColumn.setWidth(150);
nameColumn.setResizable(true);
TableColumn ageColumn = new TableColumn(table, SWT.RIGHT);
ageColumn.setText("Age");
ageColumn.setWidth(80);
ageColumn.setResizable(true);
TableColumn departmentColumn = new TableColumn(table, SWT.LEFT);
departmentColumn.setText("Department");
departmentColumn.setWidth(120);
departmentColumn.setResizable(true);
TableColumn salaryColumn = new TableColumn(table, SWT.RIGHT);
salaryColumn.setText("Salary");
salaryColumn.setWidth(100);
salaryColumn.setResizable(true);
TableColumn statusColumn = new TableColumn(table, SWT.CENTER);
statusColumn.setText("Status");
statusColumn.setWidth(100);
statusColumn.setResizable(true);
// Add comprehensive sample data
String[][] employeeData = {
{"001", "John Smith", "30", "Engineering", "75000", "Active"},
{"002", "Jane Johnson", "28", "Marketing", "65000", "Active"},
{"003", "Bob Williams", "35", "Engineering", "85000", "Active"},
{"004", "Alice Brown", "32", "HR", "60000", "Active"},
{"005", "Charlie Davis", "29", "Sales", "70000", "Inactive"},
{"006", "Diana Miller", "31", "Engineering", "80000", "Active"},
{"007", "Frank Wilson", "33", "Finance", "72000", "Active"},
{"008", "Grace Taylor", "27", "Marketing", "63000", "Pending"}
};
for (String[] row : employeeData) {
TableItem item = new TableItem(table, SWT.NONE);
item.setText(row);
// Set different colors based on status
String status = row[5];
if ("Inactive".equals(status)) {
item.setBackground(display.getSystemColor(SWT.COLOR_GRAY));
} else if ("Pending".equals(status)) {
item.setBackground(display.getSystemColor(SWT.COLOR_YELLOW));
} else {
item.setBackground(display.getSystemColor(SWT.COLOR_WHITE));
}
}
// Button panel for table operations
Composite buttonComposite = new Composite(shell, SWT.NONE);
buttonComposite.setLayout(new RowLayout());
buttonComposite.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, false));
Button addButton = new Button(buttonComposite, SWT.PUSH);
addButton.setText("Add Employee");
addButton.addSelectionListener(e -> {
TableItem newItem = new TableItem(table, SWT.NONE);
newItem.setText(new String[]{
String.format("%03d", table.getItemCount()),
"New Employee",
"25",
"Unassigned",
"50000",
"Pending"
});
newItem.setBackground(display.getSystemColor(SWT.COLOR_YELLOW));
table.setSelection(newItem);
});
Button deleteButton = new Button(buttonComposite, SWT.PUSH);
deleteButton.setText("Delete Selected");
deleteButton.addSelectionListener(e -> {
int[] selectionIndices = table.getSelectionIndices();
if (selectionIndices.length > 0) {
MessageBox confirmBox = new MessageBox(shell, SWT.ICON_QUESTION | SWT.YES | SWT.NO);
confirmBox.setMessage("Delete " + selectionIndices.length + " selected item(s)?");
confirmBox.setText("Confirm Deletion");
if (confirmBox.open() == SWT.YES) {
table.remove(selectionIndices);
}
} else {
MessageBox infoBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
infoBox.setMessage("Please select items to delete.");
infoBox.setText("No Selection");
infoBox.open();
}
});
Button toggleStatusButton = new Button(buttonComposite, SWT.PUSH);
toggleStatusButton.setText("Toggle Status");
toggleStatusButton.addSelectionListener(e -> {
TableItem[] selection = table.getSelection();
for (TableItem item : selection) {
String currentStatus = item.getText(5);
String newStatus = "Active".equals(currentStatus) ? "Inactive" : "Active";
item.setText(5, newStatus);
// Update color based on new status
if ("Inactive".equals(newStatus)) {
item.setBackground(display.getSystemColor(SWT.COLOR_GRAY));
} else {
item.setBackground(display.getSystemColor(SWT.COLOR_WHITE));
}
}
});
Button selectAllButton = new Button(buttonComposite, SWT.PUSH);
selectAllButton.setText("Select All");
selectAllButton.addSelectionListener(e -> table.selectAll());
Button clearSelectionButton = new Button(buttonComposite, SWT.PUSH);
clearSelectionButton.setText("Clear Selection");
clearSelectionButton.addSelectionListener(e -> table.deselectAll());
// Information panel
Composite infoComposite = new Composite(shell, SWT.NONE);
infoComposite.setLayout(new GridLayout(3, false));
infoComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
Label totalLabel = new Label(infoComposite, SWT.NONE);
totalLabel.setText("Total: " + table.getItemCount());
Label selectedLabel = new Label(infoComposite, SWT.NONE);
selectedLabel.setText("Selected: 0");
Label checkedLabel = new Label(infoComposite, SWT.NONE);
checkedLabel.setText("Checked: 0");
// Update labels when selection changes
table.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
selectedLabel.setText("Selected: " + table.getSelectionCount());
int checkedCount = 0;
for (TableItem item : table.getItems()) {
if (item.getChecked()) {
checkedCount++;
}
}
checkedLabel.setText("Checked: " + checkedCount);
}
});
// Center window
Monitor primary = display.getPrimaryMonitor();
Rectangle bounds = primary.getBounds();
Rectangle rect = shell.getBounds();
int x = bounds.x + (bounds.width - rect.width) / 2;
int y = bounds.y + (bounds.height - rect.height) / 2;
shell.setLocation(x, y);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
}
Dialogs and Advanced UI Components
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.SWT;
public class DialogAndComponentExample {
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setText("Dialog and Component Example");
shell.setLayout(new GridLayout(3, false));
shell.setSize(600, 400);
// Message dialog button
Button messageButton = new Button(shell, SWT.PUSH);
messageButton.setText("Message Dialog");
messageButton.addSelectionListener(e -> {
MessageBox messageBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
messageBox.setMessage("This is an information message dialog.");
messageBox.setText("Information");
messageBox.open();
});
// Confirmation dialog button
Button confirmButton = new Button(shell, SWT.PUSH);
confirmButton.setText("Confirm Dialog");
confirmButton.addSelectionListener(e -> {
MessageBox confirmBox = new MessageBox(shell, SWT.ICON_QUESTION | SWT.YES | SWT.NO | SWT.CANCEL);
confirmBox.setMessage("Do you want to proceed with this operation?");
confirmBox.setText("Confirmation Required");
int result = confirmBox.open();
String resultText = switch (result) {
case SWT.YES -> "User selected: YES";
case SWT.NO -> "User selected: NO";
case SWT.CANCEL -> "User selected: CANCEL";
default -> "Unknown result";
};
MessageBox resultBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
resultBox.setMessage(resultText);
resultBox.setText("User Choice Result");
resultBox.open();
});
// Input dialog button
Button inputButton = new Button(shell, SWT.PUSH);
inputButton.setText("Input Dialog");
inputButton.addSelectionListener(e -> {
showCustomInputDialog(shell);
});
// File dialog button
Button fileButton = new Button(shell, SWT.PUSH);
fileButton.setText("File Dialog");
fileButton.addSelectionListener(e -> {
FileDialog fileDialog = new FileDialog(shell, SWT.OPEN | SWT.MULTI);
fileDialog.setText("Select Files");
fileDialog.setFilterExtensions(new String[]{"*.txt", "*.java", "*.xml", "*.*"});
fileDialog.setFilterNames(new String[]{
"Text Files (*.txt)",
"Java Files (*.java)",
"XML Files (*.xml)",
"All Files (*.*)"
});
String firstFile = fileDialog.open();
if (firstFile != null) {
String[] fileNames = fileDialog.getFileNames();
String filterPath = fileDialog.getFilterPath();
StringBuilder message = new StringBuilder();
message.append("Selected ").append(fileNames.length).append(" file(s):\n\n");
for (String fileName : fileNames) {
message.append(filterPath).append(System.getProperty("file.separator")).append(fileName).append("\n");
}
MessageBox resultBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
resultBox.setMessage(message.toString());
resultBox.setText("File Selection Result");
resultBox.open();
}
});
// Directory dialog button
Button dirButton = new Button(shell, SWT.PUSH);
dirButton.setText("Directory Dialog");
dirButton.addSelectionListener(e -> {
DirectoryDialog dirDialog = new DirectoryDialog(shell);
dirDialog.setText("Select Directory");
dirDialog.setMessage("Choose a directory:");
String selectedDirectory = dirDialog.open();
if (selectedDirectory != null) {
MessageBox resultBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
resultBox.setMessage("Selected directory:\n" + selectedDirectory);
resultBox.setText("Directory Selection Result");
resultBox.open();
}
});
// Color dialog button
Button colorButton = new Button(shell, SWT.PUSH);
colorButton.setText("Color Dialog");
colorButton.addSelectionListener(e -> {
ColorDialog colorDialog = new ColorDialog(shell);
colorDialog.setText("Select Color");
RGB selectedColor = colorDialog.open();
if (selectedColor != null) {
MessageBox resultBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
resultBox.setMessage(String.format("Selected color:\nRed: %d, Green: %d, Blue: %d\nHex: #%02X%02X%02X",
selectedColor.red, selectedColor.green, selectedColor.blue,
selectedColor.red, selectedColor.green, selectedColor.blue));
resultBox.setText("Color Selection Result");
resultBox.open();
}
});
// Font dialog button
Button fontButton = new Button(shell, SWT.PUSH);
fontButton.setText("Font Dialog");
fontButton.addSelectionListener(e -> {
FontDialog fontDialog = new FontDialog(shell);
fontDialog.setText("Select Font");
FontData selectedFont = fontDialog.open();
if (selectedFont != null) {
MessageBox resultBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
resultBox.setMessage(String.format("Selected font:\nName: %s\nHeight: %d\nStyle: %s",
selectedFont.getName(),
selectedFont.getHeight(),
getFontStyleString(selectedFont.getStyle())));
resultBox.setText("Font Selection Result");
resultBox.open();
}
});
// Progress dialog button
Button progressButton = new Button(shell, SWT.PUSH);
progressButton.setText("Progress Dialog");
progressButton.addSelectionListener(e -> {
showProgressDialog(shell);
});
// Custom dialog button
Button customButton = new Button(shell, SWT.PUSH);
customButton.setText("Custom Dialog");
customButton.addSelectionListener(e -> {
showAdvancedCustomDialog(shell);
});
// Center window
Monitor primary = display.getPrimaryMonitor();
Rectangle bounds = primary.getBounds();
Rectangle rect = shell.getBounds();
int x = bounds.x + (bounds.width - rect.width) / 2;
int y = bounds.y + (bounds.height - rect.height) / 2;
shell.setLocation(x, y);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
private static void showCustomInputDialog(Shell parent) {
Shell dialog = new Shell(parent, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);
dialog.setText("User Information Input");
dialog.setLayout(new GridLayout(2, false));
dialog.setSize(400, 250);
// Center dialog
Rectangle parentBounds = parent.getBounds();
Rectangle dialogBounds = dialog.getBounds();
int x = parentBounds.x + (parentBounds.width - dialogBounds.width) / 2;
int y = parentBounds.y + (parentBounds.height - dialogBounds.height) / 2;
dialog.setLocation(x, y);
// Name field
new Label(dialog, SWT.NONE).setText("Name:");
Text nameText = new Text(dialog, SWT.BORDER);
nameText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
// Age field
new Label(dialog, SWT.NONE).setText("Age:");
Spinner ageSpinner = new Spinner(dialog, SWT.BORDER);
ageSpinner.setMinimum(0);
ageSpinner.setMaximum(150);
ageSpinner.setSelection(25);
ageSpinner.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
// Gender field
new Label(dialog, SWT.NONE).setText("Gender:");
Combo genderCombo = new Combo(dialog, SWT.DROP_DOWN | SWT.READ_ONLY);
genderCombo.setItems(new String[]{"Male", "Female", "Other", "Prefer not to say"});
genderCombo.select(0);
genderCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
// Email field
new Label(dialog, SWT.NONE).setText("Email:");
Text emailText = new Text(dialog, SWT.BORDER);
emailText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
// Subscribe checkbox
new Label(dialog, SWT.NONE); // Empty label for spacing
Button subscribeCheck = new Button(dialog, SWT.CHECK);
subscribeCheck.setText("Subscribe to newsletter");
subscribeCheck.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
// Button composite
Composite buttonComposite = new Composite(dialog, SWT.NONE);
buttonComposite.setLayout(new GridLayout(2, true));
buttonComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));
Button okButton = new Button(buttonComposite, SWT.PUSH);
okButton.setText("OK");
okButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
okButton.addSelectionListener(e -> {
// Validate input
String name = nameText.getText().trim();
String email = emailText.getText().trim();
if (name.isEmpty()) {
MessageBox errorBox = new MessageBox(dialog, SWT.ICON_ERROR | SWT.OK);
errorBox.setMessage("Please enter a name.");
errorBox.setText("Validation Error");
errorBox.open();
nameText.setFocus();
return;
}
if (email.isEmpty() || !email.contains("@")) {
MessageBox errorBox = new MessageBox(dialog, SWT.ICON_ERROR | SWT.OK);
errorBox.setMessage("Please enter a valid email address.");
errorBox.setText("Validation Error");
errorBox.open();
emailText.setFocus();
return;
}
// Show result
String result = String.format(
"User Information:\n\nName: %s\nAge: %d\nGender: %s\nEmail: %s\nNewsletter: %s",
name,
ageSpinner.getSelection(),
genderCombo.getText(),
email,
subscribeCheck.getSelection() ? "Yes" : "No"
);
MessageBox resultBox = new MessageBox(parent, SWT.ICON_INFORMATION | SWT.OK);
resultBox.setMessage(result);
resultBox.setText("User Information");
resultBox.open();
dialog.dispose();
});
Button cancelButton = new Button(buttonComposite, SWT.PUSH);
cancelButton.setText("Cancel");
cancelButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
cancelButton.addSelectionListener(e -> dialog.dispose());
// Set default button and focus
dialog.setDefaultButton(okButton);
nameText.setFocus();
dialog.open();
}
private static void showProgressDialog(Shell parent) {
Shell progressDialog = new Shell(parent, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);
progressDialog.setText("Processing...");
progressDialog.setLayout(new GridLayout());
progressDialog.setSize(400, 150);
// Center dialog
Rectangle parentBounds = parent.getBounds();
Rectangle dialogBounds = progressDialog.getBounds();
int x = parentBounds.x + (parentBounds.width - dialogBounds.width) / 2;
int y = parentBounds.y + (parentBounds.height - dialogBounds.height) / 2;
progressDialog.setLocation(x, y);
Label statusLabel = new Label(progressDialog, SWT.NONE);
statusLabel.setText("Initializing...");
statusLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
ProgressBar progressBar = new ProgressBar(progressDialog, SWT.HORIZONTAL);
progressBar.setMinimum(0);
progressBar.setMaximum(100);
progressBar.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
Button cancelButton = new Button(progressDialog, SWT.PUSH);
cancelButton.setText("Cancel");
cancelButton.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false));
final boolean[] cancelled = {false};
cancelButton.addSelectionListener(e -> {
cancelled[0] = true;
progressDialog.dispose();
});
progressDialog.open();
// Simulate work in background
Display display = parent.getDisplay();
Thread worker = new Thread(() -> {
for (int i = 0; i <= 100 && !cancelled[0]; i++) {
final int progress = i;
display.asyncExec(() -> {
if (!progressDialog.isDisposed()) {
progressBar.setSelection(progress);
statusLabel.setText("Processing step " + progress + " of 100...");
}
});
try {
Thread.sleep(50); // Simulate work
} catch (InterruptedException e) {
break;
}
}
display.asyncExec(() -> {
if (!progressDialog.isDisposed()) {
if (!cancelled[0]) {
MessageBox completeBox = new MessageBox(parent, SWT.ICON_INFORMATION | SWT.OK);
completeBox.setMessage("Processing completed successfully!");
completeBox.setText("Complete");
completeBox.open();
}
progressDialog.dispose();
}
});
});
worker.start();
}
private static void showAdvancedCustomDialog(Shell parent) {
Shell dialog = new Shell(parent, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL | SWT.RESIZE);
dialog.setText("Advanced Custom Dialog");
dialog.setLayout(new GridLayout());
dialog.setSize(500, 400);
// Center dialog
Rectangle parentBounds = parent.getBounds();
Rectangle dialogBounds = dialog.getBounds();
int x = parentBounds.x + (parentBounds.width - dialogBounds.width) / 2;
int y = parentBounds.y + (parentBounds.height - dialogBounds.height) / 2;
dialog.setLocation(x, y);
// Tab folder for multiple pages
TabFolder tabFolder = new TabFolder(dialog, SWT.NONE);
tabFolder.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
// Personal Info Tab
TabItem personalTab = new TabItem(tabFolder, SWT.NONE);
personalTab.setText("Personal Info");
Composite personalComposite = new Composite(tabFolder, SWT.NONE);
personalComposite.setLayout(new GridLayout(2, false));
personalTab.setControl(personalComposite);
new Label(personalComposite, SWT.NONE).setText("First Name:");
Text firstNameText = new Text(personalComposite, SWT.BORDER);
firstNameText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
new Label(personalComposite, SWT.NONE).setText("Last Name:");
Text lastNameText = new Text(personalComposite, SWT.BORDER);
lastNameText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
new Label(personalComposite, SWT.NONE).setText("Date of Birth:");
DateTime dateTime = new DateTime(personalComposite, SWT.DATE | SWT.DROP_DOWN);
dateTime.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
// Preferences Tab
TabItem preferencesTab = new TabItem(tabFolder, SWT.NONE);
preferencesTab.setText("Preferences");
Composite preferencesComposite = new Composite(tabFolder, SWT.NONE);
preferencesComposite.setLayout(new GridLayout());
preferencesTab.setControl(preferencesComposite);
Group notificationGroup = new Group(preferencesComposite, SWT.NONE);
notificationGroup.setText("Notifications");
notificationGroup.setLayout(new GridLayout());
notificationGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
Button emailNotifications = new Button(notificationGroup, SWT.CHECK);
emailNotifications.setText("Email notifications");
Button smsNotifications = new Button(notificationGroup, SWT.CHECK);
smsNotifications.setText("SMS notifications");
Button pushNotifications = new Button(notificationGroup, SWT.CHECK);
pushNotifications.setText("Push notifications");
Group themeGroup = new Group(preferencesComposite, SWT.NONE);
themeGroup.setText("Theme");
themeGroup.setLayout(new GridLayout());
themeGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
Button lightTheme = new Button(themeGroup, SWT.RADIO);
lightTheme.setText("Light theme");
lightTheme.setSelection(true);
Button darkTheme = new Button(themeGroup, SWT.RADIO);
darkTheme.setText("Dark theme");
Button autoTheme = new Button(themeGroup, SWT.RADIO);
autoTheme.setText("Auto (system)");
// Button area
Composite buttonArea = new Composite(dialog, SWT.NONE);
buttonArea.setLayout(new GridLayout(3, false));
buttonArea.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
// Spacer
new Label(buttonArea, SWT.NONE).setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
Button okButton = new Button(buttonArea, SWT.PUSH);
okButton.setText("OK");
okButton.addSelectionListener(e -> {
String firstName = firstNameText.getText().trim();
String lastName = lastNameText.getText().trim();
if (firstName.isEmpty() || lastName.isEmpty()) {
MessageBox errorBox = new MessageBox(dialog, SWT.ICON_ERROR | SWT.OK);
errorBox.setMessage("Please fill in both first and last name.");
errorBox.setText("Validation Error");
errorBox.open();
return;
}
String theme = lightTheme.getSelection() ? "Light" :
darkTheme.getSelection() ? "Dark" : "Auto";
String notifications = "";
if (emailNotifications.getSelection()) notifications += "Email ";
if (smsNotifications.getSelection()) notifications += "SMS ";
if (pushNotifications.getSelection()) notifications += "Push ";
if (notifications.isEmpty()) notifications = "None";
String result = String.format(
"Settings saved:\n\nName: %s %s\nBirth Date: %d/%d/%d\nTheme: %s\nNotifications: %s",
firstName, lastName,
dateTime.getMonth() + 1, dateTime.getDay(), dateTime.getYear(),
theme, notifications.trim()
);
MessageBox resultBox = new MessageBox(parent, SWT.ICON_INFORMATION | SWT.OK);
resultBox.setMessage(result);
resultBox.setText("Settings Saved");
resultBox.open();
dialog.dispose();
});
Button cancelButton = new Button(buttonArea, SWT.PUSH);
cancelButton.setText("Cancel");
cancelButton.addSelectionListener(e -> dialog.dispose());
dialog.setDefaultButton(okButton);
dialog.open();
}
private static String getFontStyleString(int style) {
if (style == SWT.NORMAL) return "Normal";
String result = "";
if ((style & SWT.BOLD) != 0) result += "Bold ";
if ((style & SWT.ITALIC) != 0) result += "Italic ";
return result.trim();
}
}
File Operations and System Integration
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.dnd.*;
import org.eclipse.swt.SWT;
import java.io.*;
import java.nio.file.*;
import java.util.List;
public class FileOperationsExample {
private Text textArea;
private Label statusLabel;
private Shell shell;
private String currentFile = null;
public static void main(String[] args) {
new FileOperationsExample().run();
}
public void run() {
Display display = new Display();
createShell(display);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
private void createShell(Display display) {
shell = new Shell(display);
shell.setText("File Operations & System Integration Example");
shell.setLayout(new BorderLayout());
shell.setSize(800, 600);
createMenuBar();
createToolBar();
createMainContent();
createStatusBar();
setupDragAndDrop();
// Center window
Monitor primary = display.getPrimaryMonitor();
Rectangle bounds = primary.getBounds();
Rectangle rect = shell.getBounds();
int x = bounds.x + (bounds.width - rect.width) / 2;
int y = bounds.y + (bounds.height - rect.height) / 2;
shell.setLocation(x, y);
}
private void createMenuBar() {
Menu menuBar = new Menu(shell, SWT.BAR);
shell.setMenuBar(menuBar);
// File menu
MenuItem fileMenuItem = new MenuItem(menuBar, SWT.CASCADE);
fileMenuItem.setText("&File");
Menu fileMenu = new Menu(shell, SWT.DROP_DOWN);
fileMenuItem.setMenu(fileMenu);
MenuItem newMenuItem = new MenuItem(fileMenu, SWT.PUSH);
newMenuItem.setText("&New\tCtrl+N");
newMenuItem.setAccelerator(SWT.CTRL + 'N');
newMenuItem.addSelectionListener(e -> newFile());
MenuItem openMenuItem = new MenuItem(fileMenu, SWT.PUSH);
openMenuItem.setText("&Open\tCtrl+O");
openMenuItem.setAccelerator(SWT.CTRL + 'O');
openMenuItem.addSelectionListener(e -> openFile());
MenuItem saveMenuItem = new MenuItem(fileMenu, SWT.PUSH);
saveMenuItem.setText("&Save\tCtrl+S");
saveMenuItem.setAccelerator(SWT.CTRL + 'S');
saveMenuItem.addSelectionListener(e -> saveFile());
MenuItem saveAsMenuItem = new MenuItem(fileMenu, SWT.PUSH);
saveAsMenuItem.setText("Save &As...\tCtrl+Shift+S");
saveAsMenuItem.setAccelerator(SWT.CTRL + SWT.SHIFT + 'S');
saveAsMenuItem.addSelectionListener(e -> saveAsFile());
new MenuItem(fileMenu, SWT.SEPARATOR);
MenuItem recentFilesMenuItem = new MenuItem(fileMenu, SWT.CASCADE);
recentFilesMenuItem.setText("Recent Files");
Menu recentFilesMenu = new Menu(shell, SWT.DROP_DOWN);
recentFilesMenuItem.setMenu(recentFilesMenu);
// Add some dummy recent files
for (int i = 1; i <= 5; i++) {
MenuItem recentItem = new MenuItem(recentFilesMenu, SWT.PUSH);
recentItem.setText("document" + i + ".txt");
recentItem.addSelectionListener(e -> {
updateStatus("Recent file selected: " + ((MenuItem)e.widget).getText());
});
}
new MenuItem(fileMenu, SWT.SEPARATOR);
MenuItem exitMenuItem = new MenuItem(fileMenu, SWT.PUSH);
exitMenuItem.setText("E&xit");
exitMenuItem.addSelectionListener(e -> shell.close());
// System menu
MenuItem systemMenuItem = new MenuItem(menuBar, SWT.CASCADE);
systemMenuItem.setText("&System");
Menu systemMenu = new Menu(shell, SWT.DROP_DOWN);
systemMenuItem.setMenu(systemMenu);
MenuItem systemInfoMenuItem = new MenuItem(systemMenu, SWT.PUSH);
systemInfoMenuItem.setText("System Information");
systemInfoMenuItem.addSelectionListener(e -> showSystemInfo());
MenuItem memoryInfoMenuItem = new MenuItem(systemMenu, SWT.PUSH);
memoryInfoMenuItem.setText("Memory Information");
memoryInfoMenuItem.addSelectionListener(e -> showMemoryInfo());
MenuItem openWorkingDirMenuItem = new MenuItem(systemMenu, SWT.PUSH);
openWorkingDirMenuItem.setText("Open Working Directory");
openWorkingDirMenuItem.addSelectionListener(e -> openWorkingDirectory());
}
private void createToolBar() {
ToolBar toolBar = new ToolBar(shell, SWT.HORIZONTAL | SWT.FLAT);
toolBar.setLayoutData(BorderData.NORTH);
ToolItem newToolItem = new ToolItem(toolBar, SWT.PUSH);
newToolItem.setText("New");
newToolItem.setToolTipText("Create new file");
newToolItem.addSelectionListener(e -> newFile());
ToolItem openToolItem = new ToolItem(toolBar, SWT.PUSH);
openToolItem.setText("Open");
openToolItem.setToolTipText("Open existing file");
openToolItem.addSelectionListener(e -> openFile());
ToolItem saveToolItem = new ToolItem(toolBar, SWT.PUSH);
saveToolItem.setText("Save");
saveToolItem.setToolTipText("Save current file");
saveToolItem.addSelectionListener(e -> saveFile());
new ToolItem(toolBar, SWT.SEPARATOR);
ToolItem fileInfoToolItem = new ToolItem(toolBar, SWT.PUSH);
fileInfoToolItem.setText("File Info");
fileInfoToolItem.setToolTipText("Show current file information");
fileInfoToolItem.addSelectionListener(e -> showFileInfo());
}
private void createMainContent() {
textArea = new Text(shell, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
textArea.setLayoutData(BorderData.CENTER);
textArea.setText("Welcome to the File Operations Example!\n\n" +
"Features:\n" +
"- Drag and drop files to open them\n" +
"- Standard file operations (New, Open, Save, Save As)\n" +
"- System integration features\n" +
"- File and memory information\n\n" +
"Try dragging a text file onto this area!");
// Add modification listener
textArea.addModifyListener(e -> updateTitle());
}
private void createStatusBar() {
statusLabel = new Label(shell, SWT.BORDER);
statusLabel.setLayoutData(BorderData.SOUTH);
updateStatus("Ready - Drag files here or use File menu");
}
private void setupDragAndDrop() {
// File drop target
DropTarget dropTarget = new DropTarget(textArea, DND.DROP_DEFAULT | DND.DROP_MOVE | DND.DROP_COPY);
dropTarget.setTransfer(new Transfer[]{FileTransfer.getInstance()});
dropTarget.addDropListener(new DropTargetAdapter() {
@Override
public void drop(DropTargetEvent event) {
if (event.data instanceof String[]) {
String[] files = (String[]) event.data;
if (files.length > 0) {
loadFile(files[0]);
}
}
}
@Override
public void dragEnter(DropTargetEvent event) {
event.detail = DND.DROP_COPY;
updateStatus("Drop file to open it...");
}
@Override
public void dragLeave(DropTargetEvent event) {
updateStatus("Ready");
}
});
}
private void newFile() {
if (textArea.getText().length() > 0 && textArea.getModified()) {
MessageBox confirmBox = new MessageBox(shell, SWT.ICON_QUESTION | SWT.YES | SWT.NO | SWT.CANCEL);
confirmBox.setMessage("Current file has unsaved changes. Save before creating new file?");
confirmBox.setText("Unsaved Changes");
int result = confirmBox.open();
switch (result) {
case SWT.YES:
if (!saveFile()) return; // Cancel if save failed
break;
case SWT.CANCEL:
return;
case SWT.NO:
break;
}
}
textArea.setText("");
currentFile = null;
updateTitle();
updateStatus("New file created");
}
private void openFile() {
FileDialog dialog = new FileDialog(shell, SWT.OPEN);
dialog.setFilterExtensions(new String[]{"*.txt", "*.java", "*.xml", "*.json", "*.*"});
dialog.setFilterNames(new String[]{
"Text Files (*.txt)",
"Java Files (*.java)",
"XML Files (*.xml)",
"JSON Files (*.json)",
"All Files (*.*)"
});
String fileName = dialog.open();
if (fileName != null) {
loadFile(fileName);
}
}
private void loadFile(String fileName) {
try {
Path path = Paths.get(fileName);
String content = Files.readString(path);
textArea.setText(content);
currentFile = fileName;
updateTitle();
updateStatus("Opened: " + fileName);
} catch (IOException e) {
MessageBox errorBox = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
errorBox.setMessage("Error reading file: " + e.getMessage());
errorBox.setText("File Error");
errorBox.open();
updateStatus("Error opening file: " + fileName);
}
}
private boolean saveFile() {
if (currentFile == null) {
return saveAsFile();
} else {
return writeFile(currentFile);
}
}
private boolean saveAsFile() {
FileDialog dialog = new FileDialog(shell, SWT.SAVE);
dialog.setFilterExtensions(new String[]{"*.txt", "*.java", "*.xml", "*.json", "*.*"});
dialog.setFilterNames(new String[]{
"Text Files (*.txt)",
"Java Files (*.java)",
"XML Files (*.xml)",
"JSON Files (*.json)",
"All Files (*.*)"
});
if (currentFile != null) {
dialog.setFileName(Paths.get(currentFile).getFileName().toString());
}
String fileName = dialog.open();
if (fileName != null) {
if (writeFile(fileName)) {
currentFile = fileName;
updateTitle();
return true;
}
}
return false;
}
private boolean writeFile(String fileName) {
try {
Path path = Paths.get(fileName);
Files.writeString(path, textArea.getText());
updateStatus("Saved: " + fileName);
textArea.setModified(false);
return true;
} catch (IOException e) {
MessageBox errorBox = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
errorBox.setMessage("Error saving file: " + e.getMessage());
errorBox.setText("Save Error");
errorBox.open();
updateStatus("Error saving file: " + fileName);
return false;
}
}
private void showFileInfo() {
if (currentFile == null) {
MessageBox infoBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
infoBox.setMessage("No file is currently open.");
infoBox.setText("File Information");
infoBox.open();
return;
}
try {
Path path = Paths.get(currentFile);
long size = Files.size(path);
String lastModified = Files.getLastModifiedTime(path).toString();
boolean readable = Files.isReadable(path);
boolean writable = Files.isWritable(path);
boolean executable = Files.isExecutable(path);
String info = String.format(
"File Information:\n\n" +
"Path: %s\n" +
"Size: %,d bytes\n" +
"Last Modified: %s\n" +
"Readable: %s\n" +
"Writable: %s\n" +
"Executable: %s\n\n" +
"Text Statistics:\n" +
"Characters: %,d\n" +
"Lines: %,d",
currentFile,
size,
lastModified,
readable ? "Yes" : "No",
writable ? "Yes" : "No",
executable ? "Yes" : "No",
textArea.getCharCount(),
textArea.getLineCount()
);
MessageBox infoBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
infoBox.setMessage(info);
infoBox.setText("File Information");
infoBox.open();
} catch (IOException e) {
MessageBox errorBox = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
errorBox.setMessage("Error getting file information: " + e.getMessage());
errorBox.setText("Error");
errorBox.open();
}
}
private void showSystemInfo() {
Runtime runtime = Runtime.getRuntime();
String info = String.format(
"System Information:\n\n" +
"Operating System: %s %s (%s)\n" +
"Java Version: %s\n" +
"Java Vendor: %s\n" +
"Java Home: %s\n" +
"User Name: %s\n" +
"User Home: %s\n" +
"Working Directory: %s\n" +
"Available Processors: %d\n" +
"Total Memory: %,d MB\n" +
"Free Memory: %,d MB\n" +
"Max Memory: %,d MB",
System.getProperty("os.name"),
System.getProperty("os.version"),
System.getProperty("os.arch"),
System.getProperty("java.version"),
System.getProperty("java.vendor"),
System.getProperty("java.home"),
System.getProperty("user.name"),
System.getProperty("user.home"),
System.getProperty("user.dir"),
runtime.availableProcessors(),
runtime.totalMemory() / 1024 / 1024,
runtime.freeMemory() / 1024 / 1024,
runtime.maxMemory() / 1024 / 1024
);
MessageBox infoBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
infoBox.setMessage(info);
infoBox.setText("System Information");
infoBox.open();
}
private void showMemoryInfo() {
Runtime runtime = Runtime.getRuntime();
runtime.gc(); // Suggest garbage collection
long totalMemory = runtime.totalMemory();
long freeMemory = runtime.freeMemory();
long usedMemory = totalMemory - freeMemory;
long maxMemory = runtime.maxMemory();
String info = String.format(
"Memory Information:\n\n" +
"Total Memory: %,d KB (%,d MB)\n" +
"Used Memory: %,d KB (%,d MB)\n" +
"Free Memory: %,d KB (%,d MB)\n" +
"Max Memory: %,d KB (%,d MB)\n\n" +
"Memory Usage: %.1f%%\n" +
"Available for allocation: %,d KB (%,d MB)",
totalMemory / 1024, totalMemory / 1024 / 1024,
usedMemory / 1024, usedMemory / 1024 / 1024,
freeMemory / 1024, freeMemory / 1024 / 1024,
maxMemory / 1024, maxMemory / 1024 / 1024,
(double) usedMemory / totalMemory * 100,
(maxMemory - usedMemory) / 1024, (maxMemory - usedMemory) / 1024 / 1024
);
MessageBox infoBox = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
infoBox.setMessage(info);
infoBox.setText("Memory Information");
infoBox.open();
}
private void openWorkingDirectory() {
try {
String workingDir = System.getProperty("user.dir");
String os = System.getProperty("os.name").toLowerCase();
ProcessBuilder pb;
if (os.contains("windows")) {
pb = new ProcessBuilder("explorer", workingDir);
} else if (os.contains("mac")) {
pb = new ProcessBuilder("open", workingDir);
} else {
// Linux and other Unix-like systems
pb = new ProcessBuilder("xdg-open", workingDir);
}
pb.start();
updateStatus("Opened working directory in system file manager");
} catch (IOException e) {
MessageBox errorBox = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
errorBox.setMessage("Cannot open working directory: " + e.getMessage());
errorBox.setText("Error");
errorBox.open();
updateStatus("Error opening working directory");
}
}
private void updateTitle() {
String title = "File Operations Example";
if (currentFile != null) {
title += " - " + Paths.get(currentFile).getFileName();
if (textArea.getModified()) {
title += " *";
}
} else if (textArea.getModified()) {
title += " - Untitled *";
}
shell.setText(title);
}
private void updateStatus(String message) {
if (statusLabel != null && !statusLabel.isDisposed()) {
statusLabel.setText(message);
}
}
}