我遇到了一些麻烦,无法真正找到回答。
我需要经常将字符串添加到TextArea。字符串来自其他类/对象。
我的想法:
@FXML
private static TextArea TAactivity;
public static void activity(String s) {
TAactivity.appendText(s);
}
并从其他类写入:
MainController.activity("Random stuff");
我做错了什么?
问候
//修改
public class Main extends Application {
private final int PORT = 4000;
private final String SERVER = "127.0.0.1";
public static Client client;
@Override
public void start(Stage primaryStage) throws Exception{
client = new Client(SERVER, PORT);
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
primaryStage.setTitle("JJFTP Client");
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
}
public class Client {
private String server;
private int port;
public Client(String s, int p) throws InterruptedException, IOException {
server = s;
port = p;
}
public String messagefromserver() throws IOException {
Controller.c.activity("Waiting for message from server");
StringBuilder sb;
Socket socket = new Socket(server, port);
DataInputStream ASCIIin = new DataInputStream(socket.getInputStream());
int inputlength = ASCIIin.readInt();
sb = new StringBuilder();
for (int i = 0; i < inputlength; i++) {
int temp = ASCIIin.readInt();
if (temp < 0) {
throw new IllegalArgumentException();
}
sb.append((char) temp);
}
Controller.c.activity("Received -" + sb + "- from server");
ASCIIin.close();
socket.close();
return sb.toString();
}
}
public class Controller implements Initializable {
public static Controller c;
@FXML
private TextArea TAfiles;
@FXML
private TextField TFcmd;
@FXML
private TextArea TAactivity;
@FXML
public void send() throws Exception {
String s = TFcmd.getText();
TFcmd.setText("");
Main.client.messagetoserver(s);
String answere = Main.client.messagefromserver();
if (answere.equals("FILE")) {
StringBuilder sb = new StringBuilder();
sb.append(s);
sb.delete(0, 9);
Main.client.downloadfile(String.valueOf(sb));
updatefilelist();
activity("Filelist updated");
}
}
public void activity(String s) {
System.out.println(s);
TAactivity.setText(TAactivity.getText() + "\n" + s);
}
@Override
public void initialize(URL location, ResourceBundle resources) {
c=new Controller();
try {
updatefilelist();
} catch (IOException e) {
e.printStackTrace();
}
}
}
当然有更多方法,但我猜不是所有方法都是必要的。如果我从Client和/或对象的对象中删除静态,它表示它不能从非静态上下文中引用静态的东西。