posts - 37, comments - 8, trackbacks - 0, articles - 0

java基础:GUI基础编程(下)

Posted on 2008-08-10 07:06 梦与桥 阅读(669) 评论(0)  编辑  收藏 所属分类: java基础

10、布局管理编程演示:
        §流布局管理器(FlowLayout):

import javax.swing.*;
import java.awt.*;
public class FlowLayoutDemo extends JFrame{
 JPanel p;
 JLabel lblUser;
 JTextField txtUser;
 JButton btnCheck,btnExit;
 public FlowLayoutDemo(){
  super("流布局演示");
  setSize(250,150);
  p=new JPanel();
  p.setLayout(new FlowLayout());
  getContentPane().add(p);
  lblUser=new JLabel("用户名:");
  txtUser=new JTextField(16);
  btnCheck=new JButton("检测用户名");
  btnExit=new JButton("退出");
  p.add(lblUser);
  p.add(txtUser);
  p.add(btnCheck);
  p.add(btnExit);
  setVisible(true);
  
 }
 public static void main(String[] args) {
  new FlowLayoutDemo();
 }
}
        §边界布局管理器(BorderLayout):
import javax.swing.*;
import java.awt.*;
public class BorderLayoutDemo extends JFrame{
    JPanel p;
    JButton b1,b2,b3,b4;
    JTextArea ta;
    
public BorderLayoutDemo(){
        
super("边界布局演示");
        setSize(
250,150);
        p
=new JPanel();
        p.setLayout(
new BorderLayout());
        getContentPane().add(p);
        b1
=new JButton("East");
        b2
=new JButton("West");
        b3
=new JButton("North");
        b4
=new JButton("South");
        ta
=new JTextArea("Center");
        p.add(b1,
"East");
        p.add(b2,BorderLayout.WEST);
        p.add(
"North",b3);
        p.add(
"South",b4);
        p.add(ta,
"Center");
        setVisible(
true);
        
    }

    
public static void main(String[] args) {
        
new BorderLayoutDemo();
    }

}
        §网格布局管理器(GridLayout):
import javax.swing.*;
import java.awt.*;
public class GridLayoutDemo extends JFrame{
    JPanel p;
    JButton b1,b2,b3,b4;
    JTextArea ta;
    JTextField tf;
    
public GridLayoutDemo(){
        
super("网格布局演示");
        setSize(
250,150);
        p
=new JPanel();
        p.setLayout(
new GridLayout(3,2));
        getContentPane().add(p);
        b1
=new JButton("one");
        b2
=new JButton("two");
        b3
=new JButton("three");
        b4
=new JButton("four");
        ta
=new JTextArea("JTextArea");
        tf
=new JTextField("JTextField");
        p.add(b1);
        p.add(b2);
        p.add(b3);
        p.add(b4);
        p.add(ta);
        p.add(tf);
        setVisible(
true);
        
    }

    
public static void main(String[] args) {
        
new GridLayoutDemo();
    }

}
        §网格袋布局管理器(GridBagLayout):
import javax.swing.*;
import java.awt.*;
public class GridBagLayoutDemo extends JFrame{
    JPanel p;
    JTextArea ta;
    JTextField tf;
    JButton b1,b2;
    JLabel l1,l2;
    GridBagConstraints gbc;
    GridBagLayout gbl;
    
private void addComponent(Component c,GridBagLayout g
            ,GridBagConstraints gc,
int column ,int row,int width,int height)
    
{
        gc.gridx
=column;//指定包含组件的显示区域开始边的单元格
        gc.gridy=row;//指定位于组件显示区域的顶部的单元格
        gc.gridwidth=width;//指定在组件显示区域的一行中的单元格数
        gc.gridheight=height;//指定在组件显示区域的一列中的单元格数
        g.setConstraints(c, gc);//设置此布局中指定组件的约束条件
        p.add(c);
    }

    
public GridBagLayoutDemo(){
        
super("网格袋布局演示");
        setSize(
250,150);
        p
=new JPanel();
        gbc
=new GridBagConstraints();
        gbl
=new GridBagLayout();
        p.setLayout(gbl);
        getContentPane().add(p);
        ta
=new JTextArea("我是文本域",5,10);
        b1
=new JButton("我是按钮b1.");
        b2
=new JButton("我是按钮b2");
        tf
=new JTextField("我是文本框");
        l1
=new JLabel("我是一个标签");
        l2
=new JLabel("我是另一个标签");
        
//布局JTextArea
        gbc.weightx=0;//指定如何分布额外的水平空间
        gbc.weighty=0;//指定如何分布额外的垂直空间
        
//BOTH:在水平方向和垂直方向上同时调整组件大小
        
//fill:当组件的显示区域大于它所请求的显示区域的大小时使用此字段
        gbc.fill=GridBagConstraints.BOTH;
        addComponent(ta,gbl,gbc,
0,0,1,3);
        
//布局按钮b1
        gbc.fill=GridBagConstraints.HORIZONTAL;
        addComponent(b1,gbl,gbc,
1,0,2,1);
        
//布局按钮b2
        gbc.fill=GridBagConstraints.HORIZONTAL;
        addComponent(b2,gbl,gbc,
1,1,2,1);
        setVisible(
true);
        
//布局文本框tf
        gbc.fill=GridBagConstraints.BOTH;
        addComponent(tf,gbl,gbc,
1,2,2,1);
        setVisible(
true);
        
//布局标签l1
        gbc.fill=GridBagConstraints.BOTH;
        addComponent(l1,gbl,gbc,
0,3,2,1);
        setVisible(
true);
        
//布局标签l2
        gbc.fill=GridBagConstraints.BOTH;
        addComponent(l2,gbl,gbc,
1,3,2,1);
        setVisible(
true);
        
    }

    
public static void main(String[] args) {
        
new GridBagLayoutDemo();
    }

}

        §卡片布局管理器(CardLayout):
import javax.swing.*;
import java.awt.*;
public class CardLayoutDemo extends JFrame{
    CardLayout cl;
    JPanel p;
    JButton b1,b2,b3,b4;
    
public CardLayoutDemo(){
        
super("卡片布局演示");
        setSize(
150,250);
        cl
=new CardLayout();
        p
=new JPanel();
        p.setLayout(cl);
        getContentPane().add(p);
        b1
=new JButton("我是第一张卡片");
        b2
=new JButton("我是第二张卡片");
        b3
=new JButton("我是第三张卡片");
        b4
=new JButton("我是第四张卡片");
        p.add(
"b1",b1);
        p.add(
"b2",b2);
        p.add(
"b3",b3);
        p.add(
"b4",b4);
        setVisible(
true);
        
while(true){
            
try {
                Thread.sleep(
2000);
            }
 catch (InterruptedException e) {
                e.printStackTrace();
            }

            cl.next(p);
        }

        
    }

    
public static void main(String[] args) {
        
new CardLayoutDemo();
    }

}
        §盒式布局管理器(BoxLayout):
import java.awt.FlowLayout;
import java.awt.TextField;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.Box;
import javax.swing.JFrame;

public class BoxLayoutDemo
{
    
public static void main(String args[])
    
{
        JFrame frame
=new JFrame("用户登录");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(
300,200);
        TextField password
=new TextField(15);
        password.setEchoChar(
'*');

        Box left,right,top,bottom,base,basebox;

        top
=Box.createHorizontalBox();
        top.add(
new JLabel("用户登录"),JLabel.CENTER);

        left
=Box.createVerticalBox();
        left.add(
new JLabel("用户名:"));
        left.add(Box.createVerticalStrut(
8));
        left.add(
new JLabel("密码:"));

        right
=Box.createVerticalBox();
        right.add(
new TextField(10));
        right.add(Box.createVerticalStrut(
8));
        right.add(password);

        bottom
=Box.createHorizontalBox();
        bottom.add(
new JButton("登录"));
        bottom.add(Box.createVerticalStrut(
10));
        bottom.add(
new JButton("重置"));

        basebox
=Box.createHorizontalBox();
        basebox.add(left);
        basebox.add(Box.createHorizontalStrut(
10));
        basebox.add(right);

        base
=Box.createVerticalBox();
        base.add(top);
        base.add(Box.createVerticalStrut(
10));
        base.add(basebox);
        base.add(Box.createVerticalStrut(
10));
        base.add(bottom);

        frame.setLayout(
new FlowLayout());
        frame.add(base);
        frame.setVisible(
true);
    }

}
        §空布局管理器(自定义布局):
import javax.swing.*;
import java.awt.*;
public class NullLayoutDemo extends JFrame{
    JPanel p;
    JButton b1,b2,b3,b4;
    
public NullLayoutDemo(){
        
super("自定义布局演示");
        setSize(
250,150);
        p
=new JPanel();
        p.setLayout(
null);
        getContentPane().add(p);
        b1
=new JButton("one");
        b1.setBounds(
10,20,100,30);//设置的依次是x、y坐标,长与宽
        b2=new JButton("two");
        b2.setBounds(
120,20,100,30);
        b3
=new JButton("three");
        b3.setBounds(
10,70,100,30);
        b4
=new JButton("four");
        b4.setBounds(
120,70,100,30);
        p.add(b1);
        p.add(b2);
        p.add(b3);
        p.add(b4);
        setVisible(
true);
        
    }

    
public static void main(String[] args) {
        
new NullLayoutDemo();
    }

}
11、事件处理
(1)Java事件模型:事件模型的3个组件:事件、事件源和事件监听器
(2)事件处理的工作原理:
                §事件源是一个能够注册监听器,且可为监听器发送事件对象的对象
                §一个监听器对象是一个实现了专门的监听器接口的类实例
                §当事件发生时,事件源将事件对象发送给事件源所注册的监听器(一个或多个)
                §监听器对象使用事件对象的信息来确定做出的反应
(3)处理事件的一般步骤:
                §定义要接收某事件的类并实现相应的监听器接口
                §在事件源中注册类
                §接收对应的事件对象,并通过监听器接口中的方法进行处理
(4)事件类型:AWT事件分为两大类,低级事件和高级事件,前者是基于组件和容器的事件,后者是基于语义的事件。
                §低级事件:
                    ComponentEvent——组件事件,组件尺寸的变化和移动,是所有低层事件的基类。
                    ContainerEvent——容器事件,组件增加和删除。
                    WindowEvent——窗口事件,窗口被激活、关闭或者还原。
                    FucousEvent——焦点事件,组件获得焦点或者失去焦点。
                    KeyEvent——键盘事件,键盘的按下或释放。
                    MouseEvent——鼠标事件,鼠标键被按下、释放、鼠标移动或者托动。
                    MouseWheelEvent——鼠标滚轮被滚动。
                §高级事件:
                    ActionEvent——动作事件,按钮单击、TextField中按下Enter键、菜单选择、选择列表框等。
                    AdjustmentEvent——调节事件,在滚动条上移动滑块和调节数值。
                    ItemEvent——选择列表框中的项目。
                    TextEvent——文本事件,文本对象发生改变。
(5)动作事件示例程序:
import javax.swing.*;
import java.awt.event.*;
public class ActionEventDemo extends JFrame implements ActionListener{
    
//声明组件
    JLabel lblTitle,lblUser,lblPass;
    JTextField txtUser;
    JPasswordField pwdPass;
    JButton btnLogin,btnExit;
    JPanel pnlMain;
    
//构造方法
    public ActionEventDemo(){
        
super("用户登录");
        pnlMain
=new JPanel();
        
this.getContentPane().add(pnlMain);
        
//实例化组件
        String address="G:\\00\\images\\";
        lblTitle
=new JLabel(new ImageIcon(address+"welcome.gif"));
        lblUser
=new JLabel("用户名:");
        txtUser
=new JTextField(12);
        lblPass
=new JLabel("密码:");
        pwdPass
=new JPasswordField(12);
        
//"登录"按钮
        Icon imgLogin=new ImageIcon(address+"login.gif");
        btnLogin
=new JButton("登录(L)",imgLogin);
        btnLogin.setMnemonic(
'L');//键盘助记符
        btnLogin.setToolTipText("点击登录");//工具提示文字
        btnLogin.addActionListener(this);
        
//"退出"按钮
        Icon imgExit=new ImageIcon(address+"exit.gif");
        btnExit
=new JButton("退出(x)",imgExit);
        btnLogin.setMnemonic(
'X');
        btnExit.setToolTipText(
"退出登录");
        btnExit.addActionListener(
this);
        
//添加组件到面板
        pnlMain.add(lblTitle);
        pnlMain.add(lblUser);
        pnlMain.add(txtUser);
        pnlMain.add(lblPass);
        pnlMain.add(pwdPass);
        pnlMain.add(btnLogin);
        pnlMain.add(btnExit);
        
//设置窗口属性
        setSize(450,400);
        setResizable(
false);
        setVisible(
true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    
public void actionPerformed(ActionEvent ae){
        
if(ae.getSource()==btnLogin){
            
if(txtUser.getText().equals("admin")&&pwdPass.getText().equals("admin"))
                JOptionPane.showMessageDialog(
null,"欢迎登录");
            
else JOptionPane.showMessageDialog(null,"用户名或密码错误");            
        }

        
if(ae.getSource()==btnExit){
            System.exit(
0);
        }

    }

    
public static void main(String[] args) {
        
new ActionEventDemo();
    }


}

(5)键盘事件示例程序:

import java.awt.*;
import java.awt.geom.*;
import java.util.*;
import java.awt.event.*;
import javax.swing.*;

public class KeyEventDemo {
 public static void main(String args[]) {
  SketchFrame frame = new SketchFrame();
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.setVisible(true);
 }
}

class SketchFrame extends JFrame {
 public SketchFrame() {
  setTitle("键盘事件");
  setSize(300, 200);
  final SketchPanel panel = new SketchPanel();
  final Container contentPane = getContentPane();
  contentPane.add(panel);
 }
}

class SketchPanel extends JPanel {
 private Point2D last;
 private ArrayList lines;
 private static final int INCREMENT = 10;

 public SketchPanel() {
  last = new Point2D.Double(100, 100);// 设置开始点坐标
  lines = new ArrayList();
  KeyHandler listener = new KeyHandler();
  addKeyListener(listener);// 注册事件监听器
  setFocusable(true);
 }

 // 添加坐标
 public void add(int dx, int dy) {
  Point2D end = new Point2D.Double(last.getX()
    + dx, last.getY() + dy);// 得到终点坐标
  Line2D line = new Line2D.Double(last, end);
  lines.add(line);
  repaint();
  last = end;
 }

 // 画图方法
 public void paintComponent(Graphics g){
  super.paintComponent(g);
  Graphics2D g2=(Graphics2D)g;
  for(int i=0;i<lines.size();i++){
   g2.draw((Line2D)lines.get(i));
  }
 }

 private class KeyHandler implements KeyListener {
  // 按键被按下事件
  public void keyPressed(KeyEvent e) {
   int keyCode = e.getKeyCode();
   int d;
   d = INCREMENT;
   // 对小键盘方向键添加具体的事件响应
   if (keyCode == KeyEvent.VK_LEFT)
    add(-d, 0);
   else if (keyCode == KeyEvent.VK_RIGHT)
    add(d, 0);
   else if (keyCode == KeyEvent.VK_UP)
    add(0, -d);
   else if (keyCode == KeyEvent.VK_DOWN)
    add(0, d);
  }

  public void keyReleased(KeyEvent e) {
  }

  // 按键被单击事件监听
  public void keyTyped(KeyEvent e) {
   char keyChar = e.getKeyChar();
   int d;
   if (Character.isUpperCase(keyChar)) {
    d = INCREMENT;
    keyChar = Character.toLowerCase(keyChar);
   } else
    d = INCREMENT;
    //为键盘“h、l、k、j“添加事件响应
   if (keyChar == 'h')
    add(-d, 0);
   else if (keyChar == 'l')
    add(d, 0);
   else if (keyChar == 'k')
    add(0, -d);
   else if (keyChar == 'j')
    add(0, d);
  }
 }
}

(6)鼠标事件示例程序:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MouseEventDemo extends MouseMotionAdapter{
    JFrame frmMain;
    
int intX,intY;
    JPanel pnlMain;
    JLabel lblX,lblY;
    JTextField txtX,txtY;
    GridLayout glMain;
    
public MouseEventDemo(){
        frmMain
=new JFrame("鼠标事件演示");
        pnlMain
=new JPanel();
        frmMain.getContentPane().add(pnlMain);
        glMain
=new GridLayout(2,2);
        pnlMain.setLayout(glMain);
        lblX
=new JLabel("当前鼠标X坐标:");
        lblY
=new JLabel("当前鼠标Y坐标:");
        txtX
=new JTextField(5);
        txtY
=new JTextField(5);
        pnlMain.add(lblX);
        pnlMain.add(txtX);
        pnlMain.add(lblY);
        pnlMain.add(txtY);
        
//定义、绑定鼠标事件监听器对象
        frmMain.addMouseMotionListener(this);
        frmMain.setSize(
250,150);
        frmMain.setVisible(
true);
    }

    
//重写MmouseMotionActionListEner接口中指定方法
    public void mouseMoved(MouseEvent e){
        intX
=e.getX();
        intY
=e.getY();
        txtX.setText(String.valueOf(intX));
        txtY.setText(String.valueOf(intY));
    }

    
public static void main(String args[]){
        MouseEventDemo med
=new MouseEventDemo();
    }
    
}

只有注册用户登录后才能发表评论。


网站导航: