2015-05-21 23 views
0

我有大量的代码,我不知道如何实现关键侦听器。基本上,我想让关键听众检测像“w”这样的按键,并更改一些字段(宽度和长度),程序将在其中进行交互。我有一大堆进口报表,所以我没有包含它们。我最初的想法是让setSizeWidth和setSizeLength调用keylistener方法,这两个方法由frame.setSize中的ok()方法调用。这应该使按键“w”缩小窗口大小。我真的很抱歉很长的代码,但我很难过。忽略其他方法,因为我还没有完成这个游戏和它的水平呢!我完全失去了如何在我的java程序中使用keylistener

@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){ 
} 

}

+1

使用键绑定而不是'KeyListener'。请参阅[如何使用键绑定](http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html)以获取更多详细信息 – MadProgrammer

+0

*“我最初的想法是让setSizeWidth和setSizeLength调用keylistener方法“*为什么?它通常会以另一种方式完成... – MadProgrammer

回答

1

考虑使用的键绑定API在KeyListener,看到How to Use 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); 
      } 

     } 

    } 

} 
+0

你好,谢谢你的输入,我一定会检查出来。然而,编译器给我一个错误 - 窗口赢= SwingUtilities.getWindowAncestor(comp); - 说它找不到comp变量。 –

+1

对不起,在我写答案的时候修改了代码,应该是'Window win = SwingUtilities.getWindowAncestor(this);',现在更正了 – MadProgrammer

+0

我'我试图实现这一点,并彻底失败,有关如何将其实现到代码中的任何建议? –

相关问题