简体   繁体   English

Java Swing文本域问题

[英]Java Swing textfield issue

I created a GUI using Netbeans which took asked the user to input the content in textfields and textareas . 我使用Netbeans创建了一个GUI,它要求用户在textfieldstextareas输入内容。 When I'm trying to use it in other classes, the text entered in the textfield does not appear when i use getText method on it. 当我尝试在其他类中使用它时,当我在其上使用getText方法时,在文本textfield中输入的文本不会出现。 Rather in its place, the text which appears in the textfield specified using the edit text option in Netbeans, appears whenever getText method is used. 取而代之的是,只要使用getText方法,就会出现使用Netbeans中的编辑文本选项指定的文本textfield中显示的文本。 Is the problem related to some sort of sequencing or order? 问题与某种排序或顺序有关吗? Because I believe the text from the GUI, is being referenced before the user is actually entering it. 因为我相信GUI中的文本是在用户实际输入之前被引用的。

public class GUI extends javax.swing.JFrame {

public GUI() {

    initComponents();
}
public void Grow(){
    initComponents();
}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jTextField1 = new javax.swing.JTextField();
    jPanel1 = new javax.swing.JPanel();
    username = new javax.swing.JTextField();
    UsernameLabel = new javax.swing.JLabel();
    PasswordLabel = new javax.swing.JLabel();
    subject = new javax.swing.JTextField();
    SubjectLabel = new javax.swing.JLabel();
    jScrollPane1 = new javax.swing.JScrollPane();
    message = new javax.swing.JTextArea();
    jLabel1 = new javax.swing.JLabel();
    salutation = new javax.swing.JTextField();
    jLabel2 = new javax.swing.JLabel();
    sendbutton = new javax.swing.JButton();
    password = new javax.swing.JPasswordField();

    jTextField1.setText("jTextField1");

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jPanel1.setBackground(new java.awt.Color(204, 204, 255));
    jPanel1.setBorder(new        javax.swing.border.LineBorder(java.awt.SystemColor.controlDkShadow, 3, true));

    username.setText("Enter your text here");

    UsernameLabel.setFont(new java.awt.Font("Arial", 1, 13)); // NOI18N
    UsernameLabel.setForeground(new java.awt.Color(255, 51, 51));
    UsernameLabel.setText("Username");

    PasswordLabel.setFont(new java.awt.Font("Arial", 1, 13)); // NOI18N
    PasswordLabel.setForeground(new java.awt.Color(255, 51, 51));
    PasswordLabel.setText("Password");

    subject.setText("Enter your text here");
    subject.setCursor(new java.awt.Cursor(java.awt.Cursor.TEXT_CURSOR));
    subject.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            subjectActionPerformed(evt);
        }
    });

    SubjectLabel.setFont(new java.awt.Font("Arial", 1, 13)); // NOI18N
    SubjectLabel.setForeground(new java.awt.Color(255, 51, 51));
    SubjectLabel.setText("Subject");

    message.setColumns(20);
    message.setRows(5);
    message.setText("Enter your text here");
    jScrollPane1.setViewportView(message);

    jLabel1.setFont(new java.awt.Font("Arial", 1, 13)); // NOI18N
    jLabel1.setForeground(new java.awt.Color(255, 51, 51));
    jLabel1.setText("Message");

    salutation.setText("Enter your text here");

    jLabel2.setFont(new java.awt.Font("Arial", 1, 13)); // NOI18N
    jLabel2.setForeground(new java.awt.Color(255, 51, 51));
    jLabel2.setText("Salutation");

    sendbutton.setForeground(new java.awt.Color(255, 51, 51));
    sendbutton.setText("Send");
    sendbutton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            sendbuttonActionPerformed(evt);
        }
    });

    password.setText("Enter your text here");

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jScrollPane1)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jLabel2)
                        .addComponent(SubjectLabel))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(salutation)
                        .addComponent(subject))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(UsernameLabel, javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(PasswordLabel))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(username)
                        .addComponent(password))
                    .addGap(47, 47, 47))
                .addComponent(jLabel1)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                    .addGap(0, 0, Short.MAX_VALUE)
                    .addComponent(sendbutton)))
            .addContainerGap())
    );
    jPanel1Layout.setVerticalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(username, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(UsernameLabel)
                .addComponent(subject, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(SubjectLabel))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(PasswordLabel)
                .addComponent(salutation, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jLabel2)
                .addComponent(password, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 20, Short.MAX_VALUE)
            .addComponent(jLabel1)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 185, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(11, 11, 11)
            .addComponent(sendbutton))
    );

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    );

    pack();
}// </editor-fold>                        


private void subjectActionPerformed(java.awt.event.ActionEvent evt) {                                        
    // TODO add your handling code here:
}                                       

private void sendbuttonActionPerformed(java.awt.event.ActionEvent evt) {                                           
    // TODO add your handling code here:
    MMMMain object = new MMMMain();
    object.MassMail();

}                                          

/**
 * @param args the command line arguments
 */
public void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new GUI().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JLabel PasswordLabel;
private javax.swing.JLabel SubjectLabel;
private javax.swing.JLabel UsernameLabel;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextField jTextField1;
public javax.swing.JTextArea message;
public javax.swing.JPasswordField password;
public javax.swing.JTextField salutation;
public javax.swing.JButton sendbutton;
public javax.swing.JTextField subject;
public javax.swing.JTextField username;
// End of variables declaration                   
}

Is the problem related to some sort of sequencing or order? 问题与某种排序或顺序有关吗? Because I believe the text from the GUI, is being referenced before the user is actually entering it. 因为我相信GUI中的文本是在用户实际输入之前被引用的。

Regardless your code doesn't actually recreate your problem, Swing works in an event-driven scenario. 无论您的代码实际上没有重现您的问题,Swing都可以在事件驱动的场景中工作。 This means an event must happen if you want to get the text field's text properly. 这意味着如果要正确获取文本字段的文本,则必须发生事件。 For instance: 例如:

JTextField textField = new JTextField(20);
JFrame frame = new JFrame("Sample");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(textField);
frame.pack();
frame.setVisible(true);

System.out.println(textField.getText());

Then nothing will be printed because the getText() call happens before the user has had even the chance to write anything. 然后不会打印任何内容,因为getText()调用用户甚至有机会编写任何内容之前发生。 But if you do this: 但是如果你这样做:

final JTextField textField = new JTextField(20);
textField.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent evt) {
        System.out.println(textField.getText());
    }
};

JFrame frame = new JFrame("Sample");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(textField);
frame.pack();
frame.setVisible(true);

Then the text will be printed when user types some text and press Enter key in the text field. 然后,当用户键入一些文本并在文本字段中按Enter键时,将打印文本。 This is because an ActionEvent is fired and text field has attached an ActionListener which listens to those events and does something in response. 这是因为触发了一个ActionEvent ,并且文本字段附加了一个ActionListener ,它侦听这些事件并做出响应。 You can read more about it in Writing Event Listeners section of the Swing tutorial . 您可以在Swing教程的“ 编写事件监听器”部分中阅读更多相关信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM