[英]Combination Lock (Java)
我有一个需要创建的学校作业。 下面是信息:创建一个带有10个按钮的框架,标记为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
基本思想很简单。
您需要两件事。
所以。 您需要添加两个变量。 一个包含组合/秘密,另一个包含猜测。
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 = "";
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.