请注意我是编程的新手,因此我的代码可能非常冗余且难以阅读,但我真的需要帮助!
我试图创建一个匹配的游戏,这样当用户选择两个相互关联的按钮时,你就会得到一个匹配!我正在尝试让动作监听器正常工作,但每当我运行代码时,每个if语句都会实现,所有按钮都变为绿色。
public class Panel extends JPanel
{
int[] num = new int[2];
private JButton movie1;
private JButton movie2;
private JButton movie3;
private JLabel question;
private JButton name1;
private JButton name2;
private JButton name3;
public Panel()
{
ImageIcon movie1pic = new ImageIcon("movie1.jpg");
movie1 = new JButton (movie1pic);
movie1.addActionListener(new ButtonHandler());
ImageIcon movie2pic = new ImageIcon("movie2.png");
movie2 = new JButton (movie2pic);
movie2.addActionListener(new ButtonHandler());
ImageIcon movie3pic = new ImageIcon("movie3.png");
movie3 = new JButton (movie3pic);
movie3.addActionListener(new ButtonHandler());
question = new JLabel ("match");
ImageIcon name1pic = new ImageIcon("name1.png");
name1 = new JButton (name1pic);
name1.addActionListener(new ButtonHandler());
ImageIcon name2pic = new ImageIcon("name2.jpg");
name2 = new JButton (name2pic);
ImageIcon name3pic = new ImageIcon("name3.jpg");
name3 = new JButton (name3pic);
setLayout(new BorderLayout());
JPanel southPanel = new JPanel(new FlowLayout());
JPanel northPanel = new JPanel(new
FlowLayout());
southPanel.add(name1);
southPanel.add(name2);
southPanel.add(name3);
northPanel.add(movie1);
northPanel.add(movie2);
northPanel.add(movie3);
add(question, BorderLayout.CENTER);
add(northPanel, BorderLayout.NORTH);
add(southPanel, BorderLayout.SOUTH);
private class ButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if ( e.getSource() == "movie1.jpg" );
{
num[0] = 1;
ImageIcon green = new ImageIcon("green.png");
movie1.setIcon(green);
}
if (e.getSource() == "movie2.png");
{
num[0] = 2;
ImageIcon green = new ImageIcon("green.png");
movie2.setIcon(green);
}
else if (e.getSource() =="movie3.png" );
{
num[0] = 3;
ImageIcon green = new ImageIcon("green.png");
movie3.setIcon(green);
}
}
}
}