日期:2014-05-20 浏览次数:20684 次
import java.awt.*; import javax.swing.*; import java.awt.event.*; public class ball extends JPanel implements KeyListener{ private int x = 20;//小球的大小 private int y = 20;//小球的大小 private int a = 50;//小球的位置 private int b = 50;//小球的位置 private int x1 = 200;//窗体的大小 private int y1 = 200;//窗体的大小 ball(){ JFrame jf = new JFrame(); jf.setLocation(200,200); jf.setSize(x1,y1); JPanel p1 = new p();//覆盖组建的paint方法才能用 jf.getContentPane().add(p1); jf.setVisible(true); jf.addKeyListener(this); try{ while(true){ Thread.sleep(50); p1.repaint(); } }catch(InterruptedException e){ e.printStackTrace(); } } public void keyTyped(KeyEvent e){ } public void keyPressed(KeyEvent e){ //System.out.println(e.getKeyCode()); //System.out.println(e.VK_KP_DOWN); if(e.getKeyCode() == 40){//下 y += 4; } if(e.getKeyCode() == 39){//右 if(x>=x1-(x-b/2)){//请问怎么计算小球撞到窗体边缘.我感觉老是不行帮我鲁下思路吧高人 }else{ x += 4; } } if(e.getKeyCode() == 37){//左 x -= 4; } if(e.getKeyCode() == 38){//上 y -= 4; } } public void keyReleased(KeyEvent e){ //System.out.println("+++++++++++++++"); } public static void main(String[] args){ ball b = new ball(); //b.paint(); } private class p extends JPanel{ public void paint(Graphics g){ super.paint(g); g.setColor(Color.blue); //System.out.println(a +"a"+ b+"b" + x +"x"+ y+"y"); g.fillOval(x,y,a,b); g.drawOval(x,y,a,b); } } }