Java TodoList


import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

class TodoItem implements Serializable {
    private static final long serialVersionUID = 1L;
    private static int counter = 1;
    private int id;
    private String description;
    private String category;
    private Date deadline;
    private String priority;
    private boolean completed;

    public TodoItem(String description, String category, String deadline, String priority) throws ParseException {
        this.id = counter++;
        this.description = description;
        this.category = category;
        this.deadline = new SimpleDateFormat("yyyy-MM-dd").parse(deadline);
        this.priority = priority;
        this.completed = false;
    }

    public int getId() {
        return id;
    }

    public String getDescription() {
        return description;
    }

    public String getCategory() {
        return category;
    }

    public Date getDeadline() {
        return deadline;
    }

    public String getPriority() {
        return priority;
    }

    public boolean isCompleted() {
        return completed;
    }

    public void markCompleted() {
        this.completed = true;
    }

    public boolean isOverdue() {
        return !completed && deadline.before(new Date());
    }

    @Override
    public String toString() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String status = isCompleted() ? "完了" : (isOverdue() ? "期限切れ" : "未完了");
        return String.format("%-4d %-30s %-15s %-10s %-10s %-10s",
                id, description, category, priority, sdf.format(deadline), status);
    }
}

public class TodoListApp {
    private Map<String, List<TodoItem>> userTasks = new HashMap<>();
    private static final String DATA_FILE = "todo_data.ser";
    private String currentUser = "default";

    public TodoListApp() {
        loadTasks();
    }

    public void addTask(String description, String category, String deadline, String priority) {
        try {
            userTasks.computeIfAbsent(currentUser, k -> new ArrayList<>())
                     .add(new TodoItem(description, category, deadline, priority));
            System.out.println("タスクを追加しました。");
            saveTasks();
        } catch (ParseException e) {
            System.out.println("無効な日付形式です。形式 yyyy-MM-dd");
        }
    }

    public void listTasks() {
        List<TodoItem> tasks = userTasks.getOrDefault(currentUser, new ArrayList<>());
        if (tasks.isEmpty()) {
            System.out.println("タスクがありません。");
            return;
        }

        System.out.println(String.format("%-4s %-30s %-15s %-10s %-10s %-10s",
                "ID", "タスク内容", "カテゴリ", "優先度", "期限", "状態"));
        tasks.stream()
             .sorted(Comparator.comparing(TodoItem::getDeadline).thenComparing(TodoItem::getPriority))
             .forEach(System.out::println);
    }

    public void markTaskCompleted(int id) {
        List<TodoItem> tasks = userTasks.getOrDefault(currentUser, new ArrayList<>());
        for (TodoItem task : tasks) {
            if (task.getId() == id) {
                task.markCompleted();
                System.out.println("タスクを完了しました。");
                saveTasks();
                return;
            }
        }
        System.out.println("タスクが見つかりません。");
    }

    public void removeTask(int id) {
        List<TodoItem> tasks = userTasks.getOrDefault(currentUser, new ArrayList<>());
        if (tasks.removeIf(task -> task.getId() == id)) {
            System.out.println("タスクを削除しました。");
            saveTasks();
        } else {
            System.out.println("タスクが見つかりません。");
        }
    }

    private void saveTasks() {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(DATA_FILE))) {
            oos.writeObject(userTasks);
        } catch (IOException e) {
            System.out.println("タスクの保存に失敗しました。");
        }
    }

    @SuppressWarnings("unchecked")
    private void loadTasks() {
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(DATA_FILE))) {
            userTasks = (Map<String, List<TodoItem>>) ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            System.out.println("以前のタスクを読み込めませんでした。");
        }
    }

    public static void main(String[] args) {
        TodoListApp app = new TodoListApp();
        Scanner scanner = new Scanner(System.in);

        while (true) {
            System.out.println("\nTODOリスト - " + app.currentUser);
            System.out.println("1. タスクを追加");
            System.out.println("2. タスクを一覧表示");
            System.out.println("3. タスクを完了済みにする");
            System.out.println("4. タスクを削除");
            System.out.println("5. 終了");
            System.out.print("選択してください: ");

            int choice = scanner.nextInt();
            scanner.nextLine(); // 改行を消費

            switch (choice) {
                case 1:
                    System.out.print("タスク内容: ");
                    String description = scanner.nextLine();
                    System.out.print("カテゴリ: ");
                    String category = scanner.nextLine();
                    System.out.print("期限 (yyyy-MM-dd): ");
                    String deadline = scanner.nextLine();
                    System.out.print("優先度 (高, 中, 低): ");
                    String priority = scanner.nextLine();
                    app.addTask(description, category, deadline, priority);
                    break;
                case 2:
                    app.listTasks();
                    break;
                case 3:
                    System.out.print("完了するタスクのID: ");
                    int completeId = scanner.nextInt();
                    app.markTaskCompleted(completeId);
                    break;
                case 4:
                    System.out.print("削除するタスクのID: ");
                    int removeId = scanner.nextInt();
                    app.removeTask(removeId);
                    break;
                case 5:
                    System.out.println("終了します。");
                    scanner.close();
                    return;
                default:
                    System.out.println("無効な選択です。");
            }
        }
    }
}

javac -encoding UTF-8 TodoListApp.java
java TodoListApp

Java  配列と反復処理

import java.util.Scanner;

public class MyApp {
  public static void main(String[] args) {
    int[] scores = {70, 90, 80, 60};
    // System.out.println(scores[0]);
    // System.out.println(scores[1]);
    // System.out.println(scores[2]);
    // for (int i = 0; i < 3; i++) {
    for (int i = 0; i < scores.length; i++) {
      System.out.println(scores[i]);
    }
  }

Java ペイントソフト

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.util.Stack;
import javax.imageio.ImageIO;
import java.io.File;

public class AdvancedPaintAppWithUndoRedo extends JFrame {

    private DrawPanel drawPanel;
    private Color currentColor = Color.BLACK;
    private int brushSize = 4;
    private String currentTool = "Brush";
    private Stack<BufferedImage> undoStack = new Stack<>();
    private Stack<BufferedImage> redoStack = new Stack<>();

    public AdvancedPaintAppWithUndoRedo() {
        setTitle("Advanced Paint Application with Undo/Redo");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        drawPanel = new DrawPanel();
        add(drawPanel, BorderLayout.CENTER);

        // メニューバーの作成
        JMenuBar menuBar = new JMenuBar();
        JMenu fileMenu = new JMenu("File");
        JMenuItem saveItem = new JMenuItem("Save");
        JMenuItem openItem = new JMenuItem("Open");
        JMenuItem clearItem = new JMenuItem("Clear");
        saveItem.addActionListener(e -> saveImage());
        openItem.addActionListener(e -> openImage());
        clearItem.addActionListener(e -> drawPanel.clearCanvas());
        fileMenu.add(saveItem);
        fileMenu.add(openItem);
        fileMenu.add(clearItem);
        menuBar.add(fileMenu);

        JMenu toolMenu = new JMenu("Tools");
        JMenuItem colorItem = new JMenuItem("Choose Color");
        JMenuItem brushItem = new JMenuItem("Brush Size");
        JMenuItem toolBrush = new JMenuItem("Brush");
        JMenuItem toolLine = new JMenuItem("Line");
        JMenuItem toolRect = new JMenuItem("Rectangle");
        JMenuItem toolOval = new JMenuItem("Oval");
        JMenuItem toolText = new JMenuItem("Text");

        colorItem.addActionListener(e -> chooseColor());
        brushItem.addActionListener(e -> chooseBrushSize());
        toolBrush.addActionListener(e -> currentTool = "Brush");
        toolLine.addActionListener(e -> currentTool = "Line");
        toolRect.addActionListener(e -> currentTool = "Rectangle");
        toolOval.addActionListener(e -> currentTool = "Oval");
        toolText.addActionListener(e -> currentTool = "Text");

        toolMenu.add(colorItem);
        toolMenu.add(brushItem);
        toolMenu.add(toolBrush);
        toolMenu.add(toolLine);
        toolMenu.add(toolRect);
        toolMenu.add(toolOval);
        toolMenu.add(toolText);
        menuBar.add(toolMenu);

        JMenu editMenu = new JMenu("Edit");
        JMenuItem undoItem = new JMenuItem("Undo");
        JMenuItem redoItem = new JMenuItem("Redo");
        undoItem.addActionListener(e -> drawPanel.undo());
        redoItem.addActionListener(e -> drawPanel.redo());
        editMenu.add(undoItem);
        editMenu.add(redoItem);
        menuBar.add(editMenu);

        setJMenuBar(menuBar);
    }

    // メインメソッド
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            AdvancedPaintAppWithUndoRedo app = new AdvancedPaintAppWithUndoRedo();
            app.setVisible(true);
        });
    }

    // 色を選択する
    private void chooseColor() {
        Color color = JColorChooser.showDialog(null, "Choose a Color", currentColor);
        if (color != null) {
            currentColor = color;
            drawPanel.setColor(color);
        }
    }

    // ブラシサイズを選択する
    private void chooseBrushSize() {
        String sizeStr = JOptionPane.showInputDialog(this, "Enter brush size:", brushSize);
        if (sizeStr != null) {
            try {
                int size = Integer.parseInt(sizeStr);
                if (size > 0) {
                    brushSize = size;
                    drawPanel.setBrushSize(size);
                }
            } catch (NumberFormatException e) {
                JOptionPane.showMessageDialog(this, "Invalid size entered.");
            }
        }
    }

    // 画像を保存する
    private void saveImage() {
        JFileChooser fileChooser = new JFileChooser();
        if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
            File file = fileChooser.getSelectedFile();
            try {
                ImageIO.write(drawPanel.getImage(), "png", file);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    // 画像を開く
    private void openImage() {
        JFileChooser fileChooser = new JFileChooser();
        if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
            File file = fileChooser.getSelectedFile();
            try {
                BufferedImage image = ImageIO.read(file);
                drawPanel.setImage(image);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    // 描画用のパネル
    class DrawPanel extends JPanel {

        private BufferedImage image;
        private Graphics2D g2;
        private int startX, startY, endX, endY;

        public DrawPanel() {
            setPreferredSize(new Dimension(800, 600));
            setDoubleBuffered(false);
            addMouseListener(new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent e) {
                    startX = e.getX();
                    startY = e.getY();
                    if (g2 != null) {
                        if (currentTool.equals("Brush")) {
                            g2.fillOval(startX, startY, brushSize, brushSize);
                        }
                        saveToUndoStack();
                    }
                    repaint();
                }

                @Override
                public void mouseReleased(MouseEvent e) {
                    endX = e.getX();
                    endY = e.getY();
                    if (g2 != null) {
                        switch (currentTool) {
                            case "Line":
                                g2.drawLine(startX, startY, endX, endY);
                                break;
                            case "Rectangle":
                                g2.drawRect(Math.min(startX, endX), Math.min(startY, endY),
                                        Math.abs(startX - endX), Math.abs(startY - endY));
                                break;
                            case "Oval":
                                g2.drawOval(Math.min(startX, endX), Math.min(startY, endY),
                                        Math.abs(startX - endX), Math.abs(startY - endY));
                                break;
                            case "Text":
                                String text = JOptionPane.showInputDialog("Enter text:");
                                if (text != null) {
                                    g2.drawString(text, startX, startY);
                                }
                                break;
                        }
                    }
                    saveToUndoStack();
                    repaint();
                }
            });

            addMouseMotionListener(new MouseMotionAdapter() {
                @Override
                public void mouseDragged(MouseEvent e) {
                    if (currentTool.equals("Brush")) {
                        g2.fillOval(e.getX(), e.getY(), brushSize, brushSize);
                    }
                    repaint();
                }
            });

            clearCanvas();
        }

        // Undoスタックに現在の状態を保存
        private void saveToUndoStack() {
            BufferedImage undoImage = new BufferedImage(image.getWidth(), image.getHeight(), image.getType());
            Graphics2D g = undoImage.createGraphics();
            g.drawImage(image, 0, 0, null);
            g.dispose();
            undoStack.push(undoImage);
            redoStack.clear();  // 新しいアクションの後、Redoをクリア
        }

        // Undo機能
        public void undo() {
            if (!undoStack.isEmpty()) {
                redoStack.push(image);
                image = undoStack.pop();
                g2 = image.createGraphics();
                repaint();
            }
        }

        // Redo機能
        public void redo() {
            if (!redoStack.isEmpty()) {
                undoStack.push(image);
                image = redoStack.pop();
                g2 = image.createGraphics();
                repaint();
            }
        }

        // 色を設定
        public void setColor(Color color) {
            if (g2 != null) {
                g2.setColor(color);
            }
        }

        // ブラシサイズを設定
        public void setBrushSize(int size) {
            brushSize = size;
        }

        // キャンバスをクリア
        public void clearCanvas() {
            image = new BufferedImage(800, 600, BufferedImage.TYPE_INT_ARGB);
            g2 = image.createGraphics();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setPaint(Color.WHITE);
            g2.fillRect(0, 0, image.getWidth(), image.getHeight());
            g2.setPaint(Color.BLACK);
            repaint();
        }

        // 描画イメージを取得
        public BufferedImage getImage() {
            return image;
        }

        // 描画イメージをセット
        public void setImage(BufferedImage img) {
            image = img;
            g2 = image.createGraphics();
            repaint();
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (image != null) {
                g.drawImage(image, 0, 0, null);
            }
        }
    }
}

Java テキストエディタ

import javax.swing.*;
import javax.swing.undo.UndoManager;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.awt.dnd.*;
import java.awt.datatransfer.*;

public class AdvancedTextEditor extends JFrame implements ActionListener {
    JTabbedPane tabbedPane;
    JTextArea textArea;
    JMenuBar menuBar;
    JMenu fileMenu, editMenu, formatMenu, themeMenu;
    JMenuItem newItem, openItem, saveItem, saveAllItem, closeItem;
    JMenuItem cutItem, copyItem, pasteItem, findItem, replaceItem, undoItem, redoItem;
    JMenuItem fontItem, lightThemeItem, darkThemeItem;
    JFileChooser fileChooser;
    JLabel statusBar;
    UndoManager undoManager = new UndoManager();
    JPopupMenu contextMenu;

    public AdvancedTextEditor() {
        setTitle("Advanced Text Editor");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        tabbedPane = new JTabbedPane();
        add(tabbedPane, BorderLayout.CENTER);

        statusBar = new JLabel("Status: Ready | Line: 1, Column: 1");
        add(statusBar, BorderLayout.SOUTH);

        menuBar = new JMenuBar();

        // ファイルメニューの作成
        fileMenu = new JMenu("File");
        newItem = new JMenuItem("New");
        openItem = new JMenuItem("Open");
        saveItem = new JMenuItem("Save");
        saveAllItem = new JMenuItem("Save All");
        closeItem = new JMenuItem("Close");
        fileMenu.add(newItem);
        fileMenu.add(openItem);
        fileMenu.add(saveItem);
        fileMenu.add(saveAllItem);
        fileMenu.add(closeItem);

        // 編集メニューの作成
        editMenu = new JMenu("Edit");
        cutItem = new JMenuItem("Cut");
        copyItem = new JMenuItem("Copy");
        pasteItem = new JMenuItem("Paste");
        undoItem = new JMenuItem("Undo");
        redoItem = new JMenuItem("Redo");
        findItem = new JMenuItem("Find");
        replaceItem = new JMenuItem("Replace");
        editMenu.add(cutItem);
        editMenu.add(copyItem);
        editMenu.add(pasteItem);
        editMenu.add(undoItem);
        editMenu.add(redoItem);
        editMenu.add(findItem);
        editMenu.add(replaceItem);

        // フォーマットメニューの作成
        formatMenu = new JMenu("Format");
        fontItem = new JMenuItem("Change Font");
        formatMenu.add(fontItem);

        // テーマメニューの作成
        themeMenu = new JMenu("Themes");
        lightThemeItem = new JMenuItem("Light Theme");
        darkThemeItem = new JMenuItem("Dark Theme");
        themeMenu.add(lightThemeItem);
        themeMenu.add(darkThemeItem);

        // メニューバーにメニューを追加
        menuBar.add(fileMenu);
        menuBar.add(editMenu);
        menuBar.add(formatMenu);
        menuBar.add(themeMenu);

        setJMenuBar(menuBar);

        // アクションリスナーの設定
        newItem.addActionListener(this);
        openItem.addActionListener(this);
        saveItem.addActionListener(this);
        saveAllItem.addActionListener(this);
        closeItem.addActionListener(this);
        cutItem.addActionListener(this);
        copyItem.addActionListener(this);
        pasteItem.addActionListener(this);
        undoItem.addActionListener(this);
        redoItem.addActionListener(this);
        findItem.addActionListener(this);
        replaceItem.addActionListener(this);
        fontItem.addActionListener(this);
        lightThemeItem.addActionListener(this);
        darkThemeItem.addActionListener(this);

        // ドラッグ&ドロップ対応
        new DropTarget(tabbedPane, new FileDropHandler());

        // コンテキストメニューの設定
        contextMenu = new JPopupMenu();
        contextMenu.add(cutItem);
        contextMenu.add(copyItem);
        contextMenu.add(pasteItem);
    }

    // アクションリスナーの処理
    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == newItem) {
            addNewTab();
        }
        // 他のアクションもここに追加
    }

    // 新しいタブを追加するメソッド
    private void addNewTab() {
        JTextArea textArea = new JTextArea();
        JScrollPane scrollPane = new JScrollPane(textArea);
        tabbedPane.add("Untitled", scrollPane);
        tabbedPane.setSelectedComponent(scrollPane);
        textArea.getDocument().addUndoableEditListener(e -> undoManager.addEdit(e.getEdit()));
    }

    // ファイルドロップハンドラ
    @SuppressWarnings("unchecked")
    class FileDropHandler extends DropTargetAdapter {
        @Override
        public void drop(DropTargetDropEvent dtde) {
            dtde.acceptDrop(DnDConstants.ACTION_COPY);
            try {
                java.util.List<File> droppedFiles = (java.util.List<File>) dtde.getTransferable()
                        .getTransferData(DataFlavor.javaFileListFlavor);
                for (File file : droppedFiles) {
                    openFile(file);
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    // ファイルを開くメソッド
    private void openFile(File file) {
        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            JTextArea textArea = new JTextArea();
            textArea.read(reader, null);
            JScrollPane scrollPane = new JScrollPane(textArea);
            tabbedPane.add(file.getName(), scrollPane);
            tabbedPane.setSelectedComponent(scrollPane);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            AdvancedTextEditor editor = new AdvancedTextEditor();
            editor.setVisible(true);
        });
    }
}

Java 電卓

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Calculator extends JFrame implements ActionListener {
    private JTextField display;
    private JPanel panel;
    private StringBuilder currentInput;
    private double result;
    private String operator;

    public Calculator() {
        // Frame settings
        setTitle("Calculator");
        setSize(400, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Display settings
        display = new JTextField();
        display.setEditable(false);
        display.setFont(new Font("Arial", Font.BOLD, 24));
        add(display, BorderLayout.NORTH);

        // Button panel settings
        panel = new JPanel();
        panel.setLayout(new GridLayout(4, 4));

        // Create and add buttons
        String[] buttons = {
            "7", "8", "9", "/",
            "4", "5", "6", "*",
            "1", "2", "3", "-",
            "0", ".", "=", "+"
        };

        for (String text : buttons) {
            JButton button = new JButton(text);
            button.setFont(new Font("Arial", Font.BOLD, 24));
            button.addActionListener(this);
            panel.add(button);
        }

        add(panel, BorderLayout.CENTER);

        currentInput = new StringBuilder();
        result = 0;
        operator = "";
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String command = e.getActionCommand();

        if ("0123456789.".contains(command)) {
            currentInput.append(command);
            display.setText(currentInput.toString());
        } else if (command.equals("=")) {
            calculate();
            display.setText(String.valueOf(result));
            currentInput.setLength(0);
        } else {
            if (currentInput.length() > 0) {
                calculate();
                operator = command;
                display.setText(String.valueOf(result));
                currentInput.setLength(0);
            }
        }
    }

    private void calculate() {
        double input = currentInput.length() > 0 ? Double.parseDouble(currentInput.toString()) : 0;

        switch (operator) {
            case "+":
                result += input;
                break;
            case "-":
                result -= input;
                break;
            case "*":
                result *= input;
                break;
            case "/":
                result /= input;
                break;
            default:
                result = input;
                break;
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            Calculator calculator = new Calculator();
            calculator.setVisible(true);
        });
    }
}
  1. javac Calculator.java
  2. java Calculator

Java メモ帳

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class SimpleNotepad extends JFrame implements ActionListener {
    private JTextArea textArea;
    private JMenuItem openItem, saveItem, exitItem;

    public SimpleNotepad() {
        // Frame settings
        setTitle("Simple Notepad");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Text area settings
        textArea = new JTextArea();
        JScrollPane scrollPane = new JScrollPane(textArea);
        add(scrollPane, BorderLayout.CENTER);

        // Menu bar creation
        JMenuBar menuBar = new JMenuBar();
        JMenu fileMenu = new JMenu("File");
        openItem = new JMenuItem("Open");
        saveItem = new JMenuItem("Save");
        exitItem = new JMenuItem("Exit");

        openItem.addActionListener(this);
        saveItem.addActionListener(this);
        exitItem.addActionListener(this);

        fileMenu.add(openItem);
        fileMenu.add(saveItem);
        fileMenu.add(exitItem);
        menuBar.add(fileMenu);
        setJMenuBar(menuBar);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == openItem) {
            openFile();
        } else if (e.getSource() == saveItem) {
            saveFile();
        } else if (e.getSource() == exitItem) {
            System.exit(0);
        }
    }

    private void openFile() {
        JFileChooser fileChooser = new JFileChooser();
        int option = fileChooser.showOpenDialog(this);
        if (option == JFileChooser.APPROVE_OPTION) {
            try (BufferedReader reader = new BufferedReader(new FileReader(fileChooser.getSelectedFile()))) {
                textArea.read(reader, null);
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(this, "File could not be opened", "Error", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    private void saveFile() {
        JFileChooser fileChooser = new JFileChooser();
        int option = fileChooser.showSaveDialog(this);
        if (option == JFileChooser.APPROVE_OPTION) {
            try (FileWriter writer = new FileWriter(fileChooser.getSelectedFile())) {
                textArea.write(writer);
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(this, "File could not be saved", "Error", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            SimpleNotepad notepad = new SimpleNotepad();
            notepad.setVisible(true);
        });
    }
}