一、面板
package com.kuang.frist; import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; //Panel 可以看成是一个空间,不可以单独存在 public class TestPanel { public static void main(String[] args) { Frame frame = new Frame(); //布局的概念 Panel panel = new Panel(); //设置布局 frame.setLayout(null); //坐标 frame.setBounds(300, 300, 300, 300); frame.setBackground(Color.blue); //panel设置坐标,相当于frame panel.setBounds(200, 200, 200, 200); panel.setBackground(Color.green); //frame.add(panel) frame.add(panel); frame.setVisible(true); //监听事件,关闭窗口 frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); } }
2、布局管理器
流式布局
package com.kuang.frist; import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class testflow { public static void main(String[] args) { Frame frame=new Frame(); //组件-按钮 Button button1=new Button("button1"); Button button2=new Button("button2"); Button button3=new Button("button3"); //设置为流式布局,默认居中 //frame.setLayout(new FlowLayout()); //设置居左 frame.setLayout(new FlowLayout(FlowLayout.LEFT)); frame.setSize(300,300); //添加按钮 frame.add(button1); frame.add(button2); frame.add(button3); //设置为可见 frame.setVisible(true); //监听关闭 frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); } }
东西南北中
package com.kuang.frist; import java.awt.*; public class testBorderLayout { public static void main(String[] args) { Frame frame=new Frame("testborderLayout"); Button east=new Button("East"); Button west=new Button("west"); Button south=new Button("South"); Button nouth=new Button("Nouth"); Button Center=new Button("Center"); frame.add(east,BorderLayout.EAST); frame.add(west,BorderLayout.WEST); frame.add(south,BorderLayout.SOUTH); frame.add(nouth,BorderLayout.NORTH); frame.add(Center,BorderLayout.CENTER); frame.setSize(300,300); frame.setVisible(true); } }
表格布局
package com.kuang.frist; import java.awt.*; public class testGrid { public static void main(String[] args) { Frame frame=new Frame("testGrid"); Button east=new Button("East"); Button west=new Button("west"); Button south=new Button("South"); Button nouth=new Button("Nouth"); Button Center=new Button("Center"); frame.setLayout(new GridLayout(2,3)); frame.add(east); frame.add(west); frame.add(south); frame.add(nouth); frame.add(Center); frame.pack(); frame.setVisible(true); } }