-1

how i can check for an keyboard input inside the actionPerformed method or chek for input from the keyboard and sent the result to the actionPerformed method?

i have 3 files:

main that just call new JFrame:

  public class Main {
      public static void main(String[] args) {
          new myJFrame();
      }
  }

myJframe:

public class myJFrame extends JFrame {
myJPanel panel;

    myJFrame(){
        panel = new myJPanel();
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.add(panel);
        this.pack();
        this.setLocationRelativeTo(null);
        this.setVisible(true);
    }
}

and myJPanel:

    public class myJPanel extends JPanel implements ActionListener {
        final int PANEL_WIDTH = 500;
        final int PANEL_HEIGHT = 500;
        final int SNAKE_WIDTH = 25;
        final int SNAKE_HEIGHT = 25;
        JPanel snakeBody;
        Timer timer;
        int xVelocity = 1;
        int yVelocity = 1;
        int xPosition = 250;
        int yPosition = 250;
    
        myJPanel(){
            snakeBody = new JPanel();
            this.setPreferredSize(new Dimension(PANEL_WIDTH, PANEL_HEIGHT));
            timer = new Timer(10, this);
            timer.start();
    
        }
    
        public void paint(Graphics g){
            super.paint(g); // paint background.
            Graphics2D g2D = (Graphics2D) g;
            g2D.fillRect(xPosition, yPosition, SNAKE_WIDTH, SNAKE_HEIGHT);
    
        }
    
        @Override
        public void actionPerformed(ActionEvent e) {
            repaint();
        }
}
Tim Asher
  • 57
  • 5
  • 1
    Yep [Key Bindings](https://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html) are the answers – MadProgrammer May 29 '23 at 12:43
  • asides: so not hard-code sizing hints, do not override paint (instead override paintComponent), stick to java naming conventions – kleopatra May 29 '23 at 19:08

1 Answers1

1

Use key bindings to change a state field, perhaps one that determines direction, and then a timer's ActionListener to query this state field and use it to select a direction to move.

I recommend that you use key bindings (check the tutorial link), to show how to do this.

Side note: best to not override paint but rather paintComponent, since this will give you double-buffering out of the box and should result in smoother animation.

For example

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373