• 使用鍵盤方向控制按鈕移動


    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

    }
    }

  • 相关阅读:
    234. Palindrome Linked List
    Remove duplicates
    Unsorted, maximum ==> sorted
    Find one unique integer
    TwoSum
    13. Roman to Integer
    38. Count and Say
    543. Diameter of Binary Tree
    LuoguP1131 [ZJOI2007]时态同步 (树形DP,贪心)
    Luogu3177 [HAOI2015]树上染色 (树形DP)
  • 原文地址:https://www.cnblogs.com/nanfengnan/p/13684045.html
Copyright © 2020-2023  润新知