[英]why I can't change text in JLabel from public static void main?
I'm new in netbeans and java swing, but also confused. 我是netbeans和java swing的新手,但也感到困惑。 I put some JLabel's from drag and drop in netbeans with some text, and now I want to change that text from the code, and I'm getting error non-static variable can not be referred from static context. 我从Netbeans中拖放了一些JLabel,并添加了一些文本,现在我想从代码中更改该文本,并且我收到了无法从静态上下文引用非静态变量的错误。 help 救命
FirstFrame f = new FirstFrame();
f.labSifra.setText("aaaa");
I tried this and when I start app JLabel is still with the old text 我尝试了这个,当我启动应用程序时,JLabel仍然是旧文本
Because you try to modify your JLabel from static void main
因为您尝试从static void main
修改JLabel
public static void main(String[] args) {
//NetBeans GUI Init
}
And somewhere in your code generated from NetBeans you have: 从NetBeans生成的代码中,您具有:
private javax.swing.JLabel jLabel1;
If you drop for example JButton into form builder and double click it you will have method: 如果将例如JButton拖放到表单生成器中,然后双击它,则将具有方法:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// Here you can change text of JLabel.
jLabel1.setText("bla bla");
}
You can change defualt scope/modifier of jLabel1 by right click over GUI Component then Properties -> Code -> Variable Modifiers
您可以通过右键单击GUI组件,然后单击Properties -> Code -> Variable Modifiers
来更改jLabel1的默认作用域/修饰符。
main
is a static function, and the JLabel is a non-static member of the class, and you cannot access non-static members from a static function. main
是静态函数,而JLabel是类的非静态成员,并且您不能从静态函数访问非静态成员。
You need to delegate the setting of the text to a member function (which is non-static) of the instance of the class you've constructed in your main. 您需要将文本的设置委派给您在main中构造的类的实例的成员函数(非静态)。
Now, if you don't understand what static and non-static mean in this context - please refer to a good book. 现在,如果您不了解静态和非静态的含义,请参阅一本好书。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.