Та же идея, что и у mKorbel, но с цветом:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PasswordChecker extends JPanel {
private static final Color[] PB_COLORS = {Color.red, Color.yellow, Color.green};
private static final int MAX_LENGTH = 15;
private JPasswordField pwField1 = new JPasswordField(10);
private JPasswordField pwField2 = new JPasswordField(10);
private JProgressBar progBar = new JProgressBar();
private int ins = 10;
public PasswordChecker() {
pwField1.addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent e) {
pwField1FocusLost(e);
}
});
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints(0, 0, 1, 1, 1.0, 10,
GridBagConstraints.WEST, GridBagConstraints.BOTH,
new Insets(ins, ins, ins, ins), 0, 0);
add(new JLabel("Password"), gbc);
gbc = new GridBagConstraints(1, 0, 1, 1, 1.0, 10,
GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL,
new Insets(ins, ins, ins, ins), 0, 0);
add(pwField1, gbc);
gbc = new GridBagConstraints(0, 1, 1, 1, 1.0, 10,
GridBagConstraints.WEST, GridBagConstraints.BOTH,
new Insets(ins, ins, ins, ins), 0, 0);
add(new JLabel("Confirm Password"), gbc);
gbc = new GridBagConstraints(1, 1, 1, 1, 1.0, 10,
GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL,
new Insets(ins, ins, ins, ins), 0, 0);
add(pwField2, gbc);
gbc = new GridBagConstraints(0, 2, 1, 1, 1.0, 10,
GridBagConstraints.WEST, GridBagConstraints.BOTH,
new Insets(ins, ins, ins, ins), 0, 0);
add(new JLabel("Strength"), gbc);
gbc = new GridBagConstraints(1, 2, 1, 1, 1.0, 10,
GridBagConstraints.EAST, GridBagConstraints.BOTH,
new Insets(ins, ins, ins, ins), 0, 0);
add(progBar, gbc);
}
private void pwField1FocusLost(FocusEvent e) {
// simple check, just checks length
char[] pw = pwField1.getPassword();
int value = (pw.length * 100) / MAX_LENGTH;
value = (value > 100) ? 100 : value;
progBar.setValue(value);
int colorIndex = (PB_COLORS.length * value) / 100;
progBar.setForeground(PB_COLORS[colorIndex]);
}
private static void createAndShowUI() {
JFrame frame = new JFrame("Password Checker");
frame.getContentPane().add(new PasswordChecker());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}