如何限制Java中JPasswordField的位数?

我有我的Java代码在Eclipse中工作,但我需要添加一些function。

首先,如何限制用户可以输入的位数? 实际上我有一个JPasswordField让一个人输入一个pin代码,我希望这个JPasswordField最多限制为4位数。 那么如何在输入4位数字后立即停止输入?

然后,我如何玩JPassword框的大小? 有没有办法像JTextField一样修改它? 因为我的行“p1.setPreferredSize(new Dimension(100,25));” 似乎并没有真正让我修改盒子的大小。

在此处输入图像描述

如您所见,JPassworldField框具有默认大小,我无法弄清楚如何轻松修改。

这是我的代码:

package codePin; import java.io.*; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Main extends JFrame { private static final long serialVersionUID = 1L; private JPanel container = new JPanel(); private JPasswordField p1 = new JPasswordField(4); private JLabel label = new JLabel("Enter Pin: "); private JButton b = new JButton("OK"); public Main() { this.setTitle("NEEDS"); this.setSize(300, 500); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setLocationRelativeTo(null); container.setBackground(Color.white); container.setLayout(new BorderLayout()); JPanel top = new JPanel(); p1.setPreferredSize(new Dimension(100, 25)); //How to really modifiy this ? b.addActionListener(new BoutonListener()); top.add(label); top.add(p1); p1.setEchoChar('*'); top.add(b); this.setContentPane(top); this.setVisible(true); } class BoutonListener implements ActionListener { private final AtomicInteger nbTry = new AtomicInteger(0); @SuppressWarnings("deprecation") public void actionPerformed(ActionEvent e) { if (nbTry.get() > 2) { JOptionPane.showMessageDialog(null, "Pin blocked due to 3 wrong tries"); return; } if (p1.getText().replaceAll("\u00A0", "").length() != 4) { // System.out.println("Pin must be 4 digits"); JOptionPane.showMessageDialog(null, "Ping must be 4 digits"); return; } System.out.println("Checking..."); SwingWorker worker = new SwingWorker() { @Override protected Void doInBackground() throws Exception { boolean authenticated = false; ArrayList pins = new ArrayList(); readPinsData(new File("bdd.txt"), pins); String[] thePins = new String[pins.size()]; for (int i = 0; i < thePins.length; i++) { thePins[i] = pins.get(i).toString(); } String passEntered = String.valueOf(p1); for (String thePin : thePins) { if (passEntered.equals(thePin) && p1.getText().length() == 4) { System.out.println(":)"); authenticated = true; break; } } if (!authenticated) { System.out.println(":("); nbTry.incrementAndGet(); } return null; } }; worker.execute(); } } // Accessing pins Bdd file static public boolean readPinsData(File dataFile, ArrayList data) { boolean err = false; try { Scanner scanner = new Scanner(dataFile); String line; while (scanner.hasNext()) { line = scanner.nextLine(); try { data.add(Integer.parseInt(line)); } catch (NumberFormatException e) { e.printStackTrace(); err = true; } } scanner.close(); } catch (FileNotFoundException e) { e.printStackTrace(); err = true; } return err; } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new Main(); } }); } } 

有任何想法吗 ? 谢谢。

弗洛朗

这是我用nachokk解决方案编辑的代码:

 import java.io.*; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import javax.swing.*; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.DocumentFilter; import javax.swing.text.PlainDocument; import java.awt.*; import java.awt.event.*; public class Main extends JFrame { private static final long serialVersionUID = 1L; private JPanel container = new JPanel(); private JPasswordField p1 = new JPasswordField(4); private JLabel label = new JLabel("Enter Pin: "); private JButton b = new JButton("OK"); public Main() { this.setTitle("NEEDS"); this.setSize(300, 500); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setLocationRelativeTo(null); container.setBackground(Color.white); container.setLayout(new BorderLayout()); JPanel top = new JPanel(); PlainDocument document =(PlainDocument)p1.getDocument(); b.addActionListener(new BoutonListener()); top.add(label); top.add(p1); p1.setEchoChar('*'); top.add(b); this.setContentPane(top); this.setVisible(true); document.setDocumentFilter(new DocumentFilter(){ @Override public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException { String string =fb.getDocument().getText(0, fb.getDocument().getLength())+text; if(string.length()  2) { JOptionPane.showMessageDialog(null, "Pin blocked due to 3 wrong tries"); return; } if (p1.getText().replaceAll("\u00A0", "").length() != 4) { // System.out.println("Pin must be 4 digits"); JOptionPane.showMessageDialog(null, "Ping must be 4 digits"); return; } System.out.println("Checking..."); SwingWorker worker = new SwingWorker() { @Override protected Void doInBackground() throws Exception { boolean authenticated = false; ArrayList pins = new ArrayList(); readPinsData(new File("bdd.txt"), pins); String[] thePins = new String[pins.size()]; for (int i = 0; i < thePins.length; i++) { thePins[i] = pins.get(i).toString(); } String passEntered = String.valueOf(p1); for (String thePin : thePins) { if (passEntered.equals(thePin) && p1.getText().length() == 4) { System.out.println(":)"); authenticated = true; break; } } if (!authenticated) { System.out.println(":("); nbTry.incrementAndGet(); } return null; } }; worker.execute(); } } // Fonction permettant d'accéder/lire notre BDD de pins (fichier .txt) static public boolean readPinsData(File dataFile, ArrayList data) { boolean err = false; try { Scanner scanner = new Scanner(dataFile); String line; while (scanner.hasNext()) { line = scanner.nextLine(); try { data.add(Integer.parseInt(line)); } catch (NumberFormatException e) { e.printStackTrace(); err = true; } } scanner.close(); } catch (FileNotFoundException e) { e.printStackTrace(); err = true; } return err; } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new Main(); } }); } } 

如何使用JPassword框的大小? 有没有办法像JTextField一样修改它? 因为我的行“p1.setPreferredSize(new Dimension(100,25));” 似乎并没有真正让我修改盒子的大小。

不要使用setPrefferedSize()而是使用这个构造函数JPasswordField(int col) 。在这里阅读更多关于我应该避免在Java Swing中使用set(Preferred | Maximum | Minimum)Size方法吗?

如何限制用户可以输入的位数? 实际上我有一个JPasswordField让一个人输入一个pin代码,我希望这个JPasswordField最多限制为4位数。 那么如何在输入4位数字后立即停止输入?

对于限制输入,您可以使用DocumentFilter ,如下例所示。

  public class JPasswordFieldTest { private JPanel panel; public JPasswordFieldTest() { panel = new JPanel(); //set horizontal gap ((FlowLayout) panel.getLayout()).setHgap(2); panel.add(new JLabel("Enter pin :")); JPasswordField passwordField = new JPasswordField(4); PlainDocument document = (PlainDocument) passwordField.getDocument(); document.setDocumentFilter(new DocumentFilter() { @Override public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException { String string = fb.getDocument().getText(0, fb.getDocument().getLength()) + text; if (string.length() <= 4) { super.replace(fb, offset, length, text, attrs); //To change body of generated methods, choose Tools | Templates. } } }); panel.add(passwordField); JButton button = new JButton("OK"); panel.add(button); } public static void main(String[] args) { //Schedule a job for the event-dispatching thread: //creating and showing this application's GUI. SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI("Password Example"); } }); } private static void createAndShowGUI(String str) { JFrame frame = new JFrame(str); frame.setDefaultCloseOperation(EXIT_ON_CLOSE); JPasswordFieldTest test = new JPasswordFieldTest(); frame.add(test.panel); frame.pack(); frame.setVisible(true); } } 

在此处输入图像描述

首先,如何限制用户可以输入的位数?

  • 请参阅此问答: 如何限制JTextField中的字符数? 由于JPasswordField从JTextField扩展,它应该完美地工作。
  • 正如@nachokk正确指出的那样,使用文档filter(就像他在答案中所做的那样)是一个更灵活的选择。 您可以在概念:关于文档和实现文档filter部分的文本组件function官方文章中阅读更多相关信息。

然后,我如何玩JPassword框的大小? 有没有办法像JTextField一样修改它? 因为我的行“p1.setPreferredSize(new Dimension(100,25));” 似乎并没有真正让我修改盒子的大小。

  • 使用Swing时,请勿设置固定大小。 请参阅此主题: 我应该避免在Java Swing中使用set(Preferred | Maximum | Minimum)Size方法吗? 。
  • 您可以使用setColumns(int columns)来指示文本字段的首选大小。
  • 请参见如何使用密码字段教程。

通用代码和简易方法来解决这个问题

四位使用netbeans限制JPasswordField(Java)中的数字。

 //JPasswordField Variable name is "Password_Field_Demo" //Jlabel variable name is "lbl_register" public class Register extends javax.swing.JFrame { static int count=1; //static variable(count) initialize on first time.. //Default Constructor public Register() { initComponents(); } //KeyTyped(KeyEvent evt) Method in Password_Field_Demo private void Password_Field_DemoKeyTyped(java.awt.event.KeyEvent evt) { char c = evt.getKeyChar(); //get the Character if(Character.isDigit(c)) //isDigit() method on Character and Enter only Digit or number { if(count>4) { evt.consume();//Greater than Four Digit to consume()method ..Not Input more than Four Digit lbl_register.setText(" Maximum Four Digit Allowed.."); } else{ count++; lbl_register.setText(""); } } if((c == KeyEvent.VK_BACK_SPACE) ||(c == KeyEvent.VK_DELETE)) { if(count>1) count--; lbl_register.setText(""); } //lbl_register.setText(" count :"+count); } //End Password_Field_DemoKeyTyped()