What I'm trying to do is create in input box for a game I'm making that displays on-screen with a message such as
"Name: (input would appear here)"
What I did was pass in the message, which object I want my input to go to, and what function will use the variable(such as a function that sets the input to the player's name). Now, I could just access the input variable from the InputBox object, but, in the long run, this will be more efficient. I'm using Method.invoke
to pass the function into the object I want with the input string as an argument. Here is my code:
public class InputBox extends Textbox {
public String input = "";
private String out;
private Object obj;
private int lastLastKey = 0;
/**
*
* @param message
* @param cl The object/class where the output variable is.
* @param out The method to run. Only takes the input variable, so use this format: void toRun(String input)
*/
public InputBox(String message, Object obj, String out) {
super(message);
this.out = out;
this.obj = obj;
}
public void tick(Game game){
if (game.input.lastKey != 0 && !game.input.keys[KeyEvent.VK_ENTER]
&& !game.input.keys[KeyEvent.VK_SPACE] && !game.input.keys[KeyEvent.VK_SHIFT] && !game.input.keys[KeyEvent.VK_BACK_SLASH]){
if(game.input.lastKey != lastLastKey) input+=Character.toUpperCase((char) game.input.lastKey);
}else if(game.input.keys[KeyEvent.VK_ENTER] && !input.isEmpty() && !cleared){
Method method = null;
try {
method = obj.getClass().getMethod(out, new Class[]{ String.class, Object.class });
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
}
try {
method.invoke(obj, new Object[]{ input, obj });
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
cleared = true;
}
lastLastKey = game.input.lastKey;
}
public void render(Graphics g){
if(!cleared){
g.setColor(Color.white);
g.fillRect(10, Display.height-110, Display.width-20, 100);
g.setColor(Color.black);
g.drawRect(10, Display.height-110, Display.width-20, 100);
g.setFont(Game.smallFont);
FontMetrics fm = g.getFontMetrics();
g.drawString(message+" "+input, Display.width/2-fm.stringWidth(message+" "+input)/2, Display.height-50);
}
}
}