Adding a JLabel to a Panel - how to layout the components properly?

倾然丶 夕夏残阳落幕 提交于 2019-12-11 05:53:14

问题


I want to put some words in the frame so I used panel1.add(new JLabel("Hello"));

But there are some buttons which their sizes and positions are customized. I heard that we have to setLayout(null) for the button customizing and this is also making the label not showing up. (Not sure if it is because of this)

What is the solution for this?


回答1:


I'll point you to the Java tutorials for laying out components - they give a good introduction to Swing formatting and layouts.

Rather than calling setLayout(null), you should probably call a specific LayoutManager, such as setLayout(new FlowLayout()); so that Java knows how to display your components. You should call this before you try to add the components to the JPanel. The type of LayoutManager you give to the setLayout() method will instruct Java to draw the GUI in a specific way, such as in a Grid, or just one-after-the-other. The tutorial linked above will explain all this, and has a visual example of the different LayoutManagers




回答2:


Don't use null layout. Define rules how the buttons should be placed and either use some LayoutManager or create your own.



来源:https://stackoverflow.com/questions/13605497/adding-a-jlabel-to-a-panel-how-to-layout-the-components-properly

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