2012-05-08 31 views
0

我試圖讓使用標籤追逐用戶的鼠標一個程序,我有兩個問題:具有定時更新一個JFrame組件的位置

首先,標籤的位置判斷整個電腦屏幕的座標而不僅僅是窗口。

其次,當定時器使用repaint()時,標籤在應用過程中不移動。

private JPanel contentPane; 

/** 
* Launch the application. 
*/ 
public static void main(String[] args) { 
    EventQueue.invokeLater(new Runnable() { 
     public void run() { 
      try { 
       MouseFollowDisplay frame = new MouseFollowDisplay(); 
       frame.setVisible(true); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 
    }); 
} 

/** 
* Create the frame. 
*/ 
public MouseFollowDisplay() { 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    setBounds(100, 100, 450, 300); 
    contentPane = new JPanel(); 
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); 
    setContentPane(contentPane); 
    contentPane.setLayout(null); 

    final JLabel lblNewLabel = new JLabel("RUN!"); 
    lblNewLabel.setRequestFocusEnabled(false); 
    lblNewLabel.setLocation(new Point(5, 5)); 
    lblNewLabel.setBounds(10, 11, 31, 23); 
    contentPane.add(lblNewLabel); 

    contentPane.addMouseListener(new MouseAdapter() { 

     int DELAY = 500; 

     ActionListener MouseDetect = new ActionListener() { 

      @Override 
      public void actionPerformed(ActionEvent e) { 
       // TODO Auto-generated method stub 

       PointerInfo a = MouseInfo.getPointerInfo(); 
       Point b = a.getLocation(); 
       int x = (int) b.getX(); 
       int y = (int) b.getY(); 
       System.out.println(x + "," + y); 

       int lx = lblNewLabel.getX(); 
       int ly = lblNewLabel.getY(); 

       if (lx <= x+5 && lx >= x-5 && ly <= y+5 && ly >= y-5){ 
        DetectMouse.stop(); 
        JOptionPane.showMessageDialog(null, "You Lose!"); 
       }else{ 
        lx = -((lx - x) * 5)/(Math.abs(lx - x)); 
        ly = -((ly - y) * 5)/(Math.abs(ly - y)); 
        lblNewLabel.repaint(lx, ly, 31, 23); 
       } 

       if (DELAY >= 150) { 
        DELAY -= 5; 
        DetectMouse.setDelay(DELAY); 
       } 
      } 
     }; 

     Timer DetectMouse = new Timer(DELAY, MouseDetect); 

     public void mouseClicked(MouseEvent arg0) { 
      if (DetectMouse.isRunning()){ 
       DetectMouse.stop(); 
       DELAY = 500; 
      } 
      else{ 
       DetectMouse.start();  
      } 
     } 
    }); 
} 

}

回答

2

lblNewLabel.repaint(lx, ly, 31, 23) 

打不動你的標籤。請參閱重繪方法的javadoc

如果顯示組件,則將指定的區域添加到髒區列表中。在所有當前未決事件分派後,組件將被重新繪製。

您需要做的是調整標籤的位置,並重新繪製面板(標籤的舊區域和新區域)。

一個更好的辦法,則null佈局擁有自己的,你重寫paintComponent方法和使用方法Graphics#drawString油漆串JComponentJPanel。在這種情況下,請不要忘記撥打super.paintComponent以避免多次出現文字(例如,請參閱this SO question以瞭解如果您忘記致電super.paintComponent會發生什麼情況)

+0

我該怎麼做?在位置設置的那一刻有沒有辦法讓它重新繪製標籤? – Swanijam

+0

@ user1253476調用'repaint' – Robin

相關問題