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

    }
    }

  • 相关阅读:
    HDU 5528 Count a * b 欧拉函数
    HDU 5534 Partial Tree 完全背包
    HDU 5536 Chip Factory Trie
    HDU 5510 Bazinga KMP
    HDU 4821 String 字符串哈希
    HDU 4814 Golden Radio Base 模拟
    LA 6538 Dinner Coming Soon DP
    HDU 4781 Assignment For Princess 构造
    LA 7056 Colorful Toy Polya定理
    LA 6540 Fibonacci Tree
  • 原文地址:https://www.cnblogs.com/nanfengnan/p/13684045.html
Copyright © 2011-2022 走看看