move frames by keyboard input

Asked 2 years ago, Updated 2 years ago, 123 views

When you press the arrow on your keyboard, you are creating a program where the displayed frame moves 10 times in that direction.The input of the keyboard is detected, but the frame does not move.How can I move?The program you created below.

// Import File
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;

// Main Class

public class framing
{

    int x = 100;
    inty = 100;

 // Main Method
 public static void main (String[]args)
 {
  framing test = new framing();
 }
 // constructor
 public framing()
 {

 // Basic frame configuration.
 JFrame frame = new JFrame();
 frame.setSize(250,250);
 frame.setLocation(x,y);
 frame.setTitle("Key_test");
 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 frame.setVisible(true);

 // Keyboard Listener Settings
// Register to receive keyboard input in frame
  frame.addKeyListener(newKeyboard_input());

 }

// Class for Keyboard

class Keyboard_input implements KeyListener
{
    public void keyPressed (KeyEvente)
    {
        System.out.println("keyPressed.");

        switch(e.getKeyCode()) {
        caseKeyEvent.VK_UP:y=y-10;break;
        caseKeyEvent.VK_RIGHT: x=x+10;break;
        caseKeyEvent.VK_DOWN —y=y+10;break;
        caseKeyEvent.VK_LEFT:x=x-10;break;
    }
}
  public void keyReleased (KeyEvente)
 {
  // Display messages for keyReleased
  System.out.println("keyReleased.");
}
 public void keyType (KeyEvente)
 {
  // Display messages for keyTyped
  System.out.println("keyType.");
 }
}}

java swing

2022-09-29 22:23

1 Answers

I think you can call the setLocation method of the frame (JFrame object) again to update the location.

public void keyPressed (KeyEvente)
{
    System.out.println("keyPressed.");

    // current location
    Point point = frame.getLocation();
    intx = point.x;
    inty = point.y;
    switch(e.getKeyCode()) {
    caseKeyEvent.VK_UP:y=y-10;break;
    caseKeyEvent.VK_RIGHT: x=x+10;break;
    caseKeyEvent.VK_DOWN —y=y+10;break;
    caseKeyEvent.VK_LEFT:x=x-10;break;
    }
    frame.setLocation(x,y);
}

Code difference


2022-09-29 22:23

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.