2014-04-23 32 views
0

我正在寫一種查找應用程序,用戶必須單擊圖像的某個區域才能贏得遊戲。當用戶點擊正確的位置時,我希望圖像更新並在該區域周圍顯示一個黃色圓圈。Java GUI更新現有圖像

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 

public class findMe { 
static ImageIcon park = new ImageIcon("park.jpg"); 
static ImageIcon newPark = new ImageIcon("newPark.jpg"); 
static JLabel image = new JLabel(park); 
static JPanel big = new JPanel(); 
static JLabel text = new JLabel("Clicks: 0"); 
static int i = 10; 
static boolean winGame = false; 

public static void main(String[] args) { 
    //Create the frame 
    JFrame frame = new JFrame("Find Me"); 
    frame.setSize(935, 700); //Setting the size of the frame 

    //Declaring the Mouse listener 
    MouseHandler listener = new MouseHandler(); 

    big.add(image); 
    big.add(text); 

    image.addMouseListener(listener); 

    JOptionPane.showMessageDialog (null, "Hint: Sometimes the head of beauty isn't as  bright as you'd think."); 

    frame.getContentPane().add(big); //panel to frame 
    frame.setVisible(true); // Shows frame on screen 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
} 

private static class MouseHandler implements MouseListener { 

    public void mousePressed(MouseEvent e) { 
     if (e.getX() >= 454 && e.getX() <= 480 && e.getY() >= 600 && e.getY() <= 625) { 
      image = new JLabel(newPark); 
      JOptionPane.showMessageDialog (null, "You've found it!"); 
      winGame = true; 
     } else if (winGame == false) { 
      i--; 
      text.setText("Clicks left: " + i); 
      if (i == 0) { 
       System.exit(0); 
      } 
     } 
    } 

    public void mouseReleased(MouseEvent e) { 
    } 

    public void mouseEntered(MouseEvent e) { 
    } 

    public void mouseExited(MouseEvent e) { 
    } 

    public void mouseClicked(MouseEvent e) { 

    } 
}  

} 

的代碼更新圖像的區域是:

if (e.getX() >= 454 && e.getX() <= 480 && e.getY() >= 600 && e.getY() <= 625) { 
    image = new JLabel(newPark); 
    JOptionPane.showMessageDialog (null, "You've found it!"); 
    winGame = true; 
} 

紐帕克是原始圖像的編輯版本,與周圍的勝利面積的黃色圓圈。這是重新聲明和更新圖像的正確方法嗎?因爲這不適合我。

回答

2

不要創建image標籤,簡單的一套image標籤的icon屬性的新實例...

image.setIcon(newPark); 

您可能還需要在Initial Threads閱讀,並可在創建UI的重要性Event Dispatching Thread的背景

+0

謝謝!當我需要幫助時,MadProgrammer似乎總是在那裏;)感謝您的快速回答。不知道關於setIcon功能haha – patrickstarpants

+0

也許你應該閱讀[如何使用標籤](http://docs.oracle.com/javase/tutorial/uiswing/components/label.html);) – MadProgrammer