如何在netbeans中从main方法设置文本域文本?

时间:2013-04-12 17:58:41

标签: java swing netbeans jtextfield main

我是NetBeans的新手(但不是Java),我遇到了问题。我用NetBeans创建了一个GUI,它只包含JTextFieldJButton

我想从main方法向textfield添加文本,所以我将以下行添加到main方法的末尾(所以基本上在main方法中生成的代码创建了JFrame,并且仅在之后这是我的额外行):jTextField1.setText("WHATEVER"); 没有任何反应。我已将文本字段更改为public static,但仍然没有。

但是,如果我在按钮的actionPerformed方法中使用相同的行,则可以正常工作。

为什么呢?为什么我不能从主类中设置文本?

以下是代码:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
  */
 package pac.jframe_test;

  /**
  *
  * @author Orand
  */
public class JFrame_Test_UI extends javax.swing.JFrame {

/**
 * Creates new form JFrame_Test_UI
 */
public JFrame_Test_UI() {
    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() {

    jButton1 = new javax.swing.JButton();
    jTextField1 = new javax.swing.JTextField();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jButton1.setText("jButton1");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(154, 154, 154)
            .addComponent(jButton1)
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addContainerGap(112, Short.MAX_VALUE)
            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 185, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(103, 103, 103))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addContainerGap(109, Short.MAX_VALUE)
            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(96, 96, 96)
            .addComponent(jButton1)
            .addGap(52, 52, 52))
    );

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

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    jTextField1.setText("whatever");
}                                        

/**
 * @param args the command line arguments
 */
public static 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(JFrame_Test_UI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(JFrame_Test_UI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(JFrame_Test_UI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(JFrame_Test_UI.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 JFrame_Test_UI().setVisible(true);
        }
    });
    jTextField1.setText("WHATEVER");
}
// Variables declaration - do not modify                     
private javax.swing.JButton jButton1;
public static javax.swing.JTextField jTextField1;
// End of variables declaration                   

}

2 个答案:

答案 0 :(得分:1)

因为在您尝试设置文本时,jTextField1变量尚未初始化。实际上,只有当事件队列在main方法结束时调用runnable传递给invokeLater时才会初始化t =。

此外,您正在从主线程访问Swing组件,并且只能在事件disptach线程中使用Swing组件。这就是为什么BTW,main方法初始化传递给EventQueue.invokeLater()的runnable中的帧。请阅读Swing tutorial about concurrency,否则您的下一个问题将会问为什么在事件监听器中睡眠会冻结整个GUI。

这个字段不应该是公开的,它应该更不是静态的。为什么不从框架构造函数初始化字段的文本?这就是应该初始化的地方。

答案 1 :(得分:0)

根据netbeans代码架构,它从扩展JFrame的类的默认构造中调用 initComponents()方法,因此所有内存分配您在代码中使用的> JComponents 将在 initComponents 方法体中完成。所以建议在 initComponents 方法调用之后调用这些JComponents的任何方法。

你的代码应该是那样......

public JFrame_Test_UI() {
    initComponents();
    jTextField1.setText("WHATEVER");    
}