真的感谢上一个问题的帮助,但是仍然有一些错误。我正在制作一个寻宝游戏,用户单击gui尝试显示藏宝箱的位置。如果找到了位置,但我使用动作侦听器在按钮上显示宝箱的图像,但那是固定位置,因此我想将其随机化。得到了一些建议,可以在按钮和随机数生成器上使用数组,然后使用if / else进行检查。遇到编译器错误,我将在下面的代码中进行注释。好的编码员可能会在几秒钟内发现我的新手错误!
import java.awt.*;
import javax.swing.*;
import java.util.Random;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Test extends JFrame {
JLabel label1, label2, label3;
ImageIcon image1, image2, image3, image4, image5;
JTextField textResult;
public static void main(String[] args) {
new Test();
}
public Test (){
this.setSize(700,700);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Treasure Hunt Game");
JPanel thePanel = new JPanel();
thePanel.setLayout(new GridLayout(0,3,0,0));
image1 = new ImageIcon(getClass().getResource("Treasure.jpg"));
image2 = new ImageIcon(getClass().getResource("Pirate.jpg"));
image3 = new ImageIcon(getClass().getResource("sand2.jpg"));
image4 = new ImageIcon(getClass().getResource("emptyhole.jpg"));
image5 = new ImageIcon(getClass().getResource("map.jpg"));
label1 = new JLabel("Click the buttons to find the Treasure!");
label2 = new JLabel(image5);
label3 = new JLabel(image2);
JButton [] buttons = new JButton[9];
buttons[0] = new JButton(image3);
buttons[1] = new JButton(image3);
buttons[2] = new JButton(image3);
buttons[3] = new JButton(image3);
buttons[4] = new JButton(image3);
buttons[5] = new JButton(image3);
buttons[6] = new JButton(image3);
buttons[7] = new JButton(image3);
buttons[8] = new JButton(image3);
thePanel.add(buttons[0]);
thePanel.add(buttons[1]);
thePanel.add(buttons[2]);
thePanel.add(buttons[3]);
thePanel.add(buttons[4]);
thePanel.add(buttons[5]);
thePanel.add(buttons[6]);
thePanel.add(buttons[7]);
thePanel.add(buttons[8]);
thePanel.add(label1);
thePanel.add(label2);
thePanel.add(label3);
this.add(thePanel);
this.setVisible(true);
int treasureLocation = new Random().nextInt(buttons.length);
System.out.println(treasureLocation);
在编译器上,它给我一条错误消息,表明它不知道下面的if else语句中的“ buttons”或“ treasureLocation”。
}
public void actionPerformed(ActionEvent evt) {
if (evt.getSource() == buttons[treasureLocation]) {
}
else {
}
}
}
JLabel label1, label2, label3;
ImageIcon image1, image2, image3, image4, image5;
JTextField textResult;
JButton [] buttons; // Move the declaration here
int treasureLocation; // Move the declaration here
并改变
JButton [] buttons = new JButton[9];
到
buttons = new JButton[9];
和
int treasureLocation = new Random().nextInt(buttons.length);
到
treasureLocation = new Random().nextInt(buttons.length);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句