This question already has an answer here:
这个问题在这里已有答案:
- calling non-static method in static method in Java [duplicate] 14 answers
在Java中调用静态方法中的非静态方法[复制] 14个答案
I am using swing to make a java project with JFrames. I am trying to call the non-static method build(), which builds the JFrame with its components. However, build can't be static because I am using getClass(), which requires a non-static method. I can't make my main non-static, so how can I call build? Here is my code:
我正在使用swing来使用JFrames创建一个java项目。我试图调用非静态方法build(),它使用其组件构建JFrame。但是,构建不能是静态的,因为我使用的是getClass(),它需要一个非静态方法。我无法使我的主要非静态,所以如何调用构建?这是我的代码:
public class MainUI {
public static void main(String[] args) {
build(); // Calls build method
}
private void build() {
// Builds JFrame
JFrame frame = new JFrame();
JPanel base = new JPanel();
JLabel background = new JLabel();
frame.setVisible(true);
frame.setTitle("Space Age");
frame.setSize(640,480);
frame.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
frame.setAutoRequestFocus(false);
frame.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
frame.setLocationRelativeTo(null);
base.setSize(640,480);
base.setAlignmentX(0.0F);
base.setAlignmentY(0.0F);
base.setBackground(new java.awt.Color(255,255,255));
background.setSize(640,480);
background.setAlignmentX(0.0F);
background.setAlignmentY(0.0F);
background.setIcon(new javax.swing.ImageIcon(getClass().getResource("/path/image.png")));
frame.add(base);
frame.add(background);
}
// Variable declarations
private JFrame frame;
private JPanel base;
private JLabel background;
}
1 个解决方案
#1
3
Just create an instance of the class:
只需创建一个类的实例:
MainUI mainUI = new MainUI();
mainUI.build();
You can't call a non-static method without an instance of the class.
没有类的实例,您不能调用非静态方法。
#1
3
Just create an instance of the class:
只需创建一个类的实例:
MainUI mainUI = new MainUI();
mainUI.build();
You can't call a non-static method without an instance of the class.
没有类的实例,您不能调用非静态方法。