Search code examples
javaconstructorjframeprogram-entry-point

Creating JFrame in an instance object


I'm trying to display a countdown and I'm searching how to do it and trying codes out but that's not what I'm here to ask in this question, although I'd be happy if you helped me in that area too.

This seems a bit elementary but I can't seem to get the JFrame showing. I predicted that if I create an instance of the testmain and there's a creation of a JFrame in the constructor, it'd show the JFrame.

I even tried getting an input from the keyboard so that it'll stop. But nothing happens and the program ends right away. It says build successful.

What am I missing?

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();


    }
}

Solution

  • You've got a pseudo-constructor which is not being called. Constructors have no return type, not void, not anything.

    Change

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

    to

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

    As an aside, you will want to learn and use Java naming conventions. Variable names should all begin with a lower letter while class names with an upper case letter. Learning this and following this will allow us to better understand your code, and would allow you to better understand the code of others.

    So the class should actually be called TestMain:

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