Search code examples
javainput2d-games

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?


Solution

  • 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();
      }
    });