JFrame not presenting any Components

我的未来我决定 提交于 2019-11-26 22:26:49

问题


I am using the following code to create a very simple JFrame, but for some reason it doesn't show any components, just a blank frame. Why is this happening? I created frames a bunch of times and I just can't figure out what is wrong. The code is:

Main(){
    JFrame frame = new JFrame("Colorizer | By: NonameSL");
    frame.setSize(400,200);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel = new JPanel();
    frame.setContentPane(panel);
    textField=new JTextField("Enter your name!");
    textField.setBounds(0,0,40,200);
    textField.setVisible(true);
    frame.getContentPane().add(textField);
    button=new JButton("Go!");
    button.setBounds(0, 200, 40, 200);
    button.setVisible(true);
    frame.getContentPane().add(button);
    rectangle=new RecShape(Color.WHITE);
    rectangle.setBounds(0,40,400,160);
    rectangle.setVisible(false);
    frame.getContentPane().add(rectangle);
    Main.frame=frame;
    registerButton();
}

The RecShape class is a class I created to simply create a rectangle shape on screen. What is wrong?


回答1:


Put frame.setVisible(true); after adding components to JFrame, and it will show all the added components. Moreover, you should use specific layout rather than setting bounds for components. You can use a Layout Manager.




回答2:


You have to move frame.setVisible(true); to the end of the method; the visibility must be set to true after you have added the components.

Alternatively, you can add the following to the end of your method:

frame.revalidate();
frame.repaint();

to revalidate and repaint the frame with the newly added components although I recommend the former method.




回答3:


you can add this at the end;

frame.pack()



回答4:


Better your first add components to your variable "panel" and add then your finished panel to the .getContentPane().add().

And the most important issue is that you better call frame.setVisible(true); at the end of your method.



来源:https://stackoverflow.com/questions/24448031/jframe-not-presenting-any-components

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!