javafx 如何调用FXML 元素 进行网络请求
时间: 2024-02-11 20:30:58 浏览: 105
在FXML文件中,可以使用fx:id属性为元素命名,并使用Controller类中的@FXML注释将其映射到变量。在Controller类中,可以使用JavaFX的HTTP请求库或其他网络请求库来执行网络请求。例如,可以使用以下代码从Controller类中获取FXML元素,并使用JavaFX的HTTP请求库执行GET请求:
FXML文件:
```
<Button fx:id="myButton" text="Click me!" onAction="#handleButtonClick"/>
```
Controller类:
```
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.event.ActionEvent;
import javafx.fxml.Initializable;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.concurrent.Task;
import javafx.concurrent.WorkerStateEvent;
import javafx.event.EventHandler;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MyController implements Initializable {
@FXML
private Button myButton;
@Override
public void initialize(URL location, ResourceBundle resources) {
// TODO Auto-generated method stub
}
@FXML
private void handleButtonClick(ActionEvent event) {
Task<String> task = new Task<String>() {
@Override
protected String call() throws Exception {
URL url = new URL("http://www.example.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
int responseCode = conn.getResponseCode();
if (responseCode == 200) {
return "Success";
} else {
return "Failure";
}
}
};
task.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
@Override
public void handle(WorkerStateEvent event) {
String result = task.getValue();
// do something with the result
}
});
new Thread(task).start();
}
}
```
在上面的示例中,当用户单击按钮时,将执行handleButtonClick方法。此方法创建一个Task对象,该对象使用JavaFX的HTTP请求库执行GET请求。请求完成后,将触发Task对象的OnSucceeded事件,该事件将处理请求结果。您可以在此方法中执行任何其他所需的操作,例如更新UI元素。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)