密码锁(Java)

时间:2013-03-18 03:48:25

标签: java swing

我有一份我需要创建的学校作业。以下是信息: 创建一个带有十个按钮的框架,标记为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

1 个答案:

答案 0 :(得分:1)

基本思路很简单。

你需要两件事。

  1. 实际上是什么组合
  2. 用户猜到了什么
  3. 因此。您需要添加两个变量。一个包含组合/秘密,另一个包含猜测。

    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 = "";
            }
        }
    }