-1

I want to read a simple a key - how can I add this? Please can anyone help?

public class Test {
  public static void main(String[] args) throws IOException{

    SetUp_JFrame SetUp_JFrame =new SetUp_JFrame();
    SetUp_JFrame.PART1(); 

    READ_KEY READ_KEY =new READ_KEY();
    for(;;) { 
       READ_KEY.PART2();  
            }
             }}



 class SetUp_JFrame {
     public JFrame f; 
  void PART1()throws IOException {

    f = new JFrame();
    f.setTitle("Test");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setSize(128,128);
    f.setVisible(true);
           }}

class READ_KEY {
  void PART2() {

    A = KeyPress
       System.out.println("You Pressed Key "+A);
    }
     }

stackoverflow asking for more detail not sure what more I can say? in Basic you would use something like

DO                                 
A=Inkey$                                         
Print A                                                       
Loop

Any help will be appreciated...

qfwfq
  • 2,416
  • 1
  • 17
  • 30
  • 1
    Learn basic Java coding conventions. 1) Don't use "_" in class or method names. Have you ever seen this in the Java API? 2) Don't use all upper case characters in class and method names. Again, have you ever seen this in the API? Learn by example and don't make up your own conventions. – camickr Jul 01 '17 at 14:34
  • You should start by reading some basic tutorials - [How to Use Key Bindings](http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html) and [How to write a key listener](https://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html) - there are numrous exampels around - also, you won't need the loop – MadProgrammer Jul 01 '17 at 21:53

1 Answers1

1

A simple way is to add a KeyListener to your JFrame.

f.addKeyListener(new KeyListener() {
    @Override
    public void keyTyped(KeyEvent e) {
    }

    @Override
    public void keyPressed(KeyEvent e) {
        System.out.println("Pressed =" + e.getKeyChar());
    }

    @Override
    public void keyReleased(KeyEvent e) {
    }
});

The more preferred way is to use Key Bindings

martinez314
  • 12,162
  • 5
  • 36
  • 63