繁体   English   中英

我完全不知道如何在Java程序中使用keylistener

[英]I'm completely lost on how to use keylistener in my java program

我有大量的代码,我不知道如何将密钥监听器实现到其中。 基本上,我希望按键侦听器检测“ w”之类的按键并更改一些字段(宽度和长度),程序将在其中与之交互。 我有大量的进口声明,所以没有包括在内。 我最初的想法是让setSizeWidth和setSizeLength调用keylistener方法,这两个方法由frame.setSize中的ok()方法调用。 这应该使按键“ w”缩小窗口大小。 我真的很抱歉很长的代码,但我很沮丧。 忽略其他方法,因为我尚未完成此游戏及其级别!

@SuppressWarnings("serial")
public class Game extends JFrame implements KeyListener{
public static Game game;
public static JFrame frame = new JFrame("Bouncy Ball");




public static int x = 0;
public static int y = 0;

public static int xa = 1;
public static int ya = 1;

public static int x1 = 700;
public static int y1 = 500;

public static int x1a = 1;
public static int y1a = 1;

public static int f = 1;
public static boolean gg = true;
public static boolean t = false;

public static int width = 1000;
public static int length = 1000;





private void moveBall() {
    if(f==1){
    if (x + xa < 0)
         xa = 1;
    if (x + xa > getWidth() - 30)
         xa = -1;
    if (y + ya < 0)
         ya = 1;
    if (y + ya > getHeight() - 30)
         ya = -1;

    x = x + xa;
    y = y + ya;
   }
   else if(f==2){
    if (x + xa < 0)
         xa = 1;
    if (x + xa > getWidth() - 30)
         xa = -1;
    if (x + xa > 670&&y+ya<770)
        xa = -1;
    if (x + xa < 680&&y+ya>770)
        xa=1;
    if (y + ya < 0)
         ya = 1;
    if (y + ya > getHeight() - 30)
         ya = -1;

    x = x + xa;
    y = y + ya;
    }
    if(f==3){
    if (x + xa < 0)
         xa = 1;
    if (x + xa > getWidth() - 30)
         xa = -1;
    if (y + ya < 0)
         ya = 1;
    if (y + ya > getHeight() - 30)
         ya = -1;

    if(gg==true){
    if (x1 + x1a < 0)
         x1a = 1;
    if (x1 + x1a > getWidth() - 30)
         x1a = -1;
    if (y1+ y1a < 0)
         y1a = 1;
    if (y1 + y1a > getHeight() - 30)
         y1a = -1;
    x1+=x1a;
    y1+=y1a;
    }
    x = x + xa;
    y = y + ya;

   }
}

public static int setSizeWidth(){

????

 return width;
}

public static int setSizeLength(){

?????

  return length;
}

public void drawLevelOne(Graphics2D g2d) {
    g2d.fillOval((int)x, (int)y, 30, 30);
    if(t)g2d.setColor(Color.GREEN);
    else g2d.setColor(Color.RED);
    g2d.fillRect(300,500,30,30);
}

public void drawLevelTwo(Graphics2D g2d) {
    g2d.fillOval((int)x, (int)y, 30, 30);
    if(t)g2d.setColor(Color.GREEN);
    else g2d.setColor(Color.BLUE);
    g2d.fillRect(750,300,30,30);
    g2d.fillRect(700,0,15,800);
}

public void drawLevelThree(Graphics2D g2d) {
    g2d.fillOval((int)x, (int)y, 30, 30);
    if(t)g2d.setColor(Color.GREEN);
    else g2d.setColor(Color.RED);
    g2d.fillRect(x1,y1,30,30);
    g2d.fillRect(600,750,30,30);
}

@Override
public void paint(Graphics g) {
    super.paint(g);
    Graphics2D g2d = (Graphics2D) g;
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
             RenderingHints.VALUE_ANTIALIAS_ON);
    if(f==1) drawLevelOne(g2d);
    else if(f ==2) drawLevelTwo(g2d);
    else if(f==3) drawLevelThree(g2d);
}

 public  void checkCollision() throws InterruptedException {
    boolean a = false;
    if(270 < x && x < 330 && 470 < y && y < 530&&f==1) a = true;
    else if(720 < x && x < 780 && 270 < y && y < 330&&f==2) a = true;
    else if(f==3&&x>x1-30&&x<x1+30&&y>y1-30&&y<y1+30) gg = false;
    else if(gg==false&& 570 < x && x < 630 && 720 < y && y < 780) a = true;


    if(a) {
      t=true;
      game.repaint();
      Thread.sleep(1300);
      frame.setVisible(false);
      System.out.println("You win! Play again?");
      Scanner ggg = new Scanner (System.in);
      String l = ggg.nextLine();

      if(l.equals("yes")){
          x=0;
          y=0;
          x1 = 300;
          y1 = 500;
          gg=true;
          t = false;
          ok();
          frame.dispose();
          System.exit(0);
      }
      else  {
        frame.dispose();
        System.exit(0);
      }
      System.exit(0);
      }
}

public  void endGame() throws InterruptedException {
    frame.setVisible(false);
    System.out.println("You went out of bounds! Retry?");
    Scanner ggg = new Scanner (System.in);
    String l = ggg.nextLine();
    if(l.equals("yes")){
        x=0;
        y=0;
        x1 = 300;
        y1 = 500;
        gg=true;
        t=false;
        ok();
        frame.dispose();
        System.exit(0);
    }
    else  {
        frame.dispose();
        System.exit(0);
    }
}

public  void checkOutOfBounds() throws InterruptedException {
    if(f == 1 && (frame.getWidth() < 315 || frame.getHeight() < 540)) endGame();
    else if(f == 2 && (frame.getWidth() < 765 || frame.getHeight() < 340)) endGame();
    else if(f==3 && (frame.getWidth() < 615 || frame.getHeight() < 790)) endGame();

}

public void ok() throws InterruptedException {

    game = new Game();
    frame.add(game);
    frame.setSize(1000, 1000);

    addFocusable(true);
    frame.addKeyListner(this);
    Scanner scan = new Scanner (System.in);
    System.out.println("Level one, two, or three?(must be an int)");
    f = scan.nextInt();

    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    while (true) {

        game.moveBall();

        frame.setSize(setSizeWidth(),setSizeLength());
        game.repaint();
        Thread.sleep(5);


        checkCollision();

        checkOutOfBounds();
    }
}


     @Override
     public void keyPressed(KeyEvent e) {


     switch (e.getKeyCode()) {
        case 119:
            length -= 5;
            break;
        case 115:
            width += 5;
            break;
        case 97:
            length -= 5;
            break;
        case 100:
            length += 5;
            break;
        }


}
@Override
public void keyReleased(KeyEvent e){
}
@Override
public void keyTyped(KeyEvent e){
}

}

考虑在KeyListener使用Key Bindings API,有关更多详细信息,请参见如何使用Key Bindings

基本思想是,当键事件发生时,您想调用另一个方法。 这样,您可以在需要时调用该方法

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

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

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private JLabel label;

        public TestPane() {
            setLayout(new GridBagLayout());
            label = new JLabel("...");

            InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
            ActionMap am = getActionMap();

            im.put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0), "shrink");
            am.put("shrink", new DecreaseAction());

            add(label);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        @Override
        public void invalidate() {
            super.invalidate();
            Dimension size = getSize();
            label.setText(size.getWidth() + "x" + getHeight());
        }

        protected void resizeBy(int widthDelta, int heightDelta) {
            Window win = SwingUtilities.getWindowAncestor(this);
            Dimension size = win.getSize();
            size.width += widthDelta;
            size.height += heightDelta;
            win.setSize(size);
        }

        public class DecreaseAction extends AbstractAction {

            @Override
            public void actionPerformed(ActionEvent e) {
                resizeBy(-1, 0);
            }

        }

    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM