0

我有一个需要创建的学校作业。下面是信息: 创建一个带有十个按钮的框架,标记为 0 到 9。要退出程序,用户必须依次单击正确的三个按钮,例如 7-3-5。如果使用了错误的组合,框架会变成红色。

我已经完成了框架和在线研究帮助的按钮,但我无法使功能正常工作。请看一下我的代码,并在此先感谢。

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

public class ComboNumber extends JFrame implements ActionListener{

//variable declaration
int ans1 = 3;
int ans2 = 7;
int ans3 = 1;
int one, two, three;
String inData1, inData2, inData3;
JButton[] button;

//constructs the combolock object
public ComboNumber()
{
    //sets flowlayout
    getContentPane().setLayout(new FlowLayout());
    Container c = getContentPane();
    //creates buttons
    button = new JButton[10];
    for(int i = 0; i < button.length; ++i) {
        button[i] = new JButton("" + i);
        //adds buttons to the frame
        c.add(button[i]);
        //registers listeners with buttons
        button[i].addActionListener(this);
    }

    //sets commands for the buttons (useless)

    //sets title for frame
    setTitle("ComboLock");
}
//end combolock object

//listener object
public void actionPerformed(ActionEvent evt)
{
   Object o = evt.getSource();
   for(int i = 0; i < button.length; ++i) {
       if(button[i] == o) {
           // it is button[i] that was cliked
           // act accordingly
           return;
       }
   }
}
//end listener object

//main method
public static void main (String[] args)
{
    //calls object to format window
ComboNumber frm = new ComboNumber();

    //WindowQuitter class to listen for window closing
    WindowQuitter wQuit = new WindowQuitter();
    frm.addWindowListener(wQuit);

    //sets window size and visibility
    frm.setSize(500, 500);
    frm.setVisible(true);
}
//end main method
}
//end main class

//window quitter class
class WindowQuitter extends WindowAdapter
{
//method to close the window
public void windowClosing(WindowEvent e)
{
    //exits the program when the window is closed
    System.exit(0);
}
//end method
}
//end class
4

1 回答 1

1

基本思想很简单。

你需要两件事。

  1. 组合实际上是什么
  2. 用户猜到了什么

所以。您需要添加两个变量。一个包含组合/秘密,另一个包含猜测。

private String secret = "123";
private String guess = "";

这使您可以根据需要进行组合;)

然后在您的actionPerformed方法中,您需要将最近的按钮点击添加到猜测中,将其与秘密进行检查,看看他们是否做出了正确的猜测。如果猜测的长度超过秘密中的字符数,则需要重置猜测。

public void actionPerformed(ActionEvent evt) {
    Object o = evt.getSource();
    if (o instanceof JButton) {
        JButton btn = (JButton) o;
        guess += btn.getText();
        if (guess.equals(secret)) {
            JOptionPane.showMessageDialog(this, "Welcome Overloard Master");
            dispose();
        } else if (guess.length() >= 3) {
            JOptionPane.showMessageDialog(this, "WRONG", "Wrong", JOptionPane.ERROR_MESSAGE);
            guess = "";
        }
    }
}
于 2013-03-18T05:01:33.077 回答