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

    }
    }

  • 相关阅读:
    回溯-uva129
    【linux】【安全】服务器安全建议
    【linux】 服务器文件说明
    【linux】程序端口启动权限
    【android】安卓开发apk列表
    【网络基础】【TCP/IP】私有IP地址段
    【网络基础】【TCP/IP】IP的分级
    代数数论初步(全书)
    李代数笔记
    自由群,外代数和泛包络代数
  • 原文地址:https://www.cnblogs.com/nanfengnan/p/13684045.html
Copyright © 2011-2022 走看看