今天我们来做一个这样的程序,主要是掌握一个容器Panel
一个主函数,再新建一个框架类,当然需要继承框架才能成为框架类
public class MyMultiPanel {
public static void main(String args[]) {
}
}
class NewFrame extends Frame {
}
我们的需求是,主函数创建NewFrame对象时,传入参数有:框架标题,软件在显示器的位置,以及大小。
在newFrame里编写代码:
Private Panel p1,p2,p3,p4;
NewFrame(String s,int x,int y,int w,int h){
this.setTitle(s); //设置标题
this.setLayout(null) //清空默认布局(默认东南西北布局)
p1=new Panel();
p1.setBounds(0,0,w/2,h/2); //设置x,y轴的位置,设置宽,高度
p1.setBackground(Color.RED);
this.add(p1)把p1添加入框架内
}
同样的,创建p2.p3,p4…
最后设置框架属性:
this.setBounds(x,y,w,h);
this.setResizeable(false);
this.setVisible(true);
添加事件监听:
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
最后,在主函数里创建这个对象:
public class MyMultiPanel {
public static void main(String args[]) {
Frame fr=new NewFrame("hello",300,200,300,250);
}
}
要注意的是:
panel是一个面板容器,不能单独出现,需要放在Frame里面
这一章主要代码:
MyFrame.setLayout(null); // 清空布局
MyFrame.setBonus(x,y,w,h);//设置位置以及大小
那么它最终的效果就是:
所有代码:
import java.awt.Color;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class MyMultiPanel {
public static void main(String args[]) {
Frame fr=new NewFrame("hello",300,200,300,250);
}
}
class NewFrame extends Frame {
private Panel p1,p2,p3,p4;
NewFrame(String s,int x,int y,int w,int h){
this.setTitle(s);
this.setLayout(null);
p1=new Panel();
p2=new Panel();
p3=new Panel();
p4=new Panel();
p1.setBounds(0, 0, w/2, h/2);
p1.setBackground(Color.RED);
this.add(p1);
p2.setBackground(Color.BLUE);
p2.setBounds(w/2, 0, w/2, h/2);
this.add(p2);
p3.setBounds(0, h/2, w/2, h/2);
p3.setBackground(Color.CYAN);
this.add(p3);
p4.setBounds(w/2, h/2, w/2, h/2);
p4.setBackground(Color.LIGHT_GRAY);
this.add(p4);
this.setBounds(x,y,w,h);
this.setResizable(false);
this.setVisible(true);
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
}