我正在编写一种找到我的应用程序,用户必须点击图像的某个区域才能赢得游戏。当用户点击正确的位置时,我希望图像更新并在该区域周围显示一个黄色圆圈。
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;
}
newPark是原始图片的编辑版本,在获胜区域周围有一个黄色圆圈。这是重新声明和更新图像的正确方法吗?因为它不适合我。
答案 0 :(得分:2)
不要创建image
标签的新实例,只需设置image
标签的icon
属性...
image.setIcon(newPark);
您可能还想阅读Initial Threads以及在事件调度线程的上下文中创建UI的重要性