[Snippet] ButtonHandler - A cleaner and easier way to add button clicking
This will let you add buttons from any class, not just cramming them into ClickingButtons.java
That means that you can create completely independent classes you can share without having to make any edits to core PI files. Basically plug 'n play.
Add to ClickingButtons.java
Example of use: (This can be put anywhere)
That means that you can create completely independent classes you can share without having to make any edits to core PI files. Basically plug 'n play.
Code:
package server.model.players.buttons;
/*
* Author - Fritz (L Lawliet/TheRedArmy)
* Interface for a new button
*/
public interface Button {
/*
* What will be ran when the button is clicked
*/
public void onClick();
}
Code:
package server.model.players.buttons;
import java.util.*;
/*
* Author - Fritz (L Lawliet/TheRedArmy)
* Contains all of the registered buttons and methods to add and run them
*/
public class ButtonHandler {
/*
* Adds a button to the map
* @param id - The button's id
* @param btn - The button containing the onClick method
*/
public static void registerButton(int id, Button btn) {
gameButtons.put(id, btn);
}
/*
* Checks to see if the map contains the button and if it does, it runs the button's onClick method
* @param id - Id of the button
*/
public static void runButton(int id) {
if(gameButtons.get(id) != null) {
gameButtons.get(id).onClick();
}
}
/*
* Map containing all of the buttons and their ids
*/
public static HashMap<Integer, Button> gameButtons = new HashMap<Integer, Button>();
}
Code:
default: ButtonHandler.runButton(actionButtonId); break;
Example of use: (This can be put anywhere)
Code:
ButtonHandler.registerButton(1000, new Button() {
public void onClick() {
System.out.println("Button 1000 clicked!");
}
});