如下:
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;public class test3 extends JFrame {
/***构造函数***/
test3(String title) {
super(title);
set();
setWindow();
}

JPanel jp1 = new JPanel();
JPanel jp2 = new JPanel();

JLabel jl1 = new JLabel("JP1");
JLabel jl2 = new JLabel("JP2");

//设置
private void set() {
this.setLayout(new BoxLayout(this.getContentPane(), BoxLayout.Y_AXIS));
this.add(jp1);
this.add(jp2);

jp1.setBackground(Color.red);
jp2.setBackground(Color.GREEN);

jp1.add(jl1);
jp2.add(jl2);

jp1.setPreferredSize(new Dimension(this.getWidth(),50));
jp2.setPreferredSize(new Dimension(this.getWidth(),50));
}

/********* 设置窗口 **********/
private void setWindow() {
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // 设置Window的布局管理器为BoxLayout
this.setSize(200,200);
this.setLocationRelativeTo(this);
this.setVisible(true);
}

/***主函数***/
public static void main(String[] args) {
new test3("测试");
}
}有没有办法在不删除JPanel的情况下,跟下面的实现是一样的效果啊
(就是让两个装着Label的Panel只占上面的一点空间):import java.awt.Color;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;public class test3 extends JFrame {
/***构造函数***/
test3(String title) {
super(title);
set();
setWindow();
}

JLabel jl1 = new JLabel("JP1");
JLabel jl2 = new JLabel("JP2");

//设置
private void set() {
jl1.setBackground(Color.red);
jl2.setBackground(Color.GREEN);
this.setLayout(new BoxLayout(this.getContentPane(), BoxLayout.Y_AXIS));
this.add(jl1);
this.add(jl2);
}

/********* 设置窗口 **********/
private void setWindow() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 设置Window的布局管理器为BoxLayout
this.setSize(200,200);
this.setLocationRelativeTo(this);
this.setVisible(true);
}

/***主函数***/
public static void main(String[] args) {
new test3("测试");
}
}
//不知道怎么回事,背景也不管用啦!
//高手帮帮忙,多谢啦!