Search code examples
javaswinguser-interfaceipjtextfield

Set IP address inside JTextField in JAVA


I have this simple GUI in JAVA and i want to put inside the JTextField a string that contains the IP of my local machine.

I tried to get the IP with this command :

InetAddress.getLocalHost().getHostAddress();

and to store it inside a string , and to put the string inside the JTextField I have tried using gettext() and settext(), but without success.

The code :

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

import java.awt.FlowLayout;

public class GuiLearn extends JFrame {
    private JLabel label;
    private JTextField textfield;

    public GuiLearn () {
        setLayout (new FlowLayout());

        textfield = new JTextField("This is where the IP address should be...");
        add(textfield);
    }

    public static void main (String args[]) {
        GuiLearn yuvi = new GuiLearn();

        yuvi.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        yuvi.setSize(400,400);
        yuvi.setVisible(true);
        yuvi.setTitle("guiiiiiii");
    }
}

please help..


Solution

  • When you instantiate your JTextField, the String argument you pass into the constructor will set the text for you. Since InetAddress.getLocalHost().getHostAddress() returns a String, you can simply pass it in as a constructor argument to the JTextField.

    this.textfield = new JTextField(InetAddress.getLocalHost().getHostAddress());
    

    Or you can simply call this.textField.setText(InetAddress.getLocalHost().getHostAddress()) at any point after you have instantiated the object.