zoukankan      html  css  js  c++  java
  • 使用鍵盤方向控制按鈕移動

    package result;

    import javax.security.auth.x500.X500Principal;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;

    public class F8 extends JFrame implements KeyListener {
    JButton b[] = new JButton[3];
    // 定義按鈕組件數組
    int x, y;
    public F8() {
    setSize(300, 300);
    setVisible(true);
    setLayout(new FlowLayout());
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    for (int i = 0; i < b.length; i++) {
    b[i] = new JButton("" + i);
    b[i].setBackground(Color.red);
    b[i].setForeground(Color.yellow);
    b[i].addKeyListener(this);
    add(b[i]);
    }
    validate();
    }

    public void keyPressed(KeyEvent e) {
    JButton button = (JButton) e.getSource();
    x = button.getBounds().x;
    y = button.getBounds().y;
    if (e.getKeyCode() == KeyEvent.VK_UP) {
    y = y - 2;
    if (y <= 0) {
    y = 0;
    }
    button.setLocation(x, y);
    } else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
    y = y + 2;
    if(y>=300)
    y=0;
    button.setLocation(x,y);
    }
    else if (e.getKeyCode() == KeyEvent.VK_LEFT) {
    x = x-2;
    if (x <= 0) {
    x = 300;
    }
    button.setLocation(x,y);
    }
    else if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
    x = x+2;
    if (x >=300) {
    x = 0;
    }
    button.setLocation(x,y);
    }
    }
    public void keyTyped(KeyEvent e) {

    }
    public void keyRealsed(KeyEvent e) {

    }
    public static void main(String[] args) {
    new F8();
    }

    @Override
    public void keyReleased(KeyEvent e) {
    // TODO Auto-generated method stub

    }
    }

  • 相关阅读:
    HashMap Hashtable LinkedHashMap 和TreeMap
    RestTemplate -springwebclient
    IntelliJ IDEA 12:
    mac安装RabbitMQ
    mysql 常用,使用经验
    消息中间件性能究竟哪家强?
    log4j2配置文件log4j2.xml
    内存增长 避免
    nginx 服务器重启命令,关闭
    jquery获取css color 值返回RGB
  • 原文地址:https://www.cnblogs.com/nanfengnan/p/13684045.html
Copyright © 2011-2022 走看看