Wednesday, March 18, 2009

COMBINATION LOCK

/*

Exercise 3
Program Name:Combination Lock
Programmer name: Danver G. Palmiano
Date Started: March 18,2009, 8:15pm
Date Ended: March 18, 2009,9:15pm
Aim: The user must click the correct combination button. If user will click the correct button then it is a right code and then exit, else the background of the JFrame will turn into color Red if wrong combination..
*/

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Combination extends JPanel {

String[] password={"7","3","5"};
int Check=0;
int counter=0;
public Combination() {

JButton btn1 = new JButton("0");
btn1.addActionListener(new ButtonListener());
add(btn1);
JButton btn2 = new JButton("1");
btn2.addActionListener(new ButtonListener());
add(btn2);
JButton btn3 = new JButton("2");
btn3.addActionListener(new ButtonListener());
add(btn3);
JButton btn4 = new JButton("3");
btn4.addActionListener(new ButtonListener());
add(btn4);
JButton btn5 = new JButton("4");
btn5.addActionListener(new ButtonListener());
add(btn5);
JButton btn6 = new JButton("5");
btn1.addActionListener(new ButtonListener());
add(btn6);
JButton btn7 = new JButton("6");
btn7.addActionListener(new ButtonListener());
add(btn7);
JButton btn8 = new JButton("7");
btn8.addActionListener(new ButtonListener());
add(btn8);
JButton btn9 = new JButton("8");
btn9.addActionListener(new ButtonListener());
add(btn9);
JButton btn10 = new JButton("9");
btn10.addActionListener(new ButtonListener());
add(btn10);

}

public static void main(String[] args) {
JFrame frame = new JFrame();
frame.getContentPane().add(new MainClass());

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setVisible(true);
}
}

class ButtonListener implements ActionListener {
ButtonListener() {
}

public void actionPerformed(ActionEvent e)
{
if(counter<3)
{
if (e.getActionCommand().equals(password[counter]))
{
Check=1;
}
else
{
Check=2;
}
counter++;
}
else
{
if (e.getActionCommand().equals(password[counter]))
{
Check=1;
}
else
{
Check=2;
}
counter=0;
if(Check==3)
{
this.setBackground(Color.RED);
}
else
{
System.exit(0);
}
}


}
}

No comments:

Post a Comment