Java的面板Panel类使用以及布局
Java的面板Panel类使用面板不能单独存在,必须依赖于容器import java.awt.*;import java.awt.event.ContainerListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;public class TestPanel {public static vo
·
Java的面板Panel类使用
面板不能单独存在,必须依赖于容器
import java.awt.*;
import java.awt.event.ContainerListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class TestPanel {
public static void main(String[] args) {
Frame frame = new Frame(); //创建弹窗
Panel panel = new Panel(); //创建面板
// 面板不能单独存在,必须依赖于容器
//设置布局 不设置情况下默认置顶
frame.setLayout(null);
//设置弹窗位置 大小
frame.setBounds(200,200,500,500);
//设置窗口颜色
frame.setBackground(new Color(68, 24, 87));
//设置面板相对位置 大小
panel.setBounds(50,50,400,400);
//设置面板颜色
panel.setBackground(new Color(2,45,99));
//将面板添加到窗口中
frame.add(panel);
//设置可见性
frame.setVisible(true);
//添加监听
//适配器模式
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
FlowLayout类的流式布局设计
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
//流式布局 可以提供靠左、靠右、居中常量布局方式
public class TestFlowLayout {
public static void main(String[] args) {
Frame frame = new Frame();
frame.setBounds(100,100,500,500);
frame.setBackground(new Color(86, 211, 214));
Button button1 = new Button("back");
Button button2 = new Button("return");
Button button3 = new Button("enter");
frame.add(button1);
frame.add(button2);
frame.add(button3);
//流式布局
frame.setLayout(new FlowLayout(FlowLayout.CENTER));
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
窗口布局练习
Frame frame1 = new Frame("Windows Layout");
frame1.setSize(400,500);
frame1.setLocation(100,100);
frame1.setBackground(new Color(229, 254, 251));
frame1.setVisible(true);
frame1.setLayout(new GridLayout(2,1));
//上面部分
Panel panel1 = new Panel(new BorderLayout());
Panel panel2 = new Panel(new GridLayout(2,1));
Panel panel3 = new Panel(new BorderLayout());
Panel panel4 = new Panel(new GridLayout(2,2));
panel1.add(panel2,BorderLayout.CENTER);
panel2.add(new Button("button1"));
panel2.add(new Button("button2"));
panel1.add(new Button("button3"),BorderLayout.WEST);
panel1.add(new Button("button4"),BorderLayout.EAST);
// 下面部分
panel3.add(panel4,BorderLayout.CENTER);
for (int i=6;i<10;i++){
panel4.add(new Button("Button"+i));
}
panel3.add(new Button("Button4"),BorderLayout.WEST);
panel3.add(new Button("Button5"),BorderLayout.EAST);
frame1.add(panel1);
frame1.add(panel3);
效果图如下
更多推荐
已为社区贡献1条内容
所有评论(0)