JavaBean自定组件
package com.wt010.jframe; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.EventListener; import java.util.EventObject; import javax.swing.*; /** * @author konecms * @date 2018年1月20日 * @version 1.0 */ class LoginEvent extends EventObject{ public String sUserName,sUserPass; public LoginEvent(Object obj,String sUserName,String sUserPass) { super(obj); // TODO Auto-generated constructor stub this.sUserName=sUserName; this.sUserPass=sUserPass; } } interface LoginListener extends EventListener{ public void validateLogin(LoginEvent mec); } class LoginBean extends JPanel implements ActionListener{ JLabel lblUser=new JLabel("用户名:"); JLabel lblPass=new JLabel("密码:"); JTextField txtUser=new JTextField(15); JPasswordField txtPass=new JPasswordField(15); JButton buttonLogin =new JButton("登录"); JButton buttonCancel=new JButton("取消"); public LoginBean(){ setLayout(new FlowLayout()); add(lblUser);add(txtUser); add(lblPass);add(txtPass); add(buttonLogin);buttonLogin.addActionListener(this); add(buttonCancel);buttonCancel.addActionListener(this); } LoginListener mel; public void addLoginListener(LoginListener mel){ this.mel=mel; } LoginEvent mec; public void fireLoginEvent(LoginEvent mec){ if(mel!=null){ mel.validateLogin(mec); }else{ System.out.println("Client not init"); } } @Override public void actionPerformed(ActionEvent ae) { // TODO Auto-generated method stub if(ae.getSource()==buttonLogin){ String temp1=txtUser.getText(); String temp2=new String(txtPass.getPassword()); mec=new LoginEvent(buttonLogin,temp1,temp2); fireLoginEvent(mec);return; } if(ae.getSource()==buttonCancel){ System.exit(0); } } } class JavaBean extends JFrame implements LoginListener{ LoginBean meb; public JavaBean(){ super("javabean"); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); meb=new LoginBean(); this.getContentPane().add(meb); meb.addLoginListener(this); } @Override public void validateLogin(LoginEvent mec) { // TODO Auto-generated method stub String s1=mec.sUserName; String s2=mec.sUserPass; JOptionPane.showMessageDialog(this, "用户名:"+s1+"\t密码是:"+s2); } public static void main(String[] args) { JavaBean mec=new JavaBean(); mec.setSize(200,200); mec.setVisible(true); } }