要在JavaFX中使用FXML与REST API进行交互,您可以遵循以下步骤:
- 添加依赖项 确保在项目的pom.xml文件中添加JavaFX和REST API客户端(如Apache HttpClient)的依赖项。
org.openjfx javafx-controls 17.0.1 org.apache.httpcomponents httpclient 4.5.13
-
创建FXML界面 创建一个FXML文件(例如:MyScene.fxml),并在其中添加所需的UI组件(如按钮、文本框等)。
-
编写控制器类 创建一个JavaFX控制器类(例如:MyController.java),并实现以下功能:
- 加载FXML文件
- 发送HTTP请求到REST API
- 处理API响应并更新UI
import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class MyController { @FXML private TextField apiUrlField; @FXML private Button fetchButton; @FXML private Label resultLabel; private CloseableHttpClient httpClient = HttpClients.createDefault(); @FXML public void initialize() { fetchButton.setOnAction(event -> fetchData()); } private void fetchData() { String apiUrl = apiUrlField.getText(); if (apiUrl == null || apiUrl.isEmpty()) { resultLabel.setText("Please enter a valid API URL."); return; } HttpGet request = new HttpGet(apiUrl); try { HttpResponse response = httpClient.execute(request); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 200) { HttpEntity entity = response.getEntity(); String result = EntityUtils.toString(entity); resultLabel.setText(result); } else { resultLabel.setText("Error: " + statusCode); } } catch (Exception e) { resultLabel.setText("Error: " + e.getMessage()); } finally { try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } } }
- 绑定控制器与FXML 在主应用程序类(例如:MainApp.java)中,将控制器与FXML文件关联。
import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; public class MainApp extends Application { @Override public void start(Stage primaryStage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource("MyScene.fxml")); primaryStage.setTitle("JavaFX REST API Example"); primaryStage.setScene(new Scene(root)); primaryStage.show(); } public static void main(String[] args) { launch(args); } }
现在,当用户在FXML界面中输入API URL并点击“Fetch”按钮时,控制器将发送HTTP请求到REST API,并将响应结果显示在界面上。