java GUI设计和布局(一)

2014-11-24 07:56:09 · 作者: · 浏览: 0
GUI(Graphical User Interfaces):由各种图形对象组成的用户界面,在这种用户界面下,用户的命令和对程序的控制是通过“选择”各种图形对象来实现的。
  • 抽象窗口工具包:
    • java.awt:提供基本GUI组件,视觉控制,绘图工具等
    • java.awt.event:事件处理
  • 组件和容器:
    • 组件:基本组成元素,凡是能够以图形化方式显示在屏幕上并能与用户交互的对象均为组件。
Component:抽象类,定义了GUI组件的基本特性和功能
Component常规属性和方法:
属性名 含义 设置属性的方法 获取属性的方法
visible 可见性 void setVisible(boolean) boolean getVisible()
background 背景色 void setBackground(Color) Color getBackground()
bounds 边界 void setBounds(Rectangle)
void setBounds((int,int,int,int)【x,y,w,h】
Rectangle getBounds()
size 尺寸 void setSize(Dimension)【w,h】 Dimension getSize()
location 位置 void setLocation(Point)
void setLocation(int,int)【x,y】
Point getLocation()
font 字体 void setFont(Font) Font getFont()
layoutMgr 布局 void setLayout(LayoutManager) LayoutManager getLayout()
foreground 前景色 void setForeground(Color) Color getForeground()
dropTarget 拖放目标 void setDropTarget(DropTarget) DropTarget getDropTarget()
enabled 使能 void setEnabled(boolean) boolean getEnabled()
cursor 光标 void setCursor(Cursor) Cursor getCursor()
locale 地区 void setLocale(Locale) Locale getLocale()
name 组件名称 void setName(String) String getName()
  • 容器(Container):能容纳和排列组件的组件
  • 书写顺序:Frame,组件,添加,属性


顶层容器:Frame;

[java]
import java.awt.*;
public class FirstFrame {
public static void main(String[] args) {
Frame f = new Frame("第一个图形用户界面");
Label l = new Label("这是我的第一个图形用户界面");
Button b = new Button("按钮");
f.setBackground(Color.yellow);
l.setBackground(Color.pink);
f.setBounds(100, 200, 300, 200);
//f.setSize(300,200);
//f.setLocation(100,200);
f.add(l);
f.add(b);
f.setVisible(true);
f.setLayout(new FlowLayout());
}
}

第二种写法(推荐)
[java]
import java.awt.*;
public class FirstFrame2 extends Frame{
Label l;
Button b;
public FirstFrame2(){
super("第一个图形用户界面");
l = new Label("这是我的第一个图形用户界面");
b = new Button("按钮");
setBackground(Color.yellow);
l.setBackground(Color.pink);
setBounds(100, 200, 300, 200);
//f.setSize(300,200);
//f.setLocation(100,200);
add(l);
add(b);
setVisible(true);
setLayout(new FlowLayout());
}
public static void main(String[] args) {
new FirstFrame2();
}
}

\

中间容器:Panel;
[java]
import java.awt.*;
public class PaneDemo {
public static void main(String[] args) {
Frame f = new Frame("容器组件Pane的使用");
Panel p = new Panel();
Button b = new Button("确定");

p.setBackground(Color.pink);
p.setBounds(50,50,80,60);

f.setLayout(null);
f.add(p);
p.add(b);
f.setBounds(200,200,200,160);
f.setVisible(true);
}
}

\

布局管理器


  • 容器对象.setLayout(布局管理器对象)
  • 布局管理器 容器对象.getLayout()
  • FlowLayout:流式布局,是Panel(及其子类)默认布局管理器
    • 布局效果:组件在容器中按照加入次序逐行定位,行内从左到右,一行排满后换行。组件按原始大小进行显示
    • 构造方法
      • public FlowLayout():默认居中对齐
      • public FlowLayout(int align):显示设定组件对其方式
      • public FlowLayout(int align,int hgap,int vgap):设置水平和垂直间距
        • FlowLayout.LEFT左对齐
        • FlowLayout.RIGHT 右对齐
        • FlowLayout.CENTER居中



import java.awt.*;
public clas