Keyboard inputs in java

Inputs from the keyboard in Java

In our game we want to allow the user to operate the game using the keyboard.

  • A common way to accomplish this is to use Java’s built-in KeyAdapter class. It is a class used to receive input from the keyboard.
  • Further, we will also use the built-in KeyEvent class. When a key is pressed, released, or typed, the relevant method activates in the listener object, and KeyEvent transferres then to it.
  • Finally, we then create a new class of our own, KeyInput, which will handle all button presses in the game.
[/vc_column_text][vc_empty_space height=”30px”][vc_separator type=”normal”][vc_empty_space height=”15px”][vc_column_text]

How to use Keyadapter in Java?

Start by importing the classes:

import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent;

Then we inherit the KeyAdapter class which allows you to take inputs from the keyboard (Remember inheritance?)

public class KeyInput extends KeyAdapter < Game game;

Additionally, we create the constructor that takes the game object as instance variable

Further, what will happen when a key is pressed? We attache pressing the button to the object called game

public void keyPressed(KeyEvent e)

Finally, what happens when a key is released? We attach that command to the object called game

public void keyReleased(KeyEvent e) < game.keyReleased(e); >>

The complete set of code is:

import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; public class KeyInput extends KeyAdapter < Game game; public KeyInput(Game game)< this.game = game; >public void keyPressed(KeyEvent e) < game.keyPressed(e); >public void keyReleased(KeyEvent e) < game.keyReleased(e); >>
[/vc_column_text][vc_empty_space height=”10px”][vc_separator type=”normal”][vc_empty_space height=”15px”][vc_column_text]

How use KeyEvent in Java?

We created our KeyInput class above that contains two methods, one for when we press a key and one for when we release a key. But now we want to make sure that the program actually detects which key is pressed.

Further, we will use the built-in methods VK_LEFT and VK_RIGHT found in KeyEvent to detect if it is the Left and Right arrow keys used.[/vc_column_text][vc_empty_space height=”40px”][vc_single_image image=”20081″ img_size=”large” alignment=”center” onclick=”link_image” qode_css_animation=””][vc_empty_space height=”40px”][vc_column_text]Let’s start by declaring a method for detecting if a key is pressed

public void keyPressed(KeyEvent e) < // New key press int key = e.getKeyCode(); // If we press right if (key == KeyEvent.VK_RIGHT) < System.out.println("The right arrow key is pressed"); // Or, if we press left >else if (key == KeyEvent.VK_LEFT) < System.out.println("The left arrow key is pressed"); >>

Additionally, what will happen when a key is released

public void keyReleased(KeyEvent e) < // New key has been released int key = e.getKeyCode(); // If we release the right key if(key == KeyEvent.VK_RIGHT)< System.out.println("The right arrow key is released"); >// If we release the left key else if(key == KeyEvent.VK_LEFT) < System.out.println("The left arrow key is released"); >>

Note, we can of course do the same for other keys. The Oracle KeyEvent page lists commands for the other keys

Finally, the complete set of code is:

public void keyPressed(KeyEvent e) < // New key press int key = e.getKeyCode(); // If we press right if (key == KeyEvent.VK_RIGHT) < System.out.println("The right arrow key is pressed"); // Or, if we press left >else if (key == KeyEvent.VK_LEFT) < System.out.println("The left arrow key is pressed"); >> public void keyReleased(KeyEvent e) < // New key has been released int key = e.getKeyCode(); // If we release the right key if(key == KeyEvent.VK_RIGHT)< System.out.println("The right arrow key is released"); >// If we release the left key else if(key == KeyEvent.VK_LEFT) < System.out.println("The left arrow key is released"); >>
[/vc_column_text][vc_empty_space height=”20px”][vc_separator type=”normal”][vc_empty_space height=”40px”][/vc_column][/vc_row][vc_row css_animation=”” row_type=”row” use_row_as_full_screen_section=”no” type=”full_width” angled_section=”no” text_align=”left” background_image_as_pattern=”without_pattern”][vc_column][vc_column_text]

Источник

Get a Keyboard Input in Java

Get a Keyboard Input in Java

  1. Getting Keyboard Input Using BufferedReader in Java
  2. Getting Keyboard Input Using Scanner Class in Java
  3. Getting Keyboard Input Using Console Class in Java
  4. Getting Keyboard Input Using command-line arguments in Java

This tutorial introduces how to get a keyboard input or user input in Java. We also included example programs to help you understand this topic better.

To get a user input in Java, you’ll encounter several classes such as the Scanner , BufferedReader , and Console . We’ll use these classes for our operation as we show you the different methods you can follow.

Getting Keyboard Input Using BufferedReader in Java

In this example, we used the BufferedReader class that takes the InputStreamReader class’s instance to read a user input. Here, the readLine() method reads the user input and returns a string as a result:

import java.io.BufferedReader; import java.io.InputStreamReader; public class SimpleTesting  public static void main(String[] args)   BufferedReader br = new BufferedReader(new InputStreamReader(System.in));  System.out.println("Enter Input : ");  try   String s = br.readLine();  System.out.println(s);  >catch(Exception e)   System.out.println(e);  >  > > 

Getting Keyboard Input Using Scanner Class in Java

The Scanner class is one of the simplest ways to get user input in Java. This class provides several built-in methods to get the input of various types like int and float. Here, we used the nextInt() method to get the int type of the input:

import java.util.Scanner; public class SimpleTesting  public static void main(String[] args)   System.out.println("Enter Input : ");  Scanner scanner = new Scanner(System.in);  int a = scanner.nextInt();  System.out.println(a);  scanner.close();  > > 

Getting Keyboard Input Using Console Class in Java

We can use the Console class to get user input in Java. This class belongs to the java.io package and provides the readLine() method to read user input from the console. See the example below:

import java.io.Console; public class Main  public static void main(String[] args)   Console console = System.console();  String str = console.readLine("Enter Input : ");  System.out.println(str);  > > 

Getting Keyboard Input Using command-line arguments in Java

In Java, command-line arguments are the arguments that are passed during program execution. The main() method of the program has a string-type parameter that holds the input supplied from the terminal. Remember to get the command-line argument to pass them during program execution and that the type of input is always a string type.

public class SimpleTesting  public static void main(String[] args)   if(args.length>0)   System.out.println("User Input");  for (int i = 0; i  args.length; i++)   System.out.println(args[i]);  >  >else System.out.println("No Input Found");  > > 

Run the code and pass the keyboard input as command-line arguments.

java SimpleTesting Hello DelftStack 
User Input Hello DelftStack 

Источник

Accepting keyboard input in Java is done using a Scanner object.

Consider the following statement

Scanner console = new Scanner(System.in)

This statement declares a reference variable named console. The Scanner object is associated with standard input device (System.in).

To get input from keyboard, you can call methods of Scanner class. For example in following statment nextInt() method of Scanner takes an integer and returns to variable x :

import java.util.Scanner; // Needed for Scanner class /** * This program demonstrates keyboard input. */ public class RectangleArea < public static void main(String[] args) < int length; // To hold rectangle's length. int width; // To hold rectangle's width. int area; // To hold rectangle's area // Create a Scanner object to read input. Scanner console = new Scanner(System.in); // Get length from the user. System.out.print("Enter length "); length = console.nextInt(); // Get width from the user. System.out.print("Enter width "); width = console.nextInt(); // Calculate area. area = length * width; // Display area. System.out.println("The area of rectangle is " + area); >>

Some other useful methods of Scanner class

Returns the next token as an int.

Returns the next token as a float.

Returns the next token as a long.

Finds and returns the next complete token as a string ended by a blank.

Returns the rest of the current line, excluding any line separator at the end.

import java.util.Scanner; /** * This program demonstrates various Scanner methods. */ public class ReadEmployee < public static void main(String[] args) < String name; // To hold the employee's name int age; // To hold the employee's age char gender; // To hold the employee's gender double salary; // To hold the employee's salary // Create a Scanner object to read input. Scanner console = new Scanner(System.in); // Get the employee's name System.out.print("Enter name: "); name = console.nextLine(); // Get the employee's age System.out.print("Enter age: "); age = console.nextInt(); // Get the employee's gender System.out.print("Enter gender: "); gender = console.next().charAt(0); // Get the employee's salary System.out.print("Enter salary: "); salary = console.nextDouble(); // Display the information System.out.println("Name: " + name + " Age: " + age + " Gender: " + gender + " Salary: " + salary); >>

Enter name: Alex Joseph
Enter age: 24
Enter gender: M
Enter salary: 8000
Name: Alex Joseph Age: 24 Gender: M Salary: 8000.0

Оцените статью