Here’s a simple Java text editor program using Swing. It provides a window with basic functionality to create, open, edit, and save text files.
Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class SimpleTextEditor extends JFrame implements ActionListener {
JTextArea textArea;
JScrollPane scrollPane;
JMenuBar menuBar;
JMenu fileMenu;
JMenuItem newFile, openFile, saveFile, exitApp;
public SimpleTextEditor() {
// Window Title
setTitle("Simple Text Editor");
setSize(600, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
// Text Area
textArea = new JTextArea();
scrollPane = new JScrollPane(textArea);
add(scrollPane);
// Menu Bar
menuBar = new JMenuBar();
fileMenu = new JMenu("File");
newFile = new JMenuItem("New");
openFile = new JMenuItem("Open");
saveFile = new JMenuItem("Save");
exitApp = new JMenuItem("Exit");
newFile.addActionListener(this);
openFile.addActionListener(this);
saveFile.addActionListener(this);
exitApp.addActionListener(this);
fileMenu.add(newFile);
fileMenu.add(openFile);
fileMenu.add(saveFile);
fileMenu.add(exitApp);
menuBar.add(fileMenu);
setJMenuBar(menuBar);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == newFile) {
textArea.setText("");
} else if (e.getSource() == openFile) {
JFileChooser fileChooser = new JFileChooser();
int option = fileChooser.showOpenDialog(this);
if (option == JFileChooser.APPROVE_OPTION) {
try (BufferedReader br = new BufferedReader(new FileReader(fileChooser.getSelectedFile()))) {
textArea.read(br, null);
} catch (IOException ex) {
ex.printStackTrace();
}
}
} else if (e.getSource() == saveFile) {
JFileChooser fileChooser = new JFileChooser();
int option = fileChooser.showSaveDialog(this);
if (option == JFileChooser.APPROVE_OPTION) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(fileChooser.getSelectedFile()))) {
textArea.write(bw);
} catch (IOException ex) {
ex.printStackTrace();
}
}
} else if (e.getSource() == exitApp) {
System.exit(0);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new SimpleTextEditor());
}
}
---
Features:
New File → Clears the text area.
Open File → Allows selecting and loading a text file.
Save File → Saves the current text to a file.
Exit → Closes the application
No comments:
Post a Comment