我正在尝试制作一个包含 3 个类(class)的应用程序。 Controller (主类)、SerialHandler 和 MainWindow(使用 NetBeans Gui Builder 创建的 JFrame 表单)。
public class Controller {
SerialHandler serialHandler;
MainWindow mainWindow;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Controller controller = new Controller();
controller.initializeSystem(controller);
}
public void initializeSystem(Controller _controller){
mainWindow = new MainWindow(_controller);
mainWindow.setVisible(true);
}
public void anotherMethod(){
mainWindow.setMyLabelText("Hello");
}
}
所以问题是,如果我这样做并且 SerialHandler 类中的事件调用 anotherMethod(),则 setMyLabelText 方法不起作用,但如果我从initializeSystem()调用它;它有效。
现在,如果我在 main 中声明 mainwindow,则 mainWindow 实例在 anotherMethod() 中是不可见的。
如果我在 main 之外声明 mainWindow 对象并尝试从主上下文中使用它的方法,我不能,因为 mainWindow 对象已在非静态上下文之外声明。
有人可以帮助我或至少为我指出正确的方向吗?
谢谢!
最佳答案
您的代码设计不一致:
public static void main(String[] args) {
// TODO code application logic here
Controller controller = new Controller();
controller.initializeSystem(controller);
}
public void initializeSystem(){
mainWindow = new MainWindow(_controller);
mainWindow.setVisible(true);
}
您正在创建 Controller ,并将其作为参数传递给其 initializeSystem
,这是多余的,因为您可以在 initializeSystem
中使用 this
.
你应该这样做:
public static void main(String[] args) {
// TODO code application logic here
Controller controller = new Controller();
controller.initializeSystem();
}
public void initializeSystem(Controller _controller){
mainWindow = new MainWindow(this);
mainWindow.setVisible(true);
}
第二个不一致之处是方法 anotherMethod
,它访问您的 UI 并更新其中的内容。您应该将其留给 Controller 。像这样的事情:
public class Controller {
//...
public void updateUIText(String text){
SwingUtilities.invokeLater(new Runnable() {
public void run() {
mainWindow.setMyLabelText("Hello");
}
});
}
}
现在,SerialHandler
可以在需要时通过 Controller 更新 UI。您所要做的就是将 Controller
引用传递给 SerialHandler
编辑 请注意,我使用 SwingUtilities.invokeLater
来更新 UI,这将确保 Controller
即使在我认为这是你的情况的多线程场景
关于java - Netbeans GUI 和非静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11351584/