简体   繁体   中英

I get a blank JFrame when i call my the JFrame subclass from the main method. How can I fix?

This is my frame class. I am trying to call this class from my main method but i only get a blank frame, instead of displaying my 400x400 frame, panel, and button.

public class Frame extends JFrame {


    public void getFrame() {

        JFrame frame = new JFrame();
        JPanel panel= new JPanel();
        JButton button= new JButton();
        button= new JButton("Click");
        panel.add(button);
        frame.setSize(400, 400);
        frame.add(panel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

}

This is my main method

public class Test extends JFrame  {

    public static void main(String[] args) {

        Frame f= new Frame();
        f.setVisible(true);

    }
}

Your code has two JFrames, not one. One is the Frame class itself which extends JFrame, and which your displaying. But it holds no components, and so you are seeing nothing but a blank window, as expected.

The other JFrame is created in the getFrame() method, a method that you never call in your main method.

Suggestion: do not have Frame extend JFrame, but instead create your Frame instance in the main method and then call the getFrame() method on it to display the JFrame that has components within it.

You're instantiating an instance of your Frame class, which calls the default constructor Frame(), which has nothing in it so your getFrame() method never runs. The reason you're seeing a blank JFrame is that your Frame class extends JFrame so it is infact a JFrame itself, which you've set visible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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