【问题标题】:Issues with movement in JFrameJFrame 中的移动问题
【发布时间】:2017-09-06 19:09:28
【问题描述】:

我正在尝试在JFrame 中向左或向右移动一个矩形,但是当我使用箭头按钮时,该栏没有移动;它只是在扩展。矩形是用于 Brick Breaker 类型的游戏。

public class main 
{

  public static void main(String[] args)
  {

    JFrame obj = new JFrame("Brick Breacker");
    obj.setBounds(50,50,1200,900);
    obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    obj.setVisible(true);       
    Grafica grafica = new Grafica();
    obj.add(grafica);
  }
}

public class Grafica extends JPanel implements ActionListener , KeyListener
{
    Timer tm = new Timer(0,this); 
    boolean  play = false;
    int playerX = 550; 
    int playerXs = 0;

  public Grafica()
  {
    tm.start();
    addKeyListener(this);
    setFocusable(true); 
    setFocusTraversalKeysEnabled(false);    
  }

  public void paint (Graphics g)
  {                
    //paddle 
     g.setColor(Color.GREEN);
     g.fillRect(playerX, 800, 145, 10);   

     //borders
     g.setColor(Color.BLACK);
     g.fillRect(0, 0, 5, 900);
     g.fillRect(1180, 0, 5, 900);
     g.fillRect(1200, 0, -1200, 5);
     g.setColor(Color.RED);
     g.fillRect(1200, 860, -1200, 5);

     //ball
     g.setColor(Color.blue);         
     g.fillOval(550,700, 26, 26);
  }

  public void actionPerformed(ActionEvent e)
  {     
     playerX = playerX + playerXs;
     repaint();
  }

  public void keyTyped(KeyEvent e) 
  {                 
  }

  public void keyReleased(KeyEvent e) 
  {
    playerXs = 0;       
  }

  public void keyPressed(KeyEvent e)
  {
    int c = e.getKeyCode();
    if( c == KeyEvent.VK_RIGHT )
    {
        if(playerX > 850)
        {
            playerX = 850;
        } else 
        {
            moveRight();
        }

    }

    if(c == KeyEvent.VK_LEFT)
    {
        if(playerX > 850)
        {
            playerX = 850;
        } else 
        {
            moveLeft();
        }
     }
  }

  public void moveRight()
  {
     play = true;
     playerX+=20;

  }

  public void moveLeft()
  {
     play = true;
     playerX-=20;

  }
}

【问题讨论】:

标签: java eclipse swing jframe


【解决方案1】:

这不起作用的原因是您的 paint() 实现没有清除背景,即您多次绘制绿色条 - 保留已绘制的区域。因此,它看起来像条在拉长而不是移动。

您不应该重写 paint(Graphics) 方法,而应该重写 paintComponent(Graphics) 方法,并且您应该调用 super.paintComponent(Graphics)

public void paintComponent(Graphics g)
{
    super.paintComponent(g);
    // Now do your own painting here...
}

对超类实现的调用将为您提供 Graphics 上下文的初始化,包括用您的 JPanel 的背景颜色清除它。

您可以阅读更多关于如何操作custom painting in Swing components here 的信息。

另外,作为旁注,右侧的范围限制有效,但左侧的范围限制无效 - 它应该检查 playerX < 0

最后,实现游戏循环的方式——通过响应关键输入和重新绘制——并不是最佳的。谷歌“java游戏循环”以获得如何以更好的方式做到这一点的想法(非常简单:你的游戏循环应该独立于输入并且应该定期更新场景。输入事件应该改变游戏状态,应该会在下次场景更新中体现出来)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-17
    相关资源
    最近更新 更多