java 如何从netbeans中的main方法设置文本字段文本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15977909/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set a textfield text from main method in netbeans?
提问by dwarfhero
I am new to NetBeans(but not Java) and I have a problem. I have created a GUI with NetBeans, which contains only a JTextFieldand a JButton.
我是NetBeans(但不是 Java)的新手,我遇到了问题。我用 NetBeans 创建了一个 GUI,它只包含一个JTextField和一个JButton。
I want to add text to the textfield from the main method, so I added the following line to the end of the main method (so basically in the main method the generated code creates the JFrame, and only after that comes my extra line): jTextField1.setText("WHATEVER");
And nothing happens. I have changed the textfield to public static
, but still nothing.
我想从 main 方法向文本字段添加文本,所以我在 main 方法的末尾添加了以下行(所以基本上在 main 方法中,生成的代码创建了JFrame,然后才出现我的额外行):jTextField1.setText("WHATEVER");
什么也没有发生。我已将文本字段更改为public static
,但仍然没有。
However, if I use the same line within the actionPerformed
method of the button, it works.
但是,如果我actionPerformed
在按钮的方法中使用同一行,它就可以工作。
Why? Why can't I set the text from the main class?
为什么?为什么我不能从主类设置文本?
Here is the code:
这是代码:
/*
* 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
}
}
回答by JB Nizet
Because the jTextField1
variable is not initialized yet at the moment you try to set its text. Indeed, it's only initialized t=when the event queue calls the runnable passed toinvokeLater at the end of the main method.
因为在jTextField1
您尝试设置其文本时该变量尚未初始化。实际上,它仅在事件队列调用在 main 方法结束时传递给 invokeLater 的 runnable 时才初始化 t= 。
Moreover, you're accessing a Swing component from the main thread, and Swing components must only be used from the event disptach thread. That's why, BTW, the main method initializes the frame inside a runnable passed to EventQueue.invokeLater()
. Please read the Swing tutorial about concurrency, or your next question will ask why sleeping in an event listener freezes the whole GUI.
此外,您正在从主线程访问 Swing 组件,并且只能从事件调度线程使用 Swing 组件。这就是为什么,顺便说一句,main 方法在传递给EventQueue.invokeLater()
. 请阅读有关并发的Swing 教程,否则您的下一个问题将询问为什么在事件侦听器中休眠会冻结整个 GUI。
This field should not be public, and it should even less be static. Why don't you initialize the field's text from the frame constructor? That's where it should be initialized.
这个字段不应该是公开的,更不应该是静态的。为什么不从框架构造函数初始化字段的文本?这就是它应该被初始化的地方。
回答by Mayank Tiwari
According to netbeans code architecture, it calls the initComponents()method from the default construction of your Class that extends JFrame, so the memory allocationof all the JComponents, that you are using in your code would be done in initComponentsmethod body. so it is recommended to call any method of these JComponents after the initComponentsmethod call.
根据 netbeans 代码架构,它从扩展 JFrame 的类的默认构造调用initComponents()方法,因此您在代码中使用的所有JComponents的内存分配将在initComponents方法主体中完成。所以建议在initComponents方法调用之后调用这些JComponents的任何方法 。
your code should be like that....
你的代码应该是这样的......
public JFrame_Test_UI() {
initComponents();
jTextField1.setText("WHATEVER");
}