Limbo
Limbo

Reputation: 91

Input methods other than using Scanner class?

The only way I know to get a user input is by using the Scanner Class in my code, which (I believe) only contains these methods:

What if I want an input that doesn't requires the keyboard and proceeds only if the user clicks on the screen (for instance), how am I supposed to do that?

Upvotes: 5

Views: 1667

Answers (3)

Kick Buttowski
Kick Buttowski

Reputation: 6739

You can achieve this in Java 8 by using lambda expression.

Code:

public class ListenerTest {
   public static void main(String[] args) {

  JButton testButton = new JButton("Test Button");

 testButton.addActionListener(e -> { 
   System.out.println("Click Detected by Lambda Listner");
 });

 // Swing stuff
 JFrame frame = new JFrame("Listener Test");
 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 frame.add(testButton, BorderLayout.CENTER);
 frame.pack();
 frame.setVisible(true);

}
  }

Source:

http://blueskyworkshop.com/topics/Java-Pages/lambda-expression-basics/

Tutorial

http://docs.oracle.com/javase/tutorial/uiswing/events/

Upvotes: 0

Vince
Vince

Reputation: 15146

Scanner is usually used to easily grab user input from the console. This is not used for mouse/key inputs.

If using Swing, you could add a KeyListener and MouseListener to your panel, which will trigger event methods containing code that you write.

JPanel panel = new JPanel();
panel.addKeyListener(new KeyListener() {
    public void keyPressed(KeyEvent e) {
         int keyCode = e.getKeyCode();

         switch(keyCode) {
             case KeyEvent.VK_UP:
                 // the up arrow key was pressed
                 break;
         }
    }

    //implement other methods
});

I highly suggest you look into listeners: Introduction to Event Listeners

If you aren't using GUI, look into JNativeHook, which comes with a NativeKeyListener and NativeMouseListener. They listen for input at any time, since they are added to your screen instead of a component.

GlobalScreen.getInstance().addKeyListener(new NativeKeyListener() {
    public void keyPressed(NativeKeyEvent e) {

    }

    //implement other methods
});

Upvotes: 2

Georgie
Georgie

Reputation: 61

One of the method to input using keyboard is to implement KeyListener, which offers the following methods:

  • keyTyped(KeyEvent e), which does a particular action when the key is typed.

  • keyPressed(KeyEvent e), which does a particluar action when the key is pressed.

  • keyReleased(KeyEvent e), which does a particular action when the key is released.

Hope this helped.

Upvotes: 1

Related Questions