How to Create a Java GUI App That Shows the Logged-in User and Hostname

  • Home /
  • Blog Posts /
  • How to Create a Java GUI App that shows the Logged-in User and Hostname

Create a new file called Application.java and paste the following:

import javax.swing.*;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class Application {
    public static void main(String...args) throws UnknownHostException {
        JFrame frame = new JFrame("Sample App");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300,300);

        String user = System.getProperty("user.name");
        String host = InetAddress.getLocalHost().getHostName();

        JTextArea txt = new JTextArea();
        txt.setText(
                "\n" +
                "  User: "+user+"\n" +
                "  Host: "+host+"\n"
        );
        frame.getContentPane().add(txt);

        frame.setVisible(true);
    }
}

Now open the terminal/command-line and type:

java Application.java

This will show a GUI application that will have a textarea with two lines of text:

  1. Your logged-in username
  2. The machine’s hostname