C/S模式整合

c/s模式分为以下步骤:

    1.组件和容器的定义

    2.组件和容器初始化(构造函数)

    3.添加组件和容器到继承的JFrame

    4.事件添加

    5.事件响应

在C语言、MFC、delphi、VB开发都类似

其中重要的两个部分:布局(五种):主要使用三种

          事件(注册和监听):监听3种:本类实现接口、内部类实现接口、适配器模式

在java中JTree和JTable较其他组件复杂。

C/S实例如下:

package com;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class SwingEvent extends JFrame implements ActionListener {

// 定义组件
private JLabel label1;
private JLabel label2;
private JTextField textfield1;
private JTextField textfield2;
private JButton button1;
private JButton button2;

// 容器
private JPanel panel1;
private JPanel panel2;
private JPanel panel3;

public SwingEvent() {
  // 初始化组件
  label1 = new JLabel("用户名:");
  label2 = new JLabel("密码:");
  textfield1 = new JTextField(15);
  textfield2 = new JTextField(15);
  button1 = new JButton("登陆");
  button2 = new JButton("取消");
  panel1 = new JPanel();
  panel2 = new JPanel();
  panel3 = new JPanel();

  Container con = this.getContentPane();
  con.setLayout(new BorderLayout()); // 常见三种布局,卡片布局很有效
  // 添加组件到容器
  panel1.add(label1);
  panel1.add(textfield1);
  panel2.add(label2);
  panel2.add(textfield2);
  panel3.add(button1);
  panel3.add(button2);
  con.add(panel1, BorderLayout.NORTH);
  con.add(panel2, BorderLayout.CENTER);
  con.add(panel3, BorderLayout.SOUTH);
  this.setBounds(200, 200, 250, 250);
  this.setVisible(true);
  this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  // 添加事件
  // 3种方式:1.实现ActionListener接口 2.内部类实现ActionListener接口 3.适配器(多操作时)
  // 本类中button1使用实现ActionListener接口 button2使用适配器
  button1.addActionListener(this);

  button2.addActionListener(new ActionListener() {
   @Override
   public void actionPerformed(ActionEvent e) {
    if(e.getSource() == button2){
     textfield1.setText("");
     textfield2.setText("");
    }
   }
  });

}

@Override
public void actionPerformed(ActionEvent e) {
  // TODO Auto-generated method stub
  if(e.getSource() == button1){
   JOptionPane.showMessageDialog(null, "登陆成功");
   //实现其他业务 ,如new一个其他窗口或数据库操作
  }
}

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

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值