要在JavaFX中使用FXML与REST API进行交互,您可以遵循以下步骤:
<dependencies>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-controls</artifactId>
<version>17.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
</dependencies>
创建FXML界面 创建一个FXML文件(例如:MyScene.fxml),并在其中添加所需的UI组件(如按钮、文本框等)。
编写控制器类 创建一个JavaFX控制器类(例如:MyController.java),并实现以下功能:
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();
}
}
}
}
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,并将响应结果显示在界面上。