JAVA笔记__窗体类/Panel类/Toolkit类

/**
 * 窗体类
 */
public class Main {
    public static void main(String[] args) {
        MyFrame m1 = new MyFrame();
        
    }
}

class MyFrame extends Frame{
    public MyFrame(){
        this.setTitle("My first software");
        this.setSize(300,200);
        this.setBackground(Color.yellow);
        this.setResizable(false); //不允许调整窗体大小
        this.setLocation(300,300);
        this.setLayout(new FlowLayout()); //把窗体的默认布局设成"流水布局"
        
        //在窗体上添加按钮
        Button b1 = new Button("click me.1");
        this.add(b1);
        this.add(new Button("click me.2"));
        
        this.setVisible(true);
    }
}
/**
 * Panel类(面板类),组件容器
 */
public class Main {
    public static void main(String[] args) {
        MyPanel m1 = new MyPanel();
    }
}

class MyPanel extends Frame{
    public MyPanel(){
        this.setTitle("My first software");
        this.setSize(600,400);
        this.setBackground(Color.yellow);
        this.setResizable(false); //不允许调整窗体大小
        this.setLocation(300,300);
        this.setLayout(new FlowLayout()); //把窗体的默认布局设成"流水布局"
        addPanel();
        this.setVisible(true);
    }
    public void addPanel(){ //Panel的布局默认是"流水布局"
        Panel p1 = new Panel(); //创建面板对象
        p1.setBackground(Color.GREEN);
        p1.add(new Button("click me.1"));
        p1.add(new Button("click me.2"));
        p1.add(new Button("click me.3"));
        this.add(p1); //把面板添加到窗体上
    }
}
/**
 * Toolkit类:用于将各种组件绑定到本地系统的工具包。
 */
public class Main {
    public static void main(String[] args) {
        MyToolkit m1 = new MyToolkit();
    }
}

class MyToolkit extends Frame{
    public MyToolkit(){
        this.setTitle("My first software");
        this.setSize(600,400);
        this.setBackground(Color.yellow);
        
        Toolkit t1 = Toolkit.getDefaultToolkit(); //获取工具对象
        Dimension d1 = t1.getScreenSize(); //获取当前屏幕的尺寸
        double w = d1.getWidth();
        double h = d1.getHeight();
        int x = (int)(w/2);
        int y = (int)(h/2);
        this.setLocation(x-300,y-200);
        
        //设置窗体图标 (新建一个包,把图片放进去)
        URL url = this.getClass().getClassLoader().getResource("pkg1/image/fish.jpg"); //写成pkg1.image.fish.jpg不可以
        Image ima1 = t1.getImage(url);
        this.setIconImage(ima1);
        
        this.setResizable(false); //不允许调整窗体大小
        this.setLayout(new FlowLayout()); //把窗体的默认布局设成"流水布局"
        
        this.setVisible(true);
    }
}
原文地址:https://www.cnblogs.com/fish7/p/4162170.html