Search code examples
javaswingconcurrencyjtextfield

How do I send String to JTextField from helper class?


For example in the following code i want to change the JTextField to show whether the port im scanning is open or not but i dont know how to go about doing this. Maybe i need some helper methods?

public void actionPerformed(ActionEvent arg0) {
  console.setText("Starting check\n" +
    "Start = "+stopServTf.getText()+
    "\nStop ="+stopServTf.getText()+
    "\nPort Start ="+startPortTf.getText()+
    "\nPort Stop ="+stopPortTf.getText());
  PortScanner p= new PortScanner(Integer.parseInt(startPortTf.getText()),
    Integer.parseInt(stopPortTf.getText()),startServTf.getText());
}

and the other method/constructor

public   PortScanner(int portStart, int portStop ,String ip) {
  for (int i = portStart; i <= portStop; i++) {
    try {
      Socket ServerSok = new Socket(ip, i);
      setString(i);
      //System.out.println("Port in use: " + i);
      ServerSok.close();
    } catch (Exception e) {
    }
    setStrinN(i);
    System.out.println("Port not in use: " + i);
  }
}

public static String setString(int i) {
  return "Port in use: " +i;
}

public static String setStrinN(int i){
  return "Port not in use: "+i;
} 

So that I want to send to console.setText();


Solution

  • When you are calling setString(i);, that function returns a string that you discard (i.e. do not store anywhere). You either need to store the string and retrieve it later, ot if you want to call console.setText() with that returned string, you need to pass console to the PortScanner constructor:

    public PortScanner(int portStart, int portStop, String ip, JTextArea console)
    

    and change the call to setString(i); to

    console.setText(setString(i));
    

    Furthermore (as the PortScanner constructor has changed), call

     PortScanner p= new PortScanner(Integer.parseInt(startPortTf.getText()),
       Integer.parseInt(stopPortTf.getText()),startServTf.getText()); 
    

    in actionPerformed()