簡體   English   中英

如何在 Java 中獲取 JFormattedTextField 的長度?

[英]How to get length of a JFormattedTextField in Java?

當我嘗試獲取 JFormattedTextField 的大小時遇到​​問題。 實際上,我需要用戶輸入一個簡單的 pinCode,然后獲取他輸入的內容的大小,以便在它之后立即循環。 如果他輸入了 4 位數字就可以了,否則他必須再次輸入。 但是當我運行我的項目時,我有一個無限循環,“Pin 必須是 4 位數字”......

我已經找到了這個鏈接,但它沒有解決我的問題。

這是我的代碼:

package codePin;

import java.io.*;
import java.text.NumberFormat;
import java.util.*;
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 JFormattedTextField jtf = new JFormattedTextField(NumberFormat.getIntegerInstance());
    private JLabel label = new JLabel("Enter Pin: ");
    private JButton b = new JButton("OK");

    public Main() {
        this.setTitle("APP");
        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();
        Font police = new Font("Arial", Font.BOLD, 14);
        jtf.setFont(police);
        jtf.setPreferredSize(new Dimension(150, 30));
        jtf.setForeground(Color.BLUE);

        b.addActionListener(new BoutonListener());

        top.add(label);
        top.add(jtf);
        top.add(b); 

        this.setContentPane(top);
        this.setVisible(true);
    }

    class BoutonListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            int nbTry = 0;
            boolean authenticated = false;

            do {
                do {

                    if (jtf.getText().length() != 4) { 
                        System.out.println("Pin must be 4 digits");
                    } else {
                        System.out.println("Checking...");
                    }

                    ArrayList<Integer> pins = new ArrayList<Integer>(); 
                    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(jtf);

                    for (int i = 0; i < thePins.length; i++) {
                        if (passEntered.equals(thePins[i]) && jtf.getText().length() == 4) {
                            System.out.println(":)");
                            authenticated = true;
                            break;
                        }
                    }
                } while (jtf.getText().length() != 4);
                if (!authenticated && jtf.getText().length() == 4) {
                    System.out.println(":(");
                    nbTry++;
                }
            } while (nbTry < 3 && !authenticated);
            //System.out.println("TEXT : jtf " + jtf.getText());

        }
    }

    // Function to read/access my pins database (file bdd.txt)
    static public boolean readPinsData(File dataFile, ArrayList<Integer> 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) {

        Main fen = new Main();
    }
}

bdd.txt :

1111
1234
2222
3333
4444
5555
6666
7777
8888
9999

我怎樣才能做到這一點 ? 有任何想法嗎 ?

謝謝,弗洛朗。

您似乎誤解了 actionListener 的概念:Listener 會聽取您的回答,而不會執行任何其他操作。 您在偵聽器中有循環等待正確數量的數字 - 這是錯誤的,您只需要處理偵聽器中的一個輸入(再次單擊后,將再次調用偵聽器)。 因此,可以肯定的是,因為您的循環只包含用戶輸入的一個答案,所以您得到了一個永無止境的循環。 只需在動作偵聽器中處理一個輸入,就可以了。 以下是如何編寫它的說明: http : //docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html

沒有一個答案實際上有效。 簡短的回答,您必須進行以下檢查:

if (jtf.getText().replaceAll("\u00A0","").length() != 4) {
    System.out.println("Pin must be 4 digits");
    JOptionPane.showMessageDialog(null,"Pin must be 4 digits");
    return;
}

說明: NumberFormat使用的 unicode 字符不是不間斷空格。 \\u\u003c/code>之后必須有字符的十六進制表示形式,即

完整代碼:

package codePin;
import java.io.*;
import java.text.NumberFormat;
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.concurrent.atomic.AtomicInteger;


public class Main extends JFrame {

    private static final long serialVersionUID = 1L;

    private JPanel container = new JPanel();
    private JFormattedTextField jtf = new JFormattedTextField(NumberFormat.getIntegerInstance());
    private JLabel label = new JLabel("Enter Pin: ");
    private JButton b = new JButton("OK");

    public Main() {
        this.setTitle("APP");
        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();
        Font police = new Font("Arial", Font.BOLD, 14);
        jtf.setFont(police);
        jtf.setPreferredSize(new Dimension(150, 30));
        jtf.setForeground(Color.BLUE);

        b.addActionListener(new BoutonListener());

        top.add(label);
        top.add(jtf);
        top.add(b);

        this.setContentPane(top);
        this.setVisible(true);
    }

    class BoutonListener implements ActionListener {
        private final AtomicInteger nbTry = new AtomicInteger(0);
        ArrayList<Integer> pins = readPinsData("bdd.txt");
        public void actionPerformed(ActionEvent e) {
            if (nbTry.get() > 2) {
                JOptionPane.showMessageDialog(null, "Number of tries exceeded");
                return;
            }
            final String passEntered=jtf.getText().replaceAll("\u00A0", "");
            if (passEntered.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<Void, Void>() {
                @Override
                protected Void doInBackground() throws Exception {
                    boolean authenticated = false;
                    if (pins.contains(Integer.parseInt(passEntered))) {
                        System.out.println(":)");
                        authenticated = true;
                    }

                    if (!authenticated) {
                        System.out.println(":(");
                        nbTry.incrementAndGet();
                    }
                    return null;
                }
            };
            worker.execute();
        }


    }

    // Function to read/access my pins database (file bdd.txt)
    static public ArrayList<Integer> readPinsData(String dataFile) {
        final ArrayList<Integer> data=new ArrayList<Integer>();
        try {
            BufferedReader reader = new BufferedReader(new FileReader(new File(dataFile)));
            String line;
            try {
                while ((line = reader.readLine()) != null) {
                    try {
                        data.add(Integer.parseInt(line));
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                        System.err.printf("error parsing line '%s'\n", line);
                    }
                }
            } finally {
                reader.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("error:"+e.getMessage());
        }

        return data;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                Main fen = new Main();
            }
        });

    }
}

你可以得到一個JFormattedTextField的文本長度,在這里說 jtf 這樣:

jtf.getText().length(); 

注意:根據您的需要使用此:

String s = jtf.getText();
s = s.replaceAll(",", "");
if (s.length() != 4) 

但是您遇到的問題是由於您使用循環的方式。

我認為您想在用戶完全輸入數字時顯示反應,如果是這樣,您根本不需要循環。


根據評論:

  • 刪除循環(nTry < 3 ...)
  • 定義int nbTry = 0; 作為班級成員並在您的動作偵聽器中跟蹤它。
  • BoutonListener內部檢查一切是否正確,否則 nTry++,如果 nTry >=3,則做任何你想做的事情。

import java.io.*;
import java.text.NumberFormat;
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Main extends JFrame {
    //-------------------------------here
    int nbTry = 0;
    //-------------------------------here

    private static final long serialVersionUID = 1L;

    private JPanel container = new JPanel();
    private JFormattedTextField jtf = new JFormattedTextField(NumberFormat.getIntegerInstance());
    private JLabel label = new JLabel("Enter Pin: ");
    private JButton b = new JButton("OK");

    public Main() {


        jtf.getText().length();
        this.setTitle("APP");
        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();
        Font police = new Font("Arial", Font.BOLD, 14);
        jtf.setFont(police);
        jtf.setPreferredSize(new Dimension(150, 30));
        jtf.setForeground(Color.BLUE);

        b.addActionListener(new BoutonListener());

        top.add(label);
        top.add(jtf);
        top.add(b); 

        this.setContentPane(top);
        this.setVisible(true);
    }

    class BoutonListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            String s = jtf.getText();
            s = s.replaceAll(",", "");
            System.out.println(s);
            System.out.println(s.length());
            boolean authenticated = false;
            if (nbTry > 3) {
                //Oops, enough!
            }
            if (s.length() != 4) { 
                System.out.println("Pin must be 4 digits");
            } else {
                System.out.println("Checking...");
                //and check here!
                ArrayList<Integer> pins = new ArrayList<Integer>(); 
                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(jtf);

                for (int i = 0; i < thePins.length; i++) {
                    if (passEntered.equals(thePins[i]) && jtf.getText().length() == 4) {
                        System.out.println(":)");
                        authenticated = true;
                        break;
                    }
                }
                if (authenticated) {
                    //Congratulation! 
                }
                else {
                    nbTry++;
                }
            }
        }
    }

    // Function to read/access my pins database (file bdd.txt)
    static public boolean readPinsData(File dataFile, ArrayList<Integer> 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) {

        Main fen = new Main();
    }
}

您的代碼中有一個無限循環,因此當第一次調用BoutonListener.actionPerformed時,它只是在那里旋轉而不退出。

您將不得不顯着修改您的代碼。 首先將 do-while 條件中使用的變量提取到字段中,並在每次調用actionPerformed時更新這些字段。

您將陷入無限循環,因為如果 PIN 與長度不匹配,用戶將沒有機會重新輸入他的 PIN。

Looping 和 Listeners 在這種情況下不能很好地工作。 為什么不將相關變量(例如nbTry )保留為成員並執行檢查而不循環?

您的錯誤在於if()條件:

for (int i = 0; i < thePins.length; i++) {
    if (passEntered.equals(thePins[i]) && jtf.getText().length() == 4) {
        System.out.println(":)");
        authenticated = true;
        break;
    }
}

由於您的 pinCode 的長度不等於 4,因此您永遠不會驗證條件,也永遠不會break do-while()循環。

順便說一句,使用break不是一個好主意,因為您總是可以找到允許您避免它的循環類型或條件!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM