问题
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 LayoutManager
s
回答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