10.GUI编程

AWT(Abstract Window Toolkit) .Swing

1、Frame

Frame f = new Frame("我的第一个程序");

f.setSize(500,300);

f.setLocation(300,300);

f.setBackground(Color.blue);

f.setVisible(true);

f.setResizable(false);

-----

public class  TestMultiFrame

{

public static void main(String[] args) 

{

MyFrame f1 = new MyFrame(100,100,200,200,Color.BLUE);

MyFrame f2 = new MyFrame(300,100,200,200,Color.RED);

MyFrame f3 = new MyFrame(100,300,200,200,Color.GREEN);

MyFrame f4 = new MyFrame(300,300,200,200,Color.MAGENTA);

}

}


class MyFrame extends Frame

{

static int id = 0;

MyFrame(int x,int y,int w,int h,Color color)

{

super("Frame "+(++id));

setBackground(color);

setLayout(null);

setBounds(x,y,w,h);

setVisible(true);

}

}

-----

2、Panel

Frame f = new Frame("我的Panel程序");

Panel p = new Panel(null);

f.setLayout(null);

f.setBounds(300,300,500,500);

p.setBounds(50,50,400,400);

p.setBackground(new Color(243,222,180));

f.add(p);

f.setVisible(true);

3、布局管理器

FlowLayout(Panel默认布局管理器)、BorderLayout、GridLayout、CardLayout、GridBagLayout

FlowLayout:

BorderLayout:(东西南北中)五个区域

不指定加入区域,默认加入Center区域,每个区域只能加入组件,如加入多余,先前加入的会被覆盖;

北南两个区域在垂直方向缩放,东西两个区域在水平方向缩放,中间在两个方向缩放

GridLayout:

f.setLayout(new GridLayout(3,2));//3行2列

f.pack();//让布局自动包着各个组件;


4、监听器

Button b = new Button("确定");

b.addActionListener(new Monitor());

class Monitor implements ActionListener {

public void actionPerformed(ActionEvent e) {

System.out.println("Button pressed"+e.getActionCommand());

}

}

5、paint方法(在需要重绘时自动调用paint)

public void paint(Graphics g){

}

6、鼠标监听事件

this.addMouseListener(new Monitor());

class Monitor extends MouseAdapter()

{public void mousePressed(MouseEvent e)

{MyFrame f = (MyFrame)e.getSource();

f.addPoint(new Point(e.getX(),e.getY()));

f.repaint(); //repaint()-update()-paint()

}//内部类

}

7、windows事件

this.addWindowListener(new WindowAdapter());

this.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

setVisible(false);

System.exit(-1);//-1非正常退出,0正常退出

}

});//匿名类

8、Key事件

this.addKeyListener(new MyKeyMonitor());

class MyKeyMonitor extends KeyAdapter

{

public void keyPressed(KeyEvent e)

{

int keyCode = e.getKeyCode();

if (keyCode ==KeyEvent.VK_UP)

{

System.out.println("key is pressed!");

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值