JavaFX Long pressButton - javafx

I'm currently building a Mobile app in JavaFx with the GluonMobile plugins and I try to find a way to know if the user just tap the button or if the button is pressed for over 2 second.
I try a couple of thing and I run into some problem.
The thing is I found this method on the web and he's my problem
First the code
button.addEventFilter(MouseEvent.ANY, new EventHandler<MouseEvent>() {
long startTime;
#Override
public void handle(MouseEvent event) {
if (event.getEventType().equals(MouseEvent.MOUSE_PRESSED)) {
startTime = System.currentTimeMillis();
} else if (event.getEventType().equals(MouseEvent.MOUSE_RELEASED)) {
if (System.currentTimeMillis() - startTime > 2 * 1000) {
System.out.println("Pressed for at least 2 seconds (" + (System.currentTimeMillis() - startTime) + " milliseconds)");
} else
System.out.println("Pressed for " + (System.currentTimeMillis() - startTime) + " milliseconds");
}
}
});
The problem that I have here is really weird.
When I click the button the method work.
If I click for over 2 sec it will printLn the good result.
BUT
If I click a second time on it it will print the PrintLn 2 times.
If I click a 3rd time, it will print the result 3 time...
So the problem is when I put a method (let's say a dialogBox) the box will show 3 times.
It's like if the program had a memory of how many time I click it and give me the result the number of time I click the button.
Can I "reset" the memory of the method?
Thanks.
Jc
EDIT
#FXML
public void buttonClick(ActionEvent actionEvent) {
btn1.addEventFilter(MouseEvent.ANY, new EventHandler<MouseEvent>() {
long startTime;
#Override
public void handle(MouseEvent event) {
if (event.getEventType().equals(MouseEvent.MOUSE_PRESSED)) {
startTime = System.currentTimeMillis();
} else if (event.getEventType().equals(MouseEvent.MOUSE_RELEASED)) {
if (System.currentTimeMillis() - startTime > 2 * 1000) {
System.out.println("Pressed for at least 2 seconds (" + (System.currentTimeMillis() - startTime) + " milliseconds)");
} else
System.out.println("Pressed for " + (System.currentTimeMillis() - startTime) + " milliseconds");
}
}
});
}

Related

Firebase Dynamic Links in Unity

Where should I put this chunk of code in order the listener function works every time I enter the app from the deep link?
Now in my unity mobile app I have this code in the initial load, however it does not work well.
The first case of entering the app from the deep link is not being handled. Only after initial load when I click the deep link my listener function works (as the listener is already set).
Is there any solution to this issue?
void Start()
{
DynamicLinks.DynamicLinkReceived += OnDynamicLink;
}
// Display the dynamic link received by the application.
void OnDynamicLink(object sender, EventArgs args)
{
var dynamicLinkEventArgs = args as ReceivedDynamicLinkEventArgs;
Debug.LogFormat("Received dynamic link {0}", dynamicLinkEventArgs.ReceivedDynamicLink.Url.OriginalString);
}
Test this, feel free to edit.
void Start()
{
StartCoroutine(WaitLoader()); //Loader
}
public void trueAwoken()
{
DynamicLinks.DynamicLinkReceived += OnDynamicLink;
}
public IEnumerator WaitLoader()
{
int i = 0;
while (i < 5) // Potential for true load state 5 (increase this 0-1000+?, it depends on your build?)
{
i++;
//Debug.Log("Waiting: " + i + "/" + Time.deltaTime);
yield return new WaitForFixedUpdate();
}
trueAwoken();
}

Every other rectangle detects the collison in my Java FX game

Okay so I have this little mock up game of clash royale and when I click to spawn a character and move him across the bridge on pane, I have a enemy on the bridge and my character stops as he should.
BUT, if I click to spawn my second character BEFORE he gets to enemy then the FIRST character moves through enemy and goes to tower.
Now, what I want to do is detect for every character, and they should all act the same. Not too sure what is going on here but I am needing a little assistance as this is the first game I've really made before.
private void createCharacter(CHARACTER choosenCharacter) {
gamePane.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
if (elixir > 4) {
character = new ImageView(choosenCharacter.getUrl());
healthbar = new Rectangle(50.0, 10.0, Color.BLUE);
character.setLayoutX(event.getSceneX() - 40);
character.setLayoutY(event.getSceneY() - 110);
healthbar.setLayoutX(event.getSceneX() - 40);
healthbar.setLayoutY(event.getSceneY() - 110);
System.out.println(event.getSceneX() + "\n" + event.getSceneY());
elixir = elixir - 6;
if (detectCollision()){
gameTimer.stop();
}
createGameLoop(character, healthbar);
gamePane.getChildren().add(character);
gamePane.getChildren().add(healthbar);
}
}
});
}
private void moveCharacter(ImageView character, Rectangle health) {
if (character.getLayoutX() > 180 && character.getLayoutX() < 450) {
character.setLayoutX(character.getLayoutX() - 2);
}
if (health.getLayoutX() > 180 && health.getLayoutX() < 450) {
health.setLayoutX(health.getLayoutX() - 2);
}
if (character.getLayoutX() <= 200 && character.getLayoutY() > 2) {
character.setLayoutY(character.getLayoutY() - 2);
}
if (health.getLayoutX() <= 200 && health.getLayoutY() > 2) {
health.setLayoutY(health.getLayoutY() - 2);
}
if (character.getLayoutX() < 700 && character.getLayoutX() >= 450) {
character.setLayoutX(character.getLayoutX() + 2);
}
if (health.getLayoutX() < 700 && health.getLayoutX() >= 450) {
health.setLayoutX(health.getLayoutX() + 2);
}
if (character.getLayoutX() >= 700 && character.getLayoutY() > 2) {
character.setLayoutY(character.getLayoutY() - 2);
}
if (health.getLayoutX() >= 700 && health.getLayoutY() > 2) {
health.setLayoutY(health.getLayoutY() - 2);
}
}
private void createGameLoop(ImageView character, Rectangle health) {
gameTimer = new AnimationTimer() {
#Override
public void handle(long now) {
if (detectCollision()){
gameTimer.stop();
}
moveCharacter(character, health);
}
};
gameTimer.start();
}
As you can see it's not the cleanest code but I need some way to detect each instance of my game character and I'm just not able to think of how to solve this little problem of mine. Any suggestions on how to handle something like this would be greatfully appreciated. Thanks!

nested progress tasks into one progressbar javafx

Is it possible to render in one progressbar the progress of 2 nested tasks?
I mean, if I have to read lines from several files in several directories. I have this snippet code:
EDIT:
final int steps = directories.size();
Task<Integer> task2 = new Task<Integer>() {
/**
*/
#Override
protected Integer call() throws Exception {
int len = files.length;
updateProgress(0, len);
for(int i = 0; i < files.length; i++) {
final String filename = files[i].getName();
final String file = files[i].getPath();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
}
String currentLine = null;
while ((currentLine = br.readLine()) != null) {
readlines(currentLine, filename);
}
} catch (IOException xs) {
xs.getMessage();
}
System.out.println("******* Working on: " + file + " ******************************");
updateProgress(i + 1, files.length);
}
System.out.println("done: " + directoryName);
return len;
}
};
task2.setOnRunning(r -> {
DoubleBinding totalProgress = null;
for(int i = 0; i < steps; i++) {
DoubleBinding increment = task2.progressProperty().divide(steps);
if (totalProgress == null) {
totalProgress = increment;
} else {
totalProgress = totalProgress.add(increment);
}
}
progressBar.progressProperty().bind(totalProgress);
status.textProperty().bind(task2.stateProperty().asString());
statusProcess.textProperty().bind(Bindings.when(totalProgress.isEqualTo(-1))
.then("0.00")
.otherwise(task2.progressProperty().multiply(100.00).asString("%.02f %%")));
console.textProperty().bind(task2.messageProperty());
});
new Thread(task2).start();
I am enable to access progress bar but as long as I have directories, the progress bar will restart to 0 and will check for files into the next directory and then populate the progress bar until 1 and then restart to 0 if there is another directory.
How can I do if I want to display these 2 tasks in one as I don't want to restart from 0 when the next directory is reading. If I have for example 4 directories, I expect to see a moving the progressbar until its quarter and so on.
Is anybody as an idea what I am doing wrong?
You can do something like
progressBar.progressProperty().bind(Bindings.createDoubleBinding(
() -> Math.max(0, task1.getProgress()) / 2 + Math.max(0, task2.getProgress()) /2 ,
task1.progressProperty(), task2.progressProperty());
If you can easily estimate or compute the relative times each task will take, you can weight the progress of each task accordingly, instead of simply averaging them as in the code above.

Display a message to a specific player in a networked game using Photon Unity Networking

On entering a trigger zone of an object a message is displayed to the player (which is found by tag). If the player then presses the pickup button, the item is added to their inventory. It works fine in single-player games.
When I use PUN (Photon Networking) though it displays it to all players (as all player's script detect the event) and all players can pickup the item. How I can fix this problem?
I believe fixing this piece will enable me to understand how to fix everything else:
void OnTriggerEnter(Collider col)
{
if (col.gameObject.tag == "Player")
{
displayMessage = true;
}
}
void OnTriggerExit(Collider col)
{
if (col.gameObject.tag == "Player")
{
displayMessage = false;
}
}
bool stop = false;
void OnGUI()
{
if (displayMessage)
{
if (GameObject.FindGameObjectWithTag("UInventory").GetComponent<UInventory>().inventoryMode == "Weight")
{
GUI.Label(new Rect((Screen.width/2)-200, (Screen.height/2)-30, 200, 45), "Press " + pickUpItem.ToString() + " To Take " + itemName + "(" + itemWeight + "kg)");
}
else
{
GUI.Label(new Rect((Screen.width/2)-200, (Screen.height/2)-30, 200, 45), "Press " + pickUpItem.ToString() + " To Take " + itemName);
}
}
}
Trigger code should be executed only if client owns network object. Use 'isMine' property of 'PhotonView' component of the object to check if this is true.

OUT OF MEMORY ERROR with "Android-Universal-Image-Loader"

I made gridview with Android-Universal-Image-Loader
and, when I select a picture, it's goes on the imageview.
when I select it first, it works fine. but the second one is crashed. (out of memory)
I load over 1M size image (originally took by default camera)
here is code to initialize
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
.memoryCacheExtraOptions(480, 800) // default = device screen dimensions
.discCacheExtraOptions(480, 800, CompressFormat.JPEG, 75)
.taskExecutor(AsyncTask.THREAD_POOL_EXECUTOR)
.taskExecutorForCachedImages(AsyncTask.THREAD_POOL_EXECUTOR)
.threadPoolSize(3) // default
.denyCacheImageMultipleSizesInMemory()
.memoryCacheSize(2 * 1024 * 1024)
.discCacheSize(50 * 1024 * 1024)
.discCacheFileCount(100)
.enableLogging()
.build();
and here is get uri when it's selected
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// when clicked image
//startImagePagerActivity(position);
//URI imageUri = URI.parse("android.resource://com.kmob.camera/" + parent.getItemIdAtPosition(position));
SignUp.profilePath = Uri.parse(imageUrls[position].substring(7)); // return selected uri except prefix, "file://"
Log.v("OWL", "selected file: " + imageUrls[position].substring(7));
finish();
}
});
and here is result for activity
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
//mProfile.notifyAll();
if(profilePath.getPath().toString().length()>0){
mProfile.setImageURI(profilePath);
}
}
Thanks in advance,
According to the author suggestion mention the following two lines in displayoptions
.imageScaleType(ImageScaleType.IN_SAMPLE_INT)
.bitmapConfig(Config.RGB_565) in displayioptions.
And in configuration
.memorycache(new WeakMemoryCache())

Resources