【问题标题】:Creating JFrame in an instance object在实例对象中创建 JFrame
【发布时间】:2016-05-23 00:10:34
【问题描述】:

我正在尝试显示倒计时,我正在搜索如何执行此操作并尝试代码,但这不是我在这个问题中要问的内容,尽管如果你在这方面帮助我我会很高兴区域也。

这似乎有点初级,但我似乎无法显示 JFrame。 我预测,如果我创建了一个 testmain 实例并且在构造函数中创建了一个 JFrame,它会显示 JFrame。

我什至尝试从键盘获取输入以使其停止。 但是什么也没有发生,程序立即结束。 它说构建成功。

我错过了什么?

public class testmain
{
     Timer t;
     JLabel label;

    public void testmain()
    {

        JFrame myFrame = new JFrame();
        label = new JLabel();
        myFrame.setSize(400, 400);
        myFrame.setAlwaysOnTop(true);
        myFrame.setLocationRelativeTo(null);

        label.setText("This works");
        myFrame.add(label);
        myFrame.setVisible(true);
    //        Scanner keyboard = new Scanner(System.in);
    //        keyboard.nextInt();
    //        start();


    }
     void start()
    {
        t = new Timer(1000, new TimeTest());
    }
    class TimeTest implements ActionListener
    {
        private int counter = 0;
        @Override
        public void actionPerformed(ActionEvent e)
        {
            label.setText("" + counter++);

            if(counter == 10)
                t.removeActionListener(this);
        }
    }

    public static void main(String[] args)
    {
        testmain tester = new testmain();


    }
}

【问题讨论】:

    标签: java constructor jframe main


    【解决方案1】:

    你有一个没有被调用的伪构造函数。构造函数没有返回类型,没有 void,什么都没有。

    改变

    // this never gets called
    public void testmain() {
    }
    

    // but this **will** be called
    public testmain() {
    
    }
    

    顺便说一句,你会想学习和使用Java naming conventions。变量名应全部以小写字母开头,而类名应以大写字母开头。学习这一点并遵循这一点将使我们能够更好地理解您的代码,并让您更好地理解其他人的代码。

    所以这个类实际上应该被称为 TestMain:

    public class TestMain {
    
        public TestMain() {
            // constructor code here
        }
    
    }
    

    【讨论】:

    • 哦,天哪,我怎么会这么愚蠢,把 void 放在那里...谢谢您的回答!而且我确实知道命名约定,但我只是匆忙创建了一个类以快速测试一些真正的东西,但最终在我将其放入实际项目之前使用该类来测试所有内容。不管怎样,谢谢!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-22
    • 1970-01-01
    • 2013-06-27
    • 2021-11-23
    • 2014-06-28
    • 2018-10-11
    • 1970-01-01
    相关资源
    最近更新 更多