【问题标题】:How to call non-static method from static method? [duplicate]如何从静态方法调用非静态方法? [复制]
【发布时间】:2014-04-16 21:27:29
【问题描述】:

我正在使用 swing 来制作一个带有 JFrames 的 java 项目。我正在尝试调用非静态方法 build(),它使用其组件构建 JFrame。但是,构建不能是静态的,因为我使用的是 getClass(),它需要一个非静态方法。我不能让我的 main 非静态,所以我怎么能调用 build?这是我的代码:

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;

}

【问题讨论】:

  • 通过创建其持有者类的实例new MainUI().build();

标签: java swing jframe static-methods non-static


【解决方案1】:

只需创建一个类的实例:

MainUI mainUI = new MainUI();
mainUI.build();

没有类的实例就不能调用非静态方法。

【讨论】:

    猜你喜欢
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-04
    • 1970-01-01
    相关资源
    最近更新 更多