Trying_To_Understand
Trying_To_Understand

Reputation: 161

Get an input from the user using graphics

I'm writting my first game and i want to add the name of the user to the high score chart. What is the best way to get the input from the user? except using JOption.

Needless to specify that i am drawing my game continuously. Maybe i can use JTextField?

Upvotes: 0

Views: 2883

Answers (1)

satnam
satnam

Reputation: 11494

Assuming you are rendering your game onto a JComponent, yes you can just add a JTextField onto your renderer component. Or you can render your own text field if you want to customize the look of everything.

To do a custom renderer:

Somewhere in your code, store the location of the text input box.

Rectangle r = new Rectangle(200,200,250,30);
String text = "";

In your rendering code:

public void paintComponent(Graphics g){
  g.setColor(Color.blue);
  g.fillRect(r.x, r.y, r.width, r.height);
  g.setColor(Color.black);
  // You can play with this code to center the text
  g.drawString(text, r.x, r.y+r.height);
}

Then you just need to add a keylistener somewhere in your constructor.

addKeyListener(new KeyAdapter(){
  public void keyPressed(KeyEvent e){
    text+=e.getKeyChar();

    //you might not need this is you are rendering constantly
    repaint();
  }
});

Upvotes: 1

Related Questions