-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUnsplashGallery.java
More file actions
64 lines (52 loc) · 2.08 KB
/
Copy pathUnsplashGallery.java
File metadata and controls
64 lines (52 loc) · 2.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import com.google.gson.*;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.TilePane;
import javafx.stage.Stage;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class UnsplashGallery extends Application {
private static final String ACCESS_KEY = "rSzPecnF8pvlW3t1K6pUjJGPFXyWCg-Q0tRvBw7Gaj0"; // 🔑 Unsplash API key
private static final String API_URL = "https://api.unsplash.com/photos/random?count=10&client_id=" + ACCESS_KEY;
@Override
public void start(Stage primaryStage) throws Exception {
TilePane tilePane = new TilePane();
ScrollPane scrollPane = new ScrollPane(tilePane);
JsonArray photos = fetchImagesFromUnsplash();
if (photos != null) {
for (JsonElement photo : photos) {
String imageUrl = photo.getAsJsonObject()
.getAsJsonObject("urls")
.get("small")
.getAsString();
Image image = new Image(imageUrl, 200, 200, true, true);
ImageView imageView = new ImageView(image);
tilePane.getChildren().add(imageView);
}
}
Scene scene = new Scene(scrollPane, 800, 600);
primaryStage.setTitle("Unsplash Image Gallery");
primaryStage.setScene(scene);
primaryStage.show();
}
private JsonArray fetchImagesFromUnsplash() {
try {
URL url = new URL(API_URL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
JsonParser parser = new JsonParser();
JsonElement root = parser.parse(new InputStreamReader(conn.getInputStream()));
return root.getAsJsonArray();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
launch(args);
}
}