简体   繁体   English

Java-如何在Main类中运行init方法

[英]Java - How to run init method in Main class

I'm want to run my gui, but I don't really know how to initialize this class. 我想运行我的GUI,但是我真的不知道如何初始化此类。 I'm transitioning from python to Java, so I'm still fairly new to this. 我正在从python过渡到Java,因此对此还很陌生。 The code works, I just need to know how to run it. 该代码有效,我只需要知道如何运行它即可。

import javax.swing.*;
import java.awt.*;

// Where the main run function for the application will lie
public class MainWindow extends JFrame{
    public void init(){

        // Initial window
        JFrame startFrame = new JFrame("P.D");
        startFrame.setSize(1200, 800);
        startFrame.setVisible(true);
        startFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Panel to hold our buttons
        JPanel startPanel = new JPanel();
        startFrame.add(startPanel);


        // Button to initialize everything
        JButton startButton = new JButton("Start");
        startPanel.add(startButton);
        startFrame.setLayout( new GridBagLayout() );
        startFrame.add(startButton, new GridBagConstraints());


        // Take out the border around the text
        startButton.setFocusable(false);

    }
    public static void main(String[] args) {



    }
}

How do I run the init() method under static void main(String[] args? 如何在静态void main(String [] args下运行init()方法?

suppose you just create a new MainWindow object in main method and call the init() method. 假设您只是在main方法中创建一个新的MainWindow对象,然后调用init()方法。

public static void main(String[] args){

        new MainWindow().init();

    }

You can also run the function by making it static. 您也可以通过使其静态化来运行该函数。 Like python "static method". 就像python的“静态方法”一样。

public static void init(){

.. And: ..并且:

  public static void main(String[] args) {
      init();

}

You can implement constructor instead of init() method and you can start gui like below 您可以实现构造函数而不是init()方法,并且可以如下所示启动gui

public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new MainWindow().setVisible(true);
        }
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM