JFrame does not add component when JButton is pressed

故事扮演 提交于 2019-12-02 12:15:07
frame.add(new MouseComponent());   

The size of a newly created component is (0, 0) so there is nothing to paint. So you need to invoke the layout manager when you add a component to a visible GUI.

frame.add(new MouseComponent());   
frame.revalidate();
frame.repaint();

Note this will only work if the layout manager allows you to add multiple components to the frame. The default layout manager for a frame is the BorderLayout and only a single components can be added to the CENTER of the BorderLayout.

So maybe you need to add the button using:

frame.add(button, BorderLayout.PAGE_START);

Read the section from the Swing tutorial on How to Use Layout Managers for more information and working examples.

Also, any time you do custom painting you need to override the getPreferredSize() method of the custom component so the layout managers can do their job.

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