Java自学总结之七图形用户接口

来源:互联网 发布:同方云计算战略发布会 编辑:程序博客网 时间:2024/06/10 16:34

图形用户接口也就是一个人机交互的界面,下面先介绍一下界面的组成:

1. JFrame框架,这个是屏幕上的Windows的对象,在创建界面时,这个是首要创建的,如果把设计一个界面比喻为画水彩画,那么它就相当于一个支架,在画画前先安好支架如右图

2. JPanel面板,组件是不能直接加载JFrame上的,必须先得到面板,然后在添加其他组件,面板就和上图的画板一个道理

3. widget组件,就相当于在画板上画的图形,JButton、JCHeckBox等

JFrame frame;JButton button;frame = new JFrame();button = new JButton("click me!");frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//Windows关闭时该程序自动关闭frame.getContentPane().add(button);frame.setSize(300, 300);frame.setVisible(true);

上面是一个设计了一个单纯的界面,那么下面将介绍如何设计一个有功能的界面  ,这里以按钮组件为例,在按下按钮之前显示"click me",在按下按钮之后显示"I have been clicked",那么这里就有一个问题就是程序如何知道按钮被按下,如何知道要改变按钮上的文字:

1. 事件来源:JButton ,JCheckBox等组件接收注册,并在取得用户的操作,并调用相应的接口方法

2. 事件对象:MouseEvent, KeyEvent等,在调用接口的方法时,此会作为参数被调用

3.监听接口:MouseListener,KeyListener等接口,这里,我们一般扮演监听接口的任务,也就是向按钮等组件注册并实现接口的方法

当我们对事件来源做出相关的动作时会产生事件对象。

public class SimpleGuil implements ActionListener{JFrame frame;JButton button;public static void main(String[] args) {// TODO Auto-generated method stubSimpleGuil gui = new SimpleGuil();gui.go();}public void go(){frame = new JFrame();button = new JButton("click me!");button.addActionListener(this);//注册,并得到事件对象frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.getContentPane().add(button);frame.setSize(300, 300);frame.setVisible(true);}public void actionPerformed(ActionEvent event){//<span style="font-size:24px;color:#ff0000;">这里就是接口的实现方法,当用户做出相应的操作时,编辑器就会自动调用这个函数,而不用我们手动调用</span>button.setText("I have been clicked!");}}
这里我再写一下关于面板的问题,面板类JPanel的方法是PaintComponent()函数,一般情况下,我们是不会自己调用该函数,而是面板所处的Frame显示时,该函数就会被调用

public class SimpleAnimation {int x = 70;int y = 70;public static void main(String[] args) {// TODO Auto-generated method stubSimpleAnimation gui = new SimpleAnimation();gui.go();}public void go(){JFrame frame = new JFrame();frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);MyDrawPanel1 drawPanel = new MyDrawPanel1();frame.getContentPane().add(drawPanel);frame.setSize(300, 300);frame.setVisible(true);for(int i = 0;i<130;i++){x++;y++;drawPanel.repaint();try{Thread.sleep(50);}catch(Exception ex){}}}class MyDrawPanel1 extends JPanel {<span style="white-space:pre"></span><span style="font-size:24px;color:#ff6666;">//这边引入了一个内部类的概念</span>public void paintComponent(Graphics g){g.setColor(Color.white);g.fillRect(0, 0, this.getWidth(), this.getHeight());g.setColor(Color.green);g.fillOval(x, y, 40, 40);}}}




0 0
原创粉丝点击