【问题标题】:output string using java textfield.setText() by using for loop使用 for 循环使用 java textfield.setText() 输出字符串
【发布时间】:2013-02-08 21:41:37
【问题描述】:

问题是,我尝试制作第二个文本字段 (textFieldGen) 来打印出确切的结果,例如控制台。目前,第二个文本字段仅显示一个字符串。

这是我第一次编写 Java GUI。 (额外信息,我使用 Eclipse 和 WindowBuilder + GEF 构建它)

import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import java.awt.TextField;
import java.awt.Label;
import java.awt.Button;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

public class PassGenerator {
private JFrame frmPasswordGenerator;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                PassGenerator window = new PassGenerator();
                window.frmPasswordGenerator.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the application.
 */
public PassGenerator() {
    initialize();
}

/**
 * Initialize the contents of the frame.
 */
private void initialize() {
    frmPasswordGenerator = new JFrame();
    frmPasswordGenerator.setTitle("Password Generator");
    frmPasswordGenerator.setBounds(100, 100, 419, 229);
    frmPasswordGenerator.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frmPasswordGenerator.getContentPane().setLayout(null);

    final TextField textFieldGen = new TextField();
    final TextField textFieldPass = new TextField();

    textFieldPass.setBounds(74, 60, 149, 19);
    frmPasswordGenerator.getContentPane().add(textFieldPass);

    Label labelPass = new Label("Password Length:");
    labelPass.setBounds(74, 33, 177, 21);
    frmPasswordGenerator.getContentPane().add(labelPass);

    Button genButton = new Button("Generate");
    genButton.setBounds(262, 60, 86, 23);
    frmPasswordGenerator.getContentPane().add(genButton);
    // Add action listener to button
    genButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
        // Execute when button is pressed
        //System.out.println("You clicked the button");
            String getTxt = textFieldPass.getText();
            boolean y = true;

            do{
                try{
                    int c = Integer.parseInt(getTxt);
                    Random r = new Random();
                    String[] alphabet = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","w","x","y","z"};
                    int nc = 0-c;
                    int c2 = c/2;
                    int nc2 = 0-c2;
                    int ncm = (nc+1)/2;

                    if (c%2 == 0){
                        for(int x = nc2; x<0;x++){
                            int alphaNum = r.nextInt(26);
                            System.out.print(alphabet[alphaNum]);
                            String alpha = alphabet[alphaNum];
                            textFieldGen.setText(alpha.toString());
                            int numNum = r.nextInt(10);
                            System.out.print(numNum);
                            textFieldGen.setText(Integer.toString(numNum));
                        }
                    }
                    else {
                        for(int x = ncm; x<0;x++){
                            int alphaNum = r.nextInt(26);
                            System.out.print(alphabet[alphaNum]);
                            String alpha = alphabet[alphaNum];
                            textFieldGen.setText(alpha.toString());
                            int numNum = r.nextInt(10);
                            System.out.print(numNum);
                            textFieldGen.setText(Integer.toString(numNum));
                        }
                        int numNum = r.nextInt(10);
                        System.out.print(numNum);
                        textFieldGen.setText(Integer.toString(numNum));
                    }
                    y = false;
                }
                catch (NumberFormatException e1 ){
                    int messageType = JOptionPane.PLAIN_MESSAGE;
                    JOptionPane.showMessageDialog(null, "Please Enter Integer only", "Error!!", messageType);
                    y = false;
                }
            }while (y);
        }
    });          

    Label labelGen = new Label("Generated Password:");
    labelGen.setBounds(74, 109, 149, 21);
    frmPasswordGenerator.getContentPane().add(labelGen);


    textFieldGen.setBounds(74, 136, 149, 19);
    frmPasswordGenerator.getContentPane().add(textFieldGen);

    Button copyButton = new Button("Copy");
    copyButton.setBounds(262, 136, 86, 23);
    frmPasswordGenerator.getContentPane().add(copyButton);  
}

}

【问题讨论】:

    标签: java swing document jtextfield parseint


    【解决方案1】:

    使用textFieldGen.setText (textFieldGen.getText () + "\n" + Integer.toString(numNum))

    【讨论】:

    • @MikhailVladimirov 如果我想在每次单击它时重置 genButton,我应该在 addActionListener 上添加什么?因为当我再次单击它时它会附加结果。
    【解决方案2】:

    我不明白您为什么要设置文本字段的内容两次。我会这样做:

    int alphaNum = r.nextInt(26);
    System.out.print(alphabet[alphaNum]);
    String alpha = alphabet[alphaNum];
    //textFieldGen.setText(alpha.toString());
    int numNum = r.nextInt(10);
    System.out.print(numNum);
    //textFieldGen.setText(Integer.toString(numNum));
    textFieldGen.setText(alpha + Integer.toString(numNum));
    

    一般来说,当您只想在文本字段中添加一些字符时,替换整个文本并不是一个好习惯。如果您不喜欢上述内容,那么您可以这样做:

    textField.setText(alpha);
    ...
    Document doc = textField.getDocument();
    doc.insertString(doc.getLength(), Integer.toString(numNum), null);
    

    编辑:

    import java.awt.*;
    import javax.swing.*;
    import javax.swing.text.*;
    
    public class SSCCE extends JPanel
    {
        public SSCCE()
        {
            JTextField textField = new JTextField(20);
            add( textField );
    
            textField.setText( "testing: " );
    
            try
            {
                Document doc = textField.getDocument();
                doc.insertString(doc.getLength(), "1", null);
            }
            catch(Exception e) {}
        }
    
        private static void createAndShowUI()
        {
            JFrame frame = new JFrame("SSCCE");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add( new SSCCE() );
            frame.pack();
            frame.setLocationRelativeTo( null );
            frame.setVisible( true );
        }
    
        public static void main(String[] args)
        {
            EventQueue.invokeLater(new Runnable()
            {
                public void run()
                {
                    createAndShowUI();
                }
            });
        }
    }
    

    【讨论】:

    • @MarkJue,然后发布您的 SSCCE 来证明问题。我猜不出你到底做了什么。有关 SSCCE 的示例,请参阅我的编辑。
    猜你喜欢
    • 1970-01-01
    • 2017-12-24
    • 2016-11-05
    • 1970-01-01
    • 2021-12-24
    • 2021-10-06
    • 2014-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多