简体   繁体   English

从main实现并调用JFrame / ActionListener类

[英]Implementing and calling JFrame/ActionListener class from main

I'm trying to get my program to launch a gui that gathers information before the actual programs starts. 我正试图让我的程序在实际程序启动之前启动一个收集信息的gui。 In main I try to call the JFrame which should then run until the start button is pressed and then the main program should launch. 在main中我尝试调用JFrame,然后应该运行直到按下开始按钮然后主程序应该启动。 Everything seems to be correct except for the base class of the initializeLauncher. 除了initializeLauncher的基类之外,一切似乎都是正确的。 Thanks! 谢谢!

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

class InitializeLauncher implements ActionListener {

    InitializeLauncher() {
        JFrame frame = new JFrame("launcherClient");

        Container c = frame.getContentPane();
        Dimension d = new Dimension(700,400);
        c.setPreferredSize(d);

        JButton startButton = new JButton("Start");
        JPanel pane = new JPanel();

        startButton.addActionListener(this);

        pane.add(startButton);
        frame.add(pane);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setResizable(false);
        frame.setVisible(true);
    }

    public void buttonClicked(ActionEvent e)
    {
        ApplicationDeploy displayExample = new ApplicationDeploy();
        displayExample.initializeGameClient();
    }
}

...and then in main I call this: ...然后在主要我称之为:

InitializeLauncher launcher = new InitializeLauncher();
launcher.InitializeLauncher();

By making your class abstract, you're fixing the wrong thing. 通过使你的课抽象,你正在修复错误的东西。 Instead you should give your class the missing method, public void actionPerformed(ActionEvent e) {...} 相反,你应该给你的班级缺少方法, public void actionPerformed(ActionEvent e) {...}

The basic rule here is, if you state that your class is going to implement an interface, here the ActionListener interface, then the class must implement all of the methods of the interface. 这里的基本规则是,如果您声明您的类将要实现一个接口,这里是ActionListener接口,那么该类必须实现该接口的所有方法。

@Override
public void actionPerformed(ActionEvent e) {
   // ... your code that should occur when the button is pressed goes here
}

Note that your buttonClicked(...) method will do nothing useful for you. 请注意,您的buttonClicked(...)方法对您没有任何帮助。 Likely you'll want to get rid of that method and put its code into the actionPerformed method. 可能你想要摆脱那个方法并将其代码放入actionPerformed方法。

As an aside, I often use a JOptionPane for the functionality that you're using a JFrame for. 顺便说一下,我经常使用JOptionPane来获得你正在使用JFrame的功能。

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

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