Creare un’interfaccia per l’autenticazione con java è molto semplice, in questo articolo vi spiegherò come realizzare un’applicazione, che presenterà all’utente un modulo sul proprio sito web dove inserire una password per accedere ai contenuti.
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class SecurityKey extends JPanel implements ActionListener { private static String pass = "Convalida"; private JFrame controllingFrame; private JPasswordField campoPass; public SecurityKey(JFrame f) { controllingFrame = f; campoPass = new JPasswordField(8); campoPass.setActionCommand(pass); campoPass.addActionListener(this); JLabel label = new JLabel("Inserisci la password: "); label.setLabelFor(campoPass); JComponent buttonPane = createButtonPanel(); JPanel textPane = new JPanel(new FlowLayout(FlowLayout.TRAILING)); textPane.add(label); textPane.add(campoPass); add(textPane); add(buttonPane); } protected JComponent createButtonPanel() { JPanel p = new JPanel(new GridLayout(0,1)); JButton keyButton = new JButton("Ivia"); keyButton.setActionCommand(pass); keyButton.addActionListener(this); p.add(keyButton); return p; } public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); if (pass.equals(cmd)) { char[] input = campoPass.getPassword(); if (controlloPass(input)) { JOptionPane.showMessageDialog(controllingFrame, "Password corretta."); } else { JOptionPane.showMessageDialog(controllingFrame, "Password non valida.", "Errore", JOptionPane.ERROR_MESSAGE); } for (int j = 0; j < input.length; j++) { input[j] = 0; } campoPass.selectAll(); resetFocus(); } } private static boolean controlloPass(char[] input) { boolean Ctrl = true; char[] Password = { 'j', 'a', 'v', 'a' }; if (input.length != Password.length) { Ctrl = false; } else { for (int j = 0; j < input.length; j++) { if (input[j] != Password[j]) { Ctrl = false; } } } for (int j = 0; j < Password.length; j++) { Password[j] = 0; } return Ctrl; } protected void resetFocus() { campoPass.requestFocusInWindow(); } private static void interfaccia() { JFrame frame = new JFrame("SecurityKey"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); final SecurityKey newContentPane = new SecurityKey(frame); newContentPane.setOpaque(true); frame.setContentPane(newContentPane); frame.addWindowListener(new WindowAdapter() { public void windowActivated(WindowEvent e) { newContentPane.resetFocus(); } }); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { interfaccia(); } }); } }




















