GUI和CLI:
GUI:(Graphical User Interface)图形用户接口:用图形的方式显示计算机的操作界面。
CLI:(Command Line User Interface)命令行用户接口:常见的Dos命令行操作。
awt和swing:
awt:(Abstract Windows ToolKit)抽象窗口工具包,需要调用本地系统方法实现功能,属重量级控件。
swing:在awt的基础上建立的一套图形界面系统,属于Javax扩展包下。其中提供了更多的组件。而且完全由Java实现增强了移植性,属轻量级控件。
基本的GUI使用:(通过下面实例讲解):
public class Demo {
public static void main(String[] args) {
// 创建窗口对象
Frame f = new Frame("这是一个窗口");
// 设置窗口的位置大小
f.setBounds(400, 200, 400, 300);
// 设置窗口布局为流体布局
f.setLayout(new FlowLayout());
// 创建Button按钮
Button b = new Button();
Button b2 = new Button("Touch me");
b.setLabel("Click me");
// 将按钮添加到窗口中
f.add(b);
f.add(b2);
// 创建菜单栏
MenuBar mb = new MenuBar();
// 创建菜单
Menu m = new Menu("File");
// 创建菜单项
MenuItem mi = new MenuItem("quit");
// 菜单项到菜单
m.add(mi);
// 添加菜单到菜单栏
mb.add(m);
// 添加菜单栏到窗口中
f.setMenuBar(mb);
// 给窗口关闭事件添加监听
f.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
// 给按钮b添加监听事件
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("按钮点击了!");
}
});
// 给按钮b2添加鼠标事件
b2.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
f.setBackground(Color.red);
}
@Override
public void mouseExited(MouseEvent e) {
f.setBackground(Color.WHITE);
}
});
// 给菜单项设置监听
mi.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
// 设置窗口可见
f.setVisible(true);
}
}
上述代码中,实现了在一个窗口中布局了两个button按钮,一个演示button按钮的点击事件,一个演示了鼠标箭头的进入和淡出效果。另外该代码演示了一级菜单的实现(实际上会了一级二级菜单也就会了,一级菜单的菜单项可以是菜单,也可以是菜单项),给菜单项设置了监听事件,点击菜单项既可以退出界面。这是GUI的简单使用。这里面有一点是需要特别注意的:就是适配器模式的体现,在监听事件中(包括鼠标的进入移除),代码如下:
// 给按钮b2添加鼠标事件
b2.addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
f.setBackground(Color.red);
}
@Override
public void mouseExited(MouseEvent e) {
f.setBackground(Color.WHITE);
}
});
b2.addMouseListener(new MouseListener() {
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
f.setBackground(Color.white);
}
@Override
public void mouseEntered(MouseEvent e) {
f.setBackground(Color.red);
}
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
});
实际上上诉两段代码的效果是相同的,同样可以在鼠标进入和移出时产生效果,但是代码的复杂度,是可以看的见的,适配器的使用,避免了我们对一个接口里面所有方法的实现,我们只需使用一个继承过某一接口的实现类的类就能完成。然后在该类中重写父类方法就可以。就像是第一段代码中的MouseAdapter是第二段代码中的MouseListener的子类,MouseListener实现了接口中的所有方法,MouseAdapter继承了MouseListener,所以,当MouseAdapter需要使用到哪个方法,只需重写父类方法就行。具体的适配器模式的讲解查看Java基础总结之设计模式(四)。
关于GUI图形界面开发,实际上后期会使用NetBeans等开发工具开发,其相对于eclipse有更友好的图形界面展示。
注:以上文章仅是个人学习过程总结,若有不当之处,望不吝赐教。