[英]Java: Access a Jframe Label from a static class
我一直在遇到一些麻烦,第一次是OOP编程,是从另一个类更新JFrame Label。
我可以访问类中的类和静态变量,甚至尝试访问静态方法/函数,但仍然无法从方法内部访问JFrame标签。
我目前有2个类GUI.java和Credit.java,GUI.java有JFrame。
GUI.Java具有标签lblLCD并被编码为:
public class GUI extends javax.swing.JFrame {
public static String LCDString = "":
public GUI() {
initComponents();
}
public static void RefreshLCD() {
lblLCD.setText(LCDString);
}
}
Credit.java没有JFrame并被编码为:
public class Credit {
public static void Reset() {
GUI.RefreshLCD();
}
}
关于如何解决这个问题的任何想法?
您不能从静态方法访问非静态变量。 您可能需要研究有关static关键字的更多信息。 同样,使用大量静态方法也可能是不良设计的标志。 感觉在您的示例中,您应该使用较少静态的方法。
话虽这么说,您将需要对JFrame(GUI)实例的引用,以便能够调用非静态方法。
我创建了一些示例代码,希望对您有所帮助:
图形用户界面
public class GUI extends JFrame{
// Note: this should probably not be a static variable
// You can use a private, non-static variable and create a getter/setter method for it
public static String LCDString = "";
public GUI(){
initComponents();
}
// Note: methods in Java start with a lowercase letter
public void refreshLCD(){
lblLCD.setText(LCDString);
}
}
Credit.java
public class Credit {
// Keep a reference to your jframe, so you can call non-static public methods on it
private GUI gui;
// Pass a GUI object to your Credit object
public Credit(GUI gui){
this.gui = gui;
}
// This should also probably not be a static method.
// Note: methods in Java should start with a lowercase letter
public void reset(){
gui.refreshLCD();
}
}
主要方法
//Your main method
public static void main(String[] args){
// Create a variable for your new GUI object
GUI gui = new GUI();
// Pass our new GUI variable to the Credit object we're creating
Credit credit = new Credit(gui);
// Lets set some text
GUI.LCDString = "Hello World";
// If LCDString was not static it would be something like this:
// gui.setLCDString("Hello World");
// Now we have a credit instance and can call the reset() method on this object
credit.reset();
}
这是因为,从您的问题我可以看出,您的变量lblLCD
是非静态的。 并且非静态变量不能在static
方法中引用。
要引用该非静态变量,您需要首先实例化类GUI,然后使用该对象对其进行引用。
public static void RefreshLCD() {
GUI gui = new GUI();
gui.lblLCD.setText(LCDString);
}
使变量lblLCD
静态。
为此,请勿使用static
。 使方法RefreshLCD()
,方法Reset()
和变量LCDString
非静态。
从您的Reset()
方法中,将class GUI
实例化,然后调用RefreshLCD()
方法。
public class GUI extends JFrame {
public String LCDString = "";
public GUI() {
initComponents();
}
public void RefreshLCD() {
lblLCD.setText(LCDString);
}
}
public class Credit {
public void Reset() {
new GUI().RefreshLCD();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.