Source of MyLocalIPAddressGUIApp.java


  1: //MyLocalIPAddressGUIApp.java
  2: //Finds the IP address of your local machine.

  4: import java.awt.*;
  5: import java.awt.event.*;
  6: import java.net.*;
  7: import javax.swing.*;

  9: public class MyLocalIPAddressGUIApp extends JFrame
 10: implements ActionListener
 11: {
 12:     private JButton btnDisplayIp;
 13:     private JTextField txtIpAddress;
 14:     private JButton exit;

 16:     public static void main(String [] args)
 17:     {
 18:         MyLocalIPAddressGUIApp app = new MyLocalIPAddressGUIApp();
 19:         app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 20:         app.makeGUI();
 21:         app.setSize(300, 120);
 22:         app.setVisible(true);
 23:     }

 25:     public void makeGUI()
 26:     {
 27:         getContentPane().setLayout(new GridLayout(3, 1));

 29:         btnDisplayIp = new JButton("Click to Display Local IP Address");
 30:         txtIpAddress = new JTextField();
 31:         btnDisplayIp.addActionListener(this);
 32:         txtIpAddress.addActionListener(this);
 33:         getContentPane().add(btnDisplayIp);
 34:         getContentPane().add(txtIpAddress);

 36:         exit = new JButton("Exit");
 37:         getContentPane().add(exit);
 38:         exit.addActionListener(this);
 39:     }

 41:     public void actionPerformed(ActionEvent event)
 42:     {
 43:         if (event.getSource() == exit) System.exit(0);

 45:         try
 46:         {
 47:             InetAddress address = InetAddress.getLocalHost();
 48:             txtIpAddress.setText(address.toString());
 49:         }
 50:         catch (UnknownHostException e)
 51:         {
 52:             txtIpAddress.setText("Could not find the local address");
 53:         }
 54:     }
 55: }