Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;

import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;

public class Main extends JPanel {
    JTextField fileField = new JTextField(20);
    JButton showDialog = new JButton(new ShowDialogAction("Show Dialog", KeyEvent.VK_D, this));

    public Main() {
        fileField.setEditable(false);
        fileField.setFocusable(false);
        add(new JLabel("File Selected:"));
        add(fileField);
        add(showDialog);
    }

    public void setFileFieldText(String text) {
        fileField.setText(text);
    }

    public static void main(String[] args) {
        Main mainPanel = new Main();
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setVisible(true);
    }
}

class ShowDialogAction extends AbstractAction {
    private Main swingFoo;

    public ShowDialogAction(String name, int mnemonic, Main swingFoo) {
        super(name);
        putValue(MNEMONIC_KEY, mnemonic);
        this.swingFoo = swingFoo;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        MyPanel patientPicker = new MyPanel();
        int result = JOptionPane.showConfirmDialog(swingFoo, patientPicker, "Select Something",
                JOptionPane.OK_CANCEL_OPTION);
        if (result == JOptionPane.OK_OPTION) {
            swingFoo.setFileFieldText(patientPicker.getSelectedItem());
        }
        patientPicker.setVisible(true);
    }
}

class MyPanel extends JPanel {
    private static final String[] ITEMS = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" };
    private JList<String> selectionList = new JList<>(ITEMS);

    public MyPanel() {
        add(new JScrollPane(selectionList));
        selectionList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    }

    public String getSelectedItem() {
        return selectionList.getSelectedValue();
    }

}