简体   繁体   English

MouseMoved事件

[英]MouseMoved event

What im trying to do is I draw the image, and then I use this method to hide and draw the image again where the mouse at. 我想要做的是绘制图像,然后我使用此方法隐藏并再次绘制鼠标所在的图像。

the problem im facing that I still get some little stuff from the old image which it doesn't hide the picture completely, when I try it with different methods like "KeyPressed" everything works well. 我面临的问题是,我仍然从旧图像中得到一些不完全隐藏图片的小东西,当我用不同的方法尝试它时,如“KeyPressed”一切都运行良好。

is this the right method to do the mouse event? 这是做鼠标事件的正确方法吗? or this code is incorrect? 或者此代码不正确?

public class GameFrame extends javax.swing.JFrame implements java.awt.event.ActionListener
{

   private java.util.Vector<Milk> foodList = new java.util.Vector<Milk>();
   private javax.swing.Timer moveTimer = new javax.swing.Timer(500, this);
   private MotherFigure motherFig;
   private BabyFigure babyFig;
   private FastFood burgerFig;
   private int speedTrack = 200;
   private int milkCount = 1;

   @Override
   public void actionPerformed(ActionEvent ae)
   {
      motherFig.draw();
      babyFig.draw();
      moveFood();
      collided();
      motherFig.hide();
   }

   /**
    * Creates new form GameFrame
    */
   public GameFrame()
   {
      initComponents();
      motherFig = new MotherFigure(gamePanel);
      babyFig = new BabyFigure(gamePanel);
      burgerFig = new FastFood(gamePanel);
      moveTimer.start();
      gamePanel.requestFocus();
   }

   /**
    * This method is called from within the constructor to initialize the
    * form. WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    */
   @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        gamePanel = new javax.swing.JPanel();
        txtCount = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setBackground(new java.awt.Color(255, 255, 255));
        setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
        getContentPane().setLayout(null);

        gamePanel.setBackground(new java.awt.Color(255, 255, 255));
        gamePanel.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseMoved(java.awt.event.MouseEvent evt) {
                gamePanelMouseMoved(evt);
            }
        });
        gamePanel.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                gamePanelFocusGained(evt);
            }
        });
        gamePanel.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                gamePanelKeyPressed(evt);
            }
        });

        txtCount.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        txtCount.setBorder(null);
        txtCount.setCursor(new java.awt.Cursor(java.awt.Cursor.TEXT_CURSOR));
        txtCount.setSelectionColor(new java.awt.Color(255, 255, 255));

        javax.swing.GroupLayout gamePanelLayout = new javax.swing.GroupLayout(gamePanel);
        gamePanel.setLayout(gamePanelLayout);
        gamePanelLayout.setHorizontalGroup(
            gamePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, gamePanelLayout.createSequentialGroup()
                .addContainerGap(596, Short.MAX_VALUE)
                .addComponent(txtCount, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        gamePanelLayout.setVerticalGroup(
            gamePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(gamePanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(txtCount, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(545, Short.MAX_VALUE))
        );

        getContentPane().add(gamePanel);
        gamePanel.setBounds(80, 10, 700, 580);

        pack();
    }// </editor-fold>                        

   private void gamePanelKeyPressed(java.awt.event.KeyEvent evt)                                     
   {                                         
      if (evt.getKeyCode() == java.awt.event.KeyEvent.VK_LEFT)
         motherFig.move(-10, 0); //babyFig.move(-10, 0);
      else if (evt.getKeyCode() == java.awt.event.KeyEvent.VK_RIGHT)
         motherFig.move(10, 0); //babyFig.move(10, 0);
      motherFig.draw();

   }                                    

   private void gamePanelFocusGained(java.awt.event.FocusEvent evt)                                      
   {                                          
      // TODO add your handling code here:
      txtCount.setText("Milk Catched: ");
      Milk b = new Milk(gamePanel);
      b.draw();
      foodList.add(b);
   }                                     

    private void gamePanelMouseMoved(java.awt.event.MouseEvent evt) {                                     
       motherFig.hide();
       int X = evt.getX();
       int Y = evt.getY();
       motherFig.move(X, Y);
       motherFig.reDraw(X, Y);

    }                                    

   /**
    * @param args the command line arguments
    */
   public static void main(String args[])
   {
      /*
       * Set the Nimbus look and feel
       */
      //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
       * If Nimbus (introduced in Java SE 6) is not available, stay with the
       * default look and feel. For details see
       * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
       */
      try
      {
         for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels())
         {
            if ("Nimbus".equals(info.getName()))
            {
               javax.swing.UIManager.setLookAndFeel(info.getClassName());
               break;
            }
         }
      }
      catch (ClassNotFoundException ex)
      {
         java.util.logging.Logger.getLogger(GameFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
      }
      catch (InstantiationException ex)
      {
         java.util.logging.Logger.getLogger(GameFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
      }
      catch (IllegalAccessException ex)
      {
         java.util.logging.Logger.getLogger(GameFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
      }
      catch (javax.swing.UnsupportedLookAndFeelException ex)
      {
         java.util.logging.Logger.getLogger(GameFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
      }
      //</editor-fold>

      /*
       * Create and display the form
       */
      java.awt.EventQueue.invokeLater(new Runnable()
      {

         @Override
         public void run()
         {
            new GameFrame().setVisible(true);
         }
      });
   }
    // Variables declaration - do not modify                     
    private javax.swing.JPanel gamePanel;
    private javax.swing.JTextField txtCount;
    // End of variables declaration                   

   private void moveFood()
   {
      for (int i = 0; i < foodList.size(); i++)
      {
         foodList.get(i).hide();
      }

      for (int i = 0; i < foodList.size(); i++)
      {
         foodList.get(i).move();
      }
      for (int i = 0; i < foodList.size(); i++)
      {
         foodList.get(i).draw();
      }
   }
  • You're doing your Swing drawing incorrectly. 你错误地进行了Swing绘图。 You should not call getGraphics() on a component and then draw on it since the Graphics object thus obtained won't persist, and neither will your drawing.. 你不应该在一个组件上调用getGraphics()然后在它上面绘制,因为这样获得的Graphics对象不会持久化,你的绘图也不会...
  • Instead draw in a JComponent's paintComponent(Graphics g) method override. 而是在JComponent的paintComponent(Graphics g)方法中覆盖。
  • You will want to call the super.paintComponent(g); 你会想要调用super.paintComponent(g); inside the override mentioned above, usually on the first line of your method override. 在上面提到的覆盖内部,通常在方法覆盖的第一行。 This will erase any old images for you. 这将删除任何旧图像。
  • The basic Performing Custom Painting with Swing Tutorial will help you with the details 使用Swing Tutorial进行基本的表演自定义绘画将帮助您了解详细信息
  • And the Painting in AWT and Swing article will tell you more of the advanced information that you'll want to know. AWT和Swing中绘画文章将告诉您更多您想要了解的高级信息。

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

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