gpt4 book ai didi

java - 总是需要做静态

转载 作者:行者123 更新时间:2023-11-29 07:04:43 24 4
gpt4 key购买 nike

我正在做一个项目,我遇到了一些我还没有完全理解的事情。

每次我想调用另一个类的方法,或使用 jform 中的变量时,我的 netbeans 都说我需要将其设为“静态”。现在我明白了静态的含义,并且我已经从我使用方法的类中创建了对象,但即便如此,netbeans 仍然说我需要先将对象设为静态,然后才能在 MAIN() 方法中使用它。甚至像组合框这样的 jform 变量。

有人可以解释一下吗?

提前致谢!

编辑:

这是我项目中的一些代码。它很小,但应该能说明问题:

主类:

    public class SpeeloTheek {

/**
* @param args the command line arguments
*/
public static Controller MainController = new Controller();
public static SummaryScreen MainSummaryScreen = new SummaryScreen();

public static void main(String[] args) {
// TODO code application logic here
MainSummaryScreen.setVisible(true);
MainController.SetFullScreen(MainSummaryScreen);

MainController.ComboBoxItemSelected(SummaryScreen.choiceBox);
}

Controller 类:

    package speelotheek;

import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;

public class Controller {

//Method to make JFrame fullscreen//
public void SetFullScreen(JFrame frameToUse) {
frameToUse.setExtendedState(JFrame.MAXIMIZED_BOTH);
}

public void ComboBoxItemSelected(final JComboBox comboBoxToUse) {

comboBoxToUse.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
WhichSummary(comboBoxToUse);
}
}
});

}

public void WhichSummary(JComboBox comboBoxToUse) {

System.out.println(comboBoxToUse.getSelectedItem());

}

}

编辑2:

谢谢大家 :) 我发现了问题。我在 main 方法中而不是在 main 方法之上实例化了这个类,它起作用了:)

最佳答案

为了调用类的非静态成员,您需要实例化一个对象。

例子:

Foo myObject = new Foo();  // myObject is an object of class Foo

Foo.callToStaticMember(); // static members can be called using the class name

myObject.callToNonStaticMember(); // non-static members require an object of the class

关于java - 总是需要做静态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21132681/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com