设置Jpanel的布局管理器为gridLayout(1,1);
例如:
import java.awt.Color;
import java.awt.GridLayout;
import javax.swing.*;
public class TestJpanel extends JFrame {
public static void main(String [] arge){
new TestJpanel();
}
public TestJpanel(){
setBounds(10,10,400,400);
JPanel panel = new JPanel();
panel.setBackground(Color.RED);
panel.setLayout(new GridLayout(1, 1));
JButton button = new JButton();
panel.add(button);
this.add(panel);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
}
用一个布局管理器就好了,比如可以用BorderLayout,然后把button添加到BorderLayout.CENTER