Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import javax.swing.*;
- import java.awt.*;
- import java.awt.event.*;
- /* Program to show how to detect one letter at a time in a JTextField */
- public class SecretCode2 extends JFrame implements KeyListener {
- Font displayFont = new Font("Arial", Font.PLAIN, 18);
- JTextField display;
- JLabel d2;
- JPanel panel;
- String s = "GFT";
- char[] c = {'*','*','*'};
- char[] d = {'*','*','*'};
- String ds = "~!@#$%^&*()?.,";
- public static void main(String[] args) {
- new SecretCode2();
- }
- SecretCode2() {
- this.setSize(200,130);
- this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- this.setLocationRelativeTo(null);
- this.setTitle("Enter Secret Code");
- this.setResizable(false);
- panel = new JPanel();
- panel.setLayout(new FlowLayout(FlowLayout.CENTER,10,10));
- panel.setBackground(new Color(70,70,90));
- display = new JTextField("***",9);
- display.setHorizontalAlignment(JTextField.CENTER);
- display.setFont(displayFont);
- display.addKeyListener(this);
- panel.add(display);
- d2 = new JLabel(" *** ");
- d2.setPreferredSize(new Dimension(126,26));
- d2.setBackground(Color.WHITE);
- d2.setOpaque(true);
- d2.setHorizontalAlignment(JTextField.CENTER);
- d2.setFont(displayFont);
- panel.add(d2);
- this.add(panel);
- this.setVisible(true);
- }
- @Override
- public void keyTyped( KeyEvent e ) {
- char key = e.getKeyChar();
- // if ((int)key == 8) return;
- if ((key >='A' && key <='Z') || (key >='a' && key <= 'z')) {}
- else {
- e.consume();
- return;
- }
- c[0]=c[1];
- c[1]=c[2];
- c[2]=key;
- d[0]=d[1];
- d[1]=d[2];
- d[2]=ds.charAt((int)(Math.random() * ds.length()));
- String t = new String(c).toUpperCase();
- display.setText(t);
- d2.setText(new String(d));
- //d2.setText(" "+(int)key);
- e.consume(); //after it updates the display, the keypressed also is displayed. Must consume it!!!
- if (t.equals(s)) {
- panel.setBackground(Color.RED);
- display.setText("YOU WIN");
- d2.setText("$$$");
- }
- }
- @Override
- public void keyReleased( KeyEvent e ) {}
- @Override
- public void keyPressed( KeyEvent e ) {}
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement