资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

java登录对话框源代码 java登陆界面代码

Java制作一个用户登录的窗口

Java用户登陆这块,主要还是类:

创新互联专注为客户提供全方位的互联网综合服务,包含不限于网站制作、成都做网站、闵行网络推广、成都小程序开发、闵行网络营销、闵行企业策划、闵行品牌公关、搜索引擎seo、人物专访、企业宣传片、企业代运营等,从售前售中售后,我们都将竭诚为您服务,您的肯定,是我们最大的嘉奖;创新互联为所有大学生创业者提供闵行建站搭建服务,24小时服务热线:13518219792,官方网址:www.cdcxhl.com

1,边界布局:BorderLayout。他主要分为五个布局,是JFrame(顶层容器),JDialog(创建对话框窗口的类)的默认布局方式。其最多容量为5个组件,超出5个得用其他的。设置方式为:BorderLayout.NORTH;BorderLayout.SOUTH;BorderLayout.CENTER;Borderlayout.CENTER;BorderLayout.LEFT;BorderLayout.RIGHT。

2,流式布局:FlowLayout。布局方式为从左到右,从上到下。是JPanel(轻量级容器)的默认面板布局。

3,网格布局:GridLayout。布局方式为行和列组成的网络。布局方法:setLayout(new

GridLayout(3,2,3,3));其中强两位数字表示三行两列,后两位表示行与行的间距为3,列与列的间距为3.

接着,就接触到JPanel面板。JPanel是非顶层容器,所以,一个界面只能由一个JFrame,但是可以有多个JPanel组件。其默认布局方式为流式布局。在JPanel这块,学到了用户登录界面的设计。从而接触到另外三个组件:文本框组件:JTextField;密码框组件:JPasswordField;标签组件:JLabel;复选框组件:JCheckBox;单选框组件:JRadioButton;按钮组件JButton。

用swing,怎么样点击文件→登录,弹出一个登录框,可以输入用户名和密码,点击登录,用java怎么样实现

我上传一段代码,你看看能看懂不

package com.iotek.stuManager.view;

import javax.swing.JFrame;

import javax.swing.JPanel;

import javax.swing.border.EmptyBorder;

import javax.swing.JLabel;

import java.awt.EventQueue;

import java.awt.Font;

import java.awt.Color;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.util.ArrayList;

import java.util.List;

import javax.swing.JTextField;

import javax.swing.JButton;

import javax.swing.JPasswordField;

import javax.swing.SwingConstants;

/**

* 登陆界面类

* @author Bernard

*

*/

@SuppressWarnings("serial")

public class FirstLogin extends JFrame {

private JPanel contentPane;//容器

private JTextField usernameInput;//文本框

private JPasswordField pwdInput;//密码框

private JLabel warning;//提示文本

private ListUser users = new ArrayListUser(); // 创建用户集合

/**

* 程序主方法 启动第一个界面

* Launch the application

* @param args

*/

public static void main(String args[]) {

//创建UI线程,

EventQueue.invokeLater(new Runnable() {

public void run() {

try {

//创建登陆界面

FirstLogin window = new FirstLogin();

//窗口属性设置

window.setResizable(false);//设置大小可变

window.setVisible(true);//让窗口显示

} catch (Exception e) {

e.printStackTrace();

}

}

});

}

/**

* 构造方法

* 构造方法中初始化登陆界面内容

*/

public FirstLogin() {

//初始化用户

users.add(new User("admin", "admin")); //用户名 admin 密码 admin

users.add(new User("admin1", "admin1"));//用户名 admin1 密码 admin1

users.add(new User("admin2", "admin2"));//用户名 admin2 密码 admin2

users.add(new User("admin3", "admin3"));//用户名 admin3 密码 admin3

users.add(new User("admin4", "admin4"));//用户名 admin4 密码 admin4

users.add(new User("admin5", "admin5"));//用户名 admin5 密码 admin5

/*

* 设置叉叉按钮功能

*/

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setBounds(100, 100, 450, 300);//界面长宽高

contentPane = new JPanel();//创建容器

contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));//容器边界

setContentPane(contentPane);//添加容器到主界面

contentPane.setLayout(null);//设置布局为绝对布局

/*

*初始化提示框

*/

warning = new JLabel("");//构造提示框

warning.setHorizontalAlignment(SwingConstants.CENTER);//提示框风格

warning.setBounds(105, 229, 239, 23);//提示框尺寸

warning.setForeground(Color.red);//文本颜色

contentPane.add(warning);//添加提示框到容器

/*

* 标题栏

*/

JLabel title = new JLabel("用户管理系统");//构造标题栏

title.setForeground(Color.BLUE);//设置字体颜色

title.setFont(new Font("微软雅黑", Font.PLAIN, 24));//字体

title.setBounds(152, 10, 292, 41);//设置大小

contentPane.add(title);//添加标题到容器

/*

* 版本栏

*/

JLabel version = new JLabel("version : V1.0");//初始化版本栏

version.setBounds(42, 61, 97, 15);//设置版本栏位置

contentPane.add(version);//添加版本栏到容器

/*

* 用户名栏

*/

JLabel username = new JLabel("用户名:");//初始化用户名栏

username.setBounds(72, 105, 63, 26);//设置大小

contentPane.add(username);//添加到容器

/*

* 密码栏

*/

JLabel pwd = new JLabel("密码 :");//初始化密码栏

pwd.setBounds(72, 141, 63, 26);//设置大小

contentPane.add(pwd);// 添加到容器

/*

* 用户名输入栏

*/

usernameInput = new JTextField();//初始化用户名输入

usernameInput.setBounds(187, 107, 177, 23);// 设置位置大小

contentPane.add(usernameInput);// 添加到容器

usernameInput.setColumns(10);// 限制长度

/*

* 登录按钮

*/

JButton enter = new JButton("登录");//按钮初始化

enter.setBounds(42, 189, 93, 23);//设置大小

/**

* 注册监听

*/

enter.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

String inputUserName = usernameInput.getText();//取用户名

char[] inputPwd = pwdInput.getPassword();// 取密码

String pwd = String.valueOf(inputPwd);//字符数组转字符串

int value = checkusername(inputUserName, pwd);

switch(value){

case 1:

FirstLogin.this.warning.setText("用户名或密码长度超出");

break;

case 2:

FirstLogin.this.warning.setText("用户名或密码不能为空");

break;

case 3:

EventQueue.invokeLater(new Runnable() {

public void run() {

try {

new Success();

} catch (Exception e) {

e.printStackTrace();

}

}

});

FirstLogin.this.dispose();

break;

case 4:

FirstLogin.this.warning.setText("密码错误");

break;

case 5:

FirstLogin.this.warning.setText("用户不存在");

break;

}

}

});

contentPane.add(enter);//添加按钮到容器

/*

* 退出按钮

*/

JButton exit = new JButton("退出");// 构造清空按钮

exit.setBounds(297, 189, 93, 23);// 位置大小

/**

* 注册监听

*/

exit.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

FirstLogin.this.dispose();

}

});

contentPane.add(exit);

/*

* 清空按钮

*/

JButton clear = new JButton("清空");//构造

clear.setBounds(168, 189, 93, 23);//位置大小

/**

* 注册监听

*/

clear.addActionListener(new ActionListener() {

@Override

public void actionPerformed(ActionEvent arg0) {

usernameInput.setText("");//清空用户名

pwdInput.setText("");// 清空密码

warning.setText("");// 清空警告

}

});

contentPane.add(clear);

/*

* 密码输入栏

*/

pwdInput = new JPasswordField();// 创建密码输入栏

pwdInput.setBounds(187, 144, 177, 23);// 位置大小

contentPane.add(pwdInput);// 添加到容器

}

/**

* 检测用户名密码

* @param userName 用户名

* @param pwd 密码

* @return 1.长度超出 2长度为零 3 验证失败 4验证成功 5未知错误

*/

private int checkusername(String userName,String pwd){

if(userName.length()11||pwd.length()20){

return 1;

}

if(userName.length()==0||pwd.length()==0){

return 2;

}

for(User u : users){

if(u.checkUserNmae(userName)){

if(u.checkPwd(pwd)){

return 3;

}else{

return 4;

}

}

}

return 5;

// if(){

// return 3;

// }else if(value == 2){

// return 4;

// }else {

// return 5;

// }

}

/**

* 内部内,用户类

* @author Bernard

*

*/

class User{

private String userName;// 用户名属性

private String pwd;// 密码属性

public User(String userName ,String pwd) {

this.userName = userName;

this.pwd = pwd;

}

/**

* 验证用户名

* @param username

* @return

*/

public boolean checkUserNmae(String username){

if(this.userName.equals(username)){

return true;

}

return false;

}

/**

* 验证密码

* @param pwd

* @return

*/

public boolean checkPwd(String pwd){

if(this.pwd.equals(pwd)){

return true;

}

return false;

}

}

/**

* 内部类 登录成功界面类

* @author Bernard

*

*/

class Success extends JFrame{

/**

* 构造方法,构造成功后直接显示

*/

public Success() {

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setBounds(100, 100, 450, 300);//界面长宽高

contentPane = new JPanel();//创建容器

contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));//容器边界

setContentPane(contentPane);//添加容器到主界面

contentPane.setLayout(null);//设置布局为绝对布局

JLabel title = new JLabel("恭喜登录成功");//构造标题栏

title.setForeground(Color.BLUE);//设置字体颜色

title.setFont(new Font("微软雅黑", Font.PLAIN, 24));//字体

title.setBounds(152, 50, 292, 41);//设置大小

contentPane.add(title);//添加标题到容器

this.setResizable(false);

this.setVisible(true);

}

}

}

复制下来键个类直接可以运行的.这里面有你要的一切知识,看懂的话稍加修改就行

编写Java Application,建立一个登录窗口,包含输入用户名和口令的文本框以及登录和取消两个按钮

import java.awt.*;

import javax.swing.*;

import java.awt.event.*;

public class LogOn extends JFrame

{

private JLabel usernameLabel, passwordLabel;

private JTextField usernameText;

private JPasswordField passwordText;

private JButton cancelButton,confButton;

public LogOn ()

{

super("CF Product");

setSize(400,200);

try

{

UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

}catch(Exception e) {}

Container container = getContentPane();

container.setBackground(Color.WHITE);

container.setLayout(null);

usernameLabel = new JLabel("用户名:",JLabel.RIGHT);

passwordLabel = new JLabel("密 码:",JLabel.RIGHT);

usernameText = new JTextField(10);

passwordText = new JPasswordField(10);

cancelButton = new JButton(" 退出");

confButton = new JButton("确定");

usernameLabel.setBounds(80,50,50,25);

usernameText.setBounds(130,50,80,20);

passwordLabel.setBounds(80,80,50,25);

passwordText.setBounds(130,80,80,20);

cancelButton.setBounds(250,80,80,20);

confButton.setBounds(250,50,80,20);

container.add(usernameLabel);

container.add(usernameText);

container.add(passwordLabel);

container.add(passwordText);

container.add(cancelButton);

container.add(confButton);

setVisible(true);

setDefaultCloseOperation(EXIT_ON_CLOSE);

}

public static void main (String arguments[])

{

LogOn application = new LogOn();

}

}

jsp登陆界面源代码

1、login.jsp文件

%@ page language="java" contentType="text/html; charset=GB18030"

pageEncoding="GB18030"%

%@ page import="java.util.*" %

!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

html

head

title登录页面/title

/head

body

form name="loginForm" method="post" action="judgeUser.jsp"

table

tr

td用户名:input type="text" name="userName" id="userName"/td

/tr

tr

td密码:input type="password" name="password" id="password"/td

/tr

tr

tdinput type="submit" value="登录" style="background-color:pink" input

type="reset" value="重置" style="background-color:red"/td

/tr

/table

/form

/body

/html

2、judge.jsp文件

%@ page language="java" contentType="text/html; charset=GB18030"

pageEncoding="GB18030"%

%@ page import="java.util.*" %

!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

html

head

title身份验证/title

/head

body

%

request.setCharacterEncoding("GB18030");

String name = request.getParameter("userName");

String password = request.getParameter("password");

if(name.equals("abc") password.equals("123")) {

3、afterLogin.jsp文件

%

jsp:forward page="afterLogin.jsp"

jsp:param name="userName" value="%=name%"/

/jsp:forward

%

}

else {

%

jsp:forward page="login.jsp"/

%

}

%

/body

/html

%@ page language="java" contentType="text/html; charset=GB18030"

pageEncoding="GB18030"%

!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

html

head

title登录成功/title

/head

body

%

request.setCharacterEncoding("GB18030");

String name = request.getParameter("userName");

out.println("欢迎你:" + name);

%

/body

/html

扩展资料:

java web登录界面源代码:

1、Data_uil.java文件

import java.sql.*;

public class Data_uil

{

public  Connection getConnection()

{

try{

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

}catch(ClassNotFoundException e)

{

e.printStackTrace();

}

String user="***";

String password="***";

String url="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=***";

Connection con=null;

try{

con=DriverManager.getConnection(url,user,password);

}catch(SQLException e)

{

e.printStackTrace();

}

return con;

}

public  String selectPassword(String username)

{

Connection connection=getConnection();

String sql="select *from login where username=?";

PreparedStatement preparedStatement=null;

ResultSet result=null;

String password=null;

try{

preparedStatement=connection.prepareStatement(sql);

preparedStatement.setString(1,username);

result=preparedStatement.executeQuery();//可执行的     查询

if(result.next())

password=result.getString("password");

}catch(SQLException e){

e.printStackTrace();

}finally

{

close(preparedStatement);

close(result);

close(connection);

}

System.out.println("找到的数据库密码为:"+password);

return password; 

}

public  void close (Connection con)

{

try{

if(con!=null)

{

con.close();

}

}catch(SQLException e)

{

e.printStackTrace();

}

}

public  void close (PreparedStatement preparedStatement)

{

try{

if(preparedStatement!=null)

{

preparedStatement.close();

}

}catch(SQLException e)

{

e.printStackTrace();

}

}

public  void close(ResultSet resultSet)

{

try{

if(resultSet!=null)

{

resultSet.close();

}

}catch(SQLException e)

{

e.printStackTrace();

}

}

}

2、login_check.jsp:文件

%@ page language="java" contentType="text/html; charset=utf-8"

pageEncoding="utf-8"%

!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" ""

html

head

meta http-equiv="Content-Type" content="text/html; charset=utf-8"

title验证用户密码/title

/head

body

jsp:useBean id="util" class="util.Data_uil" scope="page" /

%

String username=(String)request.getParameter("username");

String password=(String)request.getParameter("password");

if(username==null||"".equals(username))

{

out.print("script language='javaScript' alert('用户名不能为空');/script");

response.setHeader("refresh", "0;url=user_login.jsp");

}

else

{

System.out.println("输入的用户名:"+username);

String passwordInDataBase=util.selectPassword(username);

System.out.println("密码:"+passwordInDataBase);

if(passwordInDataBase==null||"".equals(passwordInDataBase))

{

out.print("script language='javaScript' alert('用户名不存在');/script");

response.setHeader("refresh", "0;url=user_login.jsp");

}

else if(passwordInDataBase.equals(password))

{

out.print("script language='javaScript' alert('登录成功');/script");

response.setHeader("refresh", "0;url=loginSucces.jsp");

}

else

{

out.print("script language='javaScript' alert('密码错误');/script");

response.setHeader("refresh", "0;url=user_login.jsp");

}

}

%

/body

/html

3、loginSucces.jsp文件

%@ page language="java" contentType="text/html; charset=utf-8"

pageEncoding="utf-8"%

!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" ""

html

head

meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"

titleInsert title here/title

/head

body

hr size="10" width="26%" align="left" color="green"

font size="6" color="red" 登录成功 /font

hr size="10" width="26%" align="left" color="green"

/body

/html

4、user_login.jsp文件

%@ page language="java" contentType="text/html; charset=utf-8"

pageEncoding="utf-8"%

!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" ""

html

head

meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"

title登录界面/title

/head

body  background="C:\Users\win8\workspace\Login\image\9dcbdc339e72a5663b5c289fb5573c13_10.jpg"

center

brbrbrbrbrbr

h1 style="color:yellow"Login/h1

br

form name="loginForm" action="login_check.jsp" method="post" 

table Border="0"

tr

td账号/td

tdinput type="text" name="username"/td

/tr

tr

td密码/td

tdinput type="password" name="password"

/td

/tr

/table

br

input type="submit" value="登录" style="color:#BC8F8F"

/form

/center

/body

/html

JAVA 中 GUI登录界面设计源代码?

import java.awt.BorderLayout;

import java.awt.Container;

import java.awt.FlowLayout;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JPanel;

import javax.swing.JPasswordField;

import javax.swing.JTextField;

public class Login {

private JFrame frame = new JFrame("登录");

private Container c = frame.getContentPane();

private JTextField username = new JTextField();

private JPasswordField password = new JPasswordField();

private JButton ok = new JButton("确定");

private JButton cancel = new JButton("取消");

public Login(){

frame.setSize(300,200);

c.setLayout(new BorderLayout());

initFrame();

frame.setVisible(true);

}

private void initFrame() {

//顶部

JPanel titlePanel = new JPanel();

titlePanel.setLayout(new FlowLayout());

titlePanel.add(new JLabel("系统管理员登录"));

c.add(titlePanel,"North");

//中部表单

JPanel fieldPanel = new JPanel();

fieldPanel.setLayout(null);

JLabel l1 = new JLabel("用户名:");

l1.setBounds(50, 20, 50, 20);

JLabel l2 = new JLabel("密 码:");

l2.setBounds(50, 60, 50, 20);

fieldPanel.add(l1);

fieldPanel.add(l2);

username.setBounds(110,20,120,20);

password.setBounds(110,60,120,20);

fieldPanel.add(username);

fieldPanel.add(password);

c.add(fieldPanel,"Center");

//底部按钮

JPanel buttonPanel = new JPanel();

buttonPanel.setLayout(new FlowLayout());

buttonPanel.add(ok);

buttonPanel.add(cancel);

c.add(buttonPanel,"South");

}

public static void main(String[] args){

new Login();

}

}

请问能不能帮我写一个Java的聊天窗口文件源代码,不要很复杂,只要能运行,聊天就行了!我用淘宝金币换,谢

话说网上真的好多啊...

package client;

import java.awt.Color;

import java.awt.Container;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

import java.io.DataInputStream;

import java.io.DataOutputStream;

import java.io.IOException;

import java.net.Socket;

import java.util.Date;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JOptionPane;

import javax.swing.JScrollPane;

import javax.swing.JTextArea;

import javax.swing.JTextField;

public class ClientFrame extends JFrame{

private JTextArea allmsg;

private JTextField welcome,copyright,chatmsg;

private JButton send;

private JScrollPane js;

private boolean isConnected = true;

public DataOutputStream out;

public DataInputStream in;

public Socket s = null;

String nic; /* -- 保存用户昵称 --*/

/**

* 初始化客户端资源

* 1.获取从LoginFrame传递过来的参数

* 2.初始化界面元素

* 3.初始化通信所需要的资源 EG:输入/输出流(DataInputStream/DataOutputStream)

* */

public ClientFrame(String name,Socket socket)

{

this.setSize(310,660);

this.setLocation(290,50);

this.setTitle("聊天室客户端"+name+"");/* -- 指定窗口的标题 --*/

this.s = socket;/* -- 接收从LoginFrame中传递过来的Socket --*/

this.nic = name+" 说: ";

welcome = new JTextField(" "+name+" 欢迎您来到聊天室 ",100);

welcome.setBackground(Color.blue);

welcome.setEnabled(false);

copyright = new JTextField(" ----- all copyright @ TOP-king -----");

copyright.setEnabled(false);

allmsg = new JTextArea();

allmsg.setEditable(false);

allmsg.append(" 系统消息: 欢迎登录在线聊天室 \n");

js = new JScrollPane(allmsg);//为JTextArea添加滚动条

chatmsg = new JTextField("在此输入聊天信息");

chatmsg.addActionListener(new listen());

send = new JButton("发送");

send.addActionListener(new listen());/* -- 添加事件监听器 --*/

try {

out = new DataOutputStream(s.getOutputStream());

in = new DataInputStream(s.getInputStream());

} catch (IOException e) {JOptionPane.showMessageDialog(null, "系统异常","错误",JOptionPane.OK_CANCEL_OPTION);}

addcomponettocontainer();

/* -- 当用户关闭窗口时进行相关的处理 eg:Socket Data(Input/Output)Stream 的关闭--*/

this.addWindowListener(new WindowAdapter(){

public void windowClosing(WindowEvent we)

{

sendmsg("quitlogout");/* -- 向服务器端发送关闭信息 --*/

isConnected = false;

destory();/* -- 销毁窗口资源 --*/

}

});

new Thread(new linread()).start();/* -- 启动读取信息线程 --*/

}

public void addcomponettocontainer()

{

Container c = this.getContentPane();

c.setLayout(null);

welcome.setBounds(75,10,150,20);

js.setBounds(10,50,280,500);

chatmsg.setBounds(10,560,180,30);

send.setBounds(220,560,70,30);

copyright.setBounds(10,600,280,20);

c.add(welcome);

c.add(js);

c.add(chatmsg);

c.add(send);

c.add(copyright);

this.setVisible(true);

this.setResizable(false);

}

class listen implements ActionListener

{

public void actionPerformed(ActionEvent e) {

// TODO Auto-generated method stub

if(e.getSource()==send||e.getSource()==chatmsg)

{

String msg = chatmsg.getText().trim();

if("".equals(msg))

{

JOptionPane.showMessageDialog(null,"发送信息不能为空!","错误",JOptionPane.OK_OPTION);

}

else

{sendmsg((new Date()).toLocaleString()+"\n"+nic+msg+"\n");chatmsg.setText("");}

}

}

}

/* -- 向服务器端发送信息 --*/

public void sendmsg(String m)

{

if(isConnected)//如果socket的输出流没关闭

{

try {

out.writeUTF(m);

} catch (IOException e) {

JOptionPane.showMessageDialog(null,"发送信息失败!(系统异常)","错误",JOptionPane.OK_OPTION);

}

}

else

{

JOptionPane.showMessageDialog(null,"发送信息失败!(服务器关闭/网络故障)","错误",JOptionPane.OK_OPTION);

}

}

/* -- 读取信息线程 --*/

class linread implements Runnable

{

public void run()

{

read();

}

public void read()

{

while(isConnected)

{

try {

String msg = in.readUTF();

if("SYSTEM_CLOSED".equals(msg))

{

JOptionPane.showMessageDialog(null,"读取消息失败(服务器关闭/网络故障)!","错误",JOptionPane.OK_OPTION);

isConnected = false;

}

else

allmsg.append(msg+"\n");

} catch (IOException e) {

}

}//end while

JOptionPane.showMessageDialog(null,"读取消息失败(服务器关闭/网络故障)!","错误",JOptionPane.OK_OPTION);

}//end read()

}

public void destory()

{

try {

this.out.close();

this.in.close();

this.s.close();

} catch (IOException e) {

}

this.dispose();

}

}

======================================================

package client;

import java.awt.*;

import javax.swing.*;

import java.awt.event.*;

import java.io.*;

import java.net.*;

public class LoginFrame extends JFrame{

private JTextField name;

private JTextField ip;

private JButton ok,cancle;

public Socket socket;

public LoginFrame()

{

super("登录框");

this.setSize(400,80);

this.setLocation(100,100);

name = new JTextField("昵称");

ip = new JTextField("127.0.0.1");

ok = new JButton("登录");

cancle = new JButton("取消");

ok.addActionListener(new listenEvent());

cancle.addActionListener(new listenEvent());

//建立容器

addcomponettocontainer();

this.setDefaultCloseOperation(EXIT_ON_CLOSE);

}

/**

* 建立容器及控件

*/

public void addcomponettocontainer()

{

Container c = this.getContentPane();

c.setLayout(null);

name.setBounds(10,10,100,30);

ip.setBounds(120,10,100,30);

ok.setBounds(230,10,70,30);

cancle.setBounds(310,10,70,30);

c.add(name);

c.add(ip);

c.add(ok);

c.add(cancle);

this.setVisible(true);

this.setResizable(false);

}

public class listenEvent implements ActionListener

{

public void actionPerformed(ActionEvent event) {

// TODO Auto-generated method stub

if(event.getSource()==ok)

{

String n = name.getText().trim();

String i = ip.getText().trim();

if("".equals(n)||"".equals(i))

{

JOptionPane.showMessageDialog(null,"昵称、IP不能够为空!","错误",JOptionPane.OK_OPTION);

}

else{login(n,i);}

}

if(event.getSource()==cancle)

{

name.setText("");

ip.setText("");

}

}

}

/**

* 进行登录

* @param name

* @param ip

*/

public void login(String name,String ip)

{

try {

socket = new Socket(ip,7777);

DataOutputStream out = new DataOutputStream(socket.getOutputStream());

out.writeUTF(name);

out.flush();//强制输出缓存中的内容

//out.close();

new ClientFrame(name,socket);

destroywindow();

} catch (UnknownHostException e) {

JOptionPane.showMessageDialog(null,"找不到主机地址(IP错误/网络故障)!","错误",JOptionPane.OK_OPTION);

} catch (IOException e) {

}

}

public void destroywindow()

{

this.dispose();

}

public static void main(String[] args)

{

new LoginFrame();

}

}

==================================================

package server;

import java.awt.Container;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

import java.io.DataInputStream;

import java.io.DataOutputStream;

import java.io.IOException;

import java.net.ServerSocket;

import java.net.Socket;

import java.util.ArrayList;

import java.util.Date;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JOptionPane;

import javax.swing.JScrollPane;

import javax.swing.JTextArea;

import javax.swing.JTextField;

public class ServerFrame extends JFrame{

/**

*

*/

private static final long serialVersionUID = 1L;

private JTextArea allmsg;

private JTextField currnum,totalnum,copyright,chatmsg;

private JButton send;

private JScrollPane js;

int num1,num2,port;/* -- num1:当前在线人数 num2:总上线人数 port:服务端口号 --*/

private ServerSocket ss;

ArrayListuser lists;//存放所有在线用户

public ServerFrame()

{

super("聊天室服务器端");

this.setSize(310,660);

this.setLocation(200,50);

lists = new ArrayListuser();

num1 = num2 =0;

port = 7777;

currnum = new JTextField(" 当前在线人数: "+num1);

currnum.setEnabled(false);

totalnum = new JTextField(" 上线总人数: "+num2);

totalnum.setEnabled(false);

copyright = new JTextField(" ----- all copyright @ TOP-king -----");

copyright.setEnabled(false);

allmsg = new JTextArea();

allmsg.append(" --------------- 系统消息 --------------\n");

allmsg.setEditable(false);

allmsg.setLineWrap(true); //允许自动换行

js = new JScrollPane(allmsg);//为JTextArea添加滚动条

chatmsg = new JTextField("在此输入系统信息");

chatmsg.addActionListener(new ActionListener(){

@SuppressWarnings("deprecation")

public void actionPerformed(ActionEvent arg0) {

String str = chatmsg.getText().trim();

if(!"".equals(str))

{sendmsg((new Date()).toLocaleString()+" -- 系统消息: "+str);chatmsg.setText("");}

else

JOptionPane.showMessageDialog(null, "消息不能为空","错误",JOptionPane.OK_OPTION);

chatmsg.setText("");/* -- 发送信息后,将输入栏中的信息清空 -- */

}

});

send = new JButton("发送");

send.addActionListener(new ActionListener(){

@SuppressWarnings("deprecation")

public void actionPerformed(ActionEvent arg0) {

String str = chatmsg.getText().trim();

if(!"".equals(str))

{sendmsg((new Date()).toLocaleString()+" -- 系统消息: "+str);chatmsg.setText("");}

else

JOptionPane.showMessageDialog(null, "消息不能为空","错误",JOptionPane.OK_OPTION);

chatmsg.setText("");/* -- 发送信息后,将输入栏中的信息清空 -- */

}

});

//建立容器

addcomponettocontainer();

this.addWindowListener(new WindowAdapter(){

public void windowClosing(WindowEvent we)

{

sendmsg("SYSTEM_CLOSED");/* -- 向客户端发送服务器关闭信息 -- */

destory();

}

});

start(); /* -- 启动连接服务 -- */

}

public void addcomponettocontainer()

{

//Container建立容器

Container c = this.getContentPane();

c.setLayout(null);

currnum.setBounds(20,15,130,20);

totalnum.setBounds(155,15,125,20);

js.setBounds(10,50,280,500);

chatmsg.setBounds(10,560,180,30);

send.setBounds(220,560,70,30);

copyright.setBounds(10,600,280,20);

c.add(currnum);

c.add(totalnum);

c.add(js);

c.add(chatmsg);

c.add(send);

c.add(copyright);

this.setVisible(true);

this.setResizable(false);

}

/**

* start()方法监听客户的连接

* 并且保存客户端的相关信息EG:用户昵称、用户所使用的Socket

* 用户连接到服务器成功之后,将其保存到用户列表中,并为该用户启动一个线程用于通信 */

@SuppressWarnings("deprecation")

public void start()

{

boolean isStarted = false;/* -- 用于标记服务器是否已经正常启动 -- */

try {

this.ss = new ServerSocket(port);

isStarted = true;

this.allmsg.append((new Date()).toLocaleString()+" 服务器启动 @ 端口: "+port+"\n");

while(isStarted)

{

Socket client = this.ss.accept(); /* -- 监听客户端的连接 -- */

DataInputStream in = new DataInputStream(client.getInputStream());

String name = in.readUTF();

user u = new user();

u.name = name;

u.socket = client;

lists.add(u); //将该用户加到列表中去

num1++;

num2++;

currnum.setText(" 当前在线人数: "+num1);

totalnum.setText(" 上线总人数: "+num2);

this.allmsg.append((new Date()).toLocaleString()+" : "+u.name+" 登录 \n");

new Thread(new ClientThread(u)).start();/* -- 为该用户启动一个通信线程 -- */

}

} catch (IOException e) {

System.out.println("服务器已经启动......");

System.exit(0);

}

}

/**

* 通信线程主要功能包括:

* 1.监听客户端输入的信息

* 2.将接收到的信息转发给其他用户 */

class ClientThread implements Runnable

{

user user = null;

boolean isConnected = true;

DataInputStream dis = null;

DataOutputStream dos = null;

public ClientThread(user u)

{

this.user = u;

try {

this.dis = new DataInputStream(this.user.socket.getInputStream());

this.dos = new DataOutputStream(this.user.socket.getOutputStream());

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

public void run()

{

readmsg();

}

/* -- 读取客户的聊天信息 -- */

@SuppressWarnings("deprecation")

public void readmsg()

{

while(isConnected)

{

try {

String msg = dis.readUTF();

if("quitlogout".equals(msg))//当用户关闭客户端窗口时,发送quit字符串 表示用户已经退出

{

num1--;

try{

this.dis.close();

this.dos.close();

this.user.socket.close();

this.isConnected = false;

}catch(IOException ioe)

{

ioe.printStackTrace();

}finally{

this.isConnected = false;

if(dis!=null) this.dis.close();

if(dos!=null) this.dos.close();

if(this.user.socket!=null) this.user.socket.close();

}

lists.remove(this.user);//从列表中删除该用户

currnum.setText(" 当前在线人数: "+num1);

allmsg.append((new Date()).toLocaleString()+" : "+this.user.name+" 退出\n");

}

else

sendmsg(msg);

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

/* -- 将信息进行转发 -- */

public void sendmsg(String msg)

{

user us = new user();

DataOutputStream os = null;

if(lists.size()0)

{

for(int i=0;ilists.size();i++)

{

us = lists.get(i);

try {

os = new DataOutputStream(us.socket.getOutputStream());

os.writeUTF(msg);

} catch (IOException e) {

e.printStackTrace();

}

}

}

else

JOptionPane.showMessageDialog(null, "当前无用户在线。发送消息失败","失败",JOptionPane.OK_OPTION);

}

public void destory()

{

try {

this.ss.close();

} catch (IOException e) {

e.printStackTrace();

}

this.dispose();

}

public static void main(String[] args)

{

new ServerFrame();

}

}

=================================================

package server;

import java.net.*;

public class user {

String name;

Socket socket;

}


本文题目:java登录对话框源代码 java登陆界面代码
文章分享:http://cdkjz.cn/article/dociocs.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220