Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.FileReader;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JToolBar;
import javax.swing.border.EmptyBorder;

public class Main {
    JPanel gui = new JPanel(new BorderLayout());
    JFileChooser fileChooser;
    private JTextArea output = new JTextArea(10, 40);

    Main() {
        gui.setBorder(new EmptyBorder(2, 3, 2, 3));

        String userDirLocation = System.getProperty("user.dir");
        File userDir = new File(userDirLocation);
        // default to user directory
        fileChooser = new JFileChooser(userDir);

        Action open = new AbstractAction("Open") {
            @Override
            public void actionPerformed(ActionEvent e) {
                int result = fileChooser.showOpenDialog(gui);
                if (result == JFileChooser.APPROVE_OPTION) {
                    try {
                        File f = fileChooser.getSelectedFile();
                        FileReader fr = new FileReader(f);
                        output.read(fr, f);
                        fr.close();
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            }
        };

        Action save = new AbstractAction("Save") {
            @Override
            public void actionPerformed(ActionEvent e) {
                int result = fileChooser.showSaveDialog(gui);
                System.out.println("Not supported yet.");
            }
        };

        JToolBar tb = new JToolBar();
        gui.add(tb, BorderLayout.PAGE_START);
        tb.add(open);
        tb.add(save);

        gui.add(new JScrollPane(output));
    }

    public JComponent getGui() {
        return gui;
    }

    public static void main(String[] args) {
        Main cicd = new Main();
        JFrame f = new JFrame("Chooser In Current Dir");
        f.add(cicd.getGui());
        f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        f.pack();
        f.setVisible(true);
    }
}