按钮Button,面板Panel的综合使用
在此感谢Java狂神说!!!
一、做一个界面 类似下图
颜色没有要求,我是随便用的
//这是我自己的包
package GUI;
//导入必要的包
import java.awt.*;
import java.awt.event.*;
public class TestDemo {
public static void main(String[] args) {
//新建一个窗口
Frame frame = new Frame();
//设置为网格布局
frame.setLayout(new GridLayout(2,1));
//新建10个按钮
Button b1 = new Button("b1");
Button b2 = new Button("b2");
Button b3 = new Button("b3");
Button b4 = new Button("b4");
Button b5 = new Button("b5");
Button b6 = new Button("b6");
Button b7 = new Button("b7");
Button b8 = new Button("b8");
Button b9 = new Button("b9");
Button b10 = new Button("b10");
//设置他们的颜色,个人爱好而已
b1.setBackground(Color.cyan);
b2.setBackground(Color.red);
b3.setBackground(Color.green);
b4.setBackground(Color.ORANGE);
b5.setBackground(Color.cyan);
b6.setBackground(Color.red);
b7.setBackground(Color.blue);
b8.setBackground(Color.orange);
b9.setBackground(Color.red);
b10.setBackground(Color.cyan);
//我们先弄好四个面板 并设置布局
Panel p1 = new Panel(new BorderLayout());
Panel p2 = new Panel(new GridLayout(2,1));
Panel p3 = new Panel(new BorderLayout());
Panel p4 = new Panel(new GridLayout(2,2));
//将面板p1,p3添加到frame上
frame.add(p1);
frame.add(p3);
//b1放到西边 b4放到东边 p2放在中间
p1.add(b1,BorderLayout.WEST);
p1.add(b4,BorderLayout.EAST);
p1.add(p2,BorderLayout.CENTER);
//将b2,b3放到p2上
p2.add(b2);
p2.add(b3);
//把b5放在p3的西边 b10放在p3的东边 p4放中间
p3.add(b5,BorderLayout.WEST);
p3.add(b10,BorderLayout.EAST);
p3.add(p4,BorderLayout.CENTER);
//将这些按钮添加到p4上
p4.add(b6);
p4.add(b7);
p4.add(b8);
p4.add(b9);
frame.setBounds(400, 400, 500, 500);
frame.setVisible(true);
}
}
总结
这是按钮Button和面板Panel的综合运用,是对前几次学习的一个小测验,检验自己的学习情况。