Skip to content
This repository was archived by the owner on Jun 19, 2024. It is now read-only.

Commit 2ee8d1b

Browse files
committed
More Javascript interaction examples
1 parent 219dc2e commit 2ee8d1b

File tree

2 files changed

+64
-1
lines changed

2 files changed

+64
-1
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package com.labymedia.ultralight.lwjgl3.opengl.js;
2+
3+
import java.util.Arrays;
4+
import java.util.List;
5+
6+
/**
7+
* Example class containing methods which Javascript can interact with.
8+
*/
9+
public class JSInteraction {
10+
private final String[] messages;
11+
12+
/**
13+
* Javascript can call varargs method as if they would be native.
14+
*
15+
* @param messages The message to store
16+
*/
17+
public JSInteraction(String... messages) {
18+
this.messages = messages;
19+
}
20+
21+
/**
22+
* Javascript can work on interface types without any issues.
23+
*
24+
* @return The stored messages as a list
25+
*/
26+
public List<String> getMessageList() {
27+
return Arrays.asList(messages);
28+
}
29+
30+
/**
31+
* Java arrays are translated to Javascript arrays automatically.
32+
*
33+
* @return The stored messages
34+
*/
35+
public String[] getMessageArray() {
36+
return messages;
37+
}
38+
}

example/lwjgl3-opengl/src/main/resources/example.js

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,9 @@ if(!counterFile.exists()) {
3838
}
3939
}
4040

41+
/**
42+
* Saves the counter to the counter.txt file.
43+
*/
4144
function saveCounter() {
4245
console.log(`Saving counter value ${counter}`);
4346

@@ -50,6 +53,28 @@ function saveCounter() {
5053
setInterval(() => {
5154
console.log(`Counter now at ${++counter}`);
5255
if(counter % 10 === 0) {
56+
// Save the counter every 10 seconds.
57+
// (Good enough for demo purposes)
5358
saveCounter();
5459
}
55-
}, 1000);
60+
}, 1000);
61+
62+
// Import the interaction class
63+
const JSInteraction = java.importClass("com.labymedia.ultralight.lwjgl3.opengl.js.JSInteraction");
64+
65+
// Instantiate using the varargs constructor
66+
const interaction = new JSInteraction("Hello, World!", "How are you doing?", "I hope you are fine.");
67+
68+
// Call the demo methods
69+
const messageList = interaction.getMessageList();
70+
const messageArray = interaction.getMessageArray();
71+
72+
// Since the list is not a Javascript own type, we have to use an indexed for loop
73+
for(let i = 0; i < messageList.size(); i++) {
74+
console.log(`messageList[${i}] = ${messageList.get(i)}`);
75+
}
76+
77+
// The array however has been fully translated
78+
for(const message of messageArray) {
79+
console.log(`messageArray[@] = ${message}`)
80+
}

0 commit comments

Comments
 (0)