繁体   English   中英

将JFrame从启动方法转换为另一种方法

[英]Getting a JFrame from the starting method into another method

我有一个问题,我试图从同一类中的另一个方法( addAButton )的开头调用公共Menu方法中的JFrame,但无法正常工作。 我试过在公共Menu内调用addAButton ,但是我不能,因为我不能在该类中放置容器。 代码:

public class Menu {

    public Menu(Component component) {

        JFrame frame = new JFrame("...");
        frame.setSize(new Dimension(1050, 700));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(component);

        // Set up the content pane.
        try {
            frame.setContentPane(new JLabel(new ImageIcon(ImageIO
                    .read(new File("res/menuBackground.png")))));
        } catch (IOException e) {
            e.printStackTrace();
        }
        addComponentsToPane(frame.getContentPane());

        // Display the window.
        frame.pack();
        frame.setVisible(true);
    }



        public static void addComponentsToPane(Container pane) {

        //some code...

        pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));

        addAButton("SP", "res/Singleplayer.png",
                "res/Singleplayer_pressed.png", pane, true);

      //other buttons...
       }



        public static void addAButton(final String text, String BtnIcon,
            String PressBtnIcon, Container container, Boolean isEnabled) {

        //stuff for buttons...

        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (button.getText().equals("Q")) {
                    System.exit(0);
                } else if (button.getText().equals("SP")) {
                    Component component = new Component();

                     //here I want to put frame.dispose to close this window for when the game window opens.

                    component.start();

                } else if(button.getText().equals("O")) {

                 //here I want to put frame.dispose to close this window for when the options window opens.

                    Component.Options();

                }
            }

        });
    }
}

首先,公共Menu代码块不是方法。 它是一个构造函数。 它的功能是初始化并准备此类的新对象的字段。

frame变量是局部变量 如果在代码块内声明变量,则只能在该代码块内使用该变量。 声明了它的代码块结束时,将立即丢弃局部变量。

如果您希望能够通过不同的方法访问数据项,则意味着该数据项是对象状态的一部分。 也就是说,对象应在整个生命周期内一直保留该项目,以便在其上调用的下一个方法将使该项目可用。

当数据项是对象状态的一部分时,应将其声明为field 也就是说,不应在任何方法或构造函数内部声明它,而应在所有方法和构造函数之前声明它。

声明字段后,可以在构造函数中对其进行初始化。 然后,您可以从同一类中的任何方法访问该字段。

public class Menu {

    private JFrame frame;  // This is the field declaration

    public Menu( Component component ) {

         frame = new JFrame("..."); // Here you just initialize, not declare.

         ... // Do the rest of your initializations

    }

    ... // Other methods
}

现在,您可以以任何方法使用场frame

暂无
暂无

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

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