
import java.awt.BorderLayout;
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import javax.swing.*;

/**
 * Demo to show how to create and run a Java IDE (IntelliJ, Eclipse, NetBeans) plug-in in just a few lines
 * using https://www.japplis.com/applet-runner/ IDE plug-in
 *
 * Compile: javac ExampleApplet.java
 * Run in IDE: Applet Runner -> Tool bar Open File button -> Select ExampleApplet.class -> Done
 */
public class ExampleApplet extends JApplet {

    @Override
    public void start() {
        Path classFileDirectory = null;
        try {
            classFileDirectory = Path.of(getClass().getProtectionDomain().getCodeSource().getLocation().toURI());
        } catch (Exception ex) {
            classFileDirectory = Path.of(System.getProperty("user.dir"));
        }
        JLabel jlMessage = new JLabel("Single file Applet that can run in Java IDE's");
        JTextArea jtaCode = new JTextArea(10, 60);
        Path exampleFile = classFileDirectory.resolve("ExampleApplet.java");
        try {
            String exampleCode = Files.readString(exampleFile);
            jtaCode.setText(exampleCode);
        } catch (IOException ex) {
            jtaCode.setText("Cannot read file: " + exampleFile + ".\n" + ex.getMessage());
        }
        JButton jbGoToFile = new JButton("Go To Applet Runner website");
        jbGoToFile.addActionListener(ae -> {
            try {
                Desktop.getDesktop().browse(new URI("https://www.japplis.com/applet-runner/"));
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, "Cannot open website");
            }
        });

        setLayout(new BorderLayout());
        add(jlMessage, BorderLayout.NORTH);
        add(new JScrollPane(jtaCode), BorderLayout.CENTER);
        add(jbGoToFile, BorderLayout.SOUTH);
    }

    public void packAndShow(String title) {
        init();
        start();
        JFrame frame = new JFrame(title);
        frame.setContentPane(getContentPane());
        frame.setJMenuBar(getJMenuBar());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    // Launch the same application from command line or via a desktop link or from the IDE
    public final static void main(String[] args) {
        ExampleApplet applet = new ExampleApplet();
        SwingUtilities.invokeLater(() -> applet.packAndShow("Example Applet"));
    }
}
