0

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

我想从 main 方法向文本字段添加文本,所以我在 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                   

}

4

2 回答 2

1

因为在jTextField1您尝试设置其文本时该变量尚未初始化。实际上,它仅在事件队列调用在 main 方法末尾传递给 invokeLater 的可运行对象时才初始化 t=。

此外,您正在从主线程访问 Swing 组件,而 Swing 组件只能在事件调度线程中使用。这就是为什么,顺便说一句,main 方法在传递给EventQueue.invokeLater(). 请阅读有关并发的 Swing 教程,否则您的下一个问题会问为什么在事件侦听器中休眠会冻结整个 GUI。

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

于 2013-04-12T19:19:58.623 回答
0

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

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

public JFrame_Test_UI() {
    initComponents();
    jTextField1.setText("WHATEVER");    
}
于 2013-04-15T07:09:27.997 回答