您的位置:首页 > 编程语言 > Java开发

java在线聊天项目1.3版 ——设计好友列表框功能

2018-01-01 00:44 645 查看
设计好友列表框功能,思路——

1、当客户端成功登陆后,则客户端把成功登陆信息发送给服务端,

2、由服务端将接收到来自各个成功登陆的客户端的用户信息添加进好友列表,

3、每当有成功登陆的用户就向各个客户端发送完整好友列表

4、好友列表窗要一直死循环着等待接收服务端不断发来的好友列表信息

注意:登陆窗退出时不要关闭socket

           聊天窗退出时不要关闭socket

 

重新整合服务端各种服务到server 类中,只要服务端一开,即可接收客户端的各种请求(登陆、注册、聊天等)



1.3版客户端代码做了登陆成功后释放自身,打开好友列表窗后,还要把成功登陆的信息发送给服务端功能

代码如下:

package com.swift.frame;

import java.awt.EventQueue;
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.ConnectException;
import java.net.Socket;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.TitledBorder;

import com.swift.util.Center;

public class LoginDialog extends JDialog {

private static final long serialVersionUID = 1L;
private JPasswordField passwordField_2;
private JPasswordField passwordField_1;
private JTextField textField_2;
private JTextField textField;
String request = null;
String response = null;

Socket s;
DataOutputStream dos;
DataInputStream dis;

public static void main(String args[]) {
JFrame.setDefaultLookAndFeelDecorated(true);
JDialog.setDefaultLookAndFeelDecorated(true);

try {
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
} catch (InstantiationException e1) {
e1.printStackTrace();
} catch (IllegalAccessException e1) {
e1.printStackTrace();
} catch (UnsupportedLookAndFeelException e1) {
e1.printStackTrace();
}

EventQueue.invokeLater(new Runnable() {
public void run() {
try {
LoginDialog dialog = new LoginDialog();
dialog.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

public LoginDialog() {
super();
setResizable(false);
setTitle("在线聊天登录框");
getContentPane().setLayout(null);
setBounds(100, 100, 427, 301);// 注册时高度为578,不注册是301

// 设置窗口居中
this.setLocation(Center.getPoint(this.getSize()));

final JTextField textField_1 = new JTextField();
textField_1.setBounds(148, 90, 192, 42);
getContentPane().add(textField_1);

final JLabel label = new JLabel();
label.setText("帐    号");
label.setBounds(76, 102, 66, 18);
getContentPane().add(label);

final JLabel label_1 = new JLabel();
label_1.setText("密    码");
label_1.setBounds(76, 167, 66, 18);
getContentPane().add(label_1);

final JPasswordField passwordField = new JPasswordField();
passwordField.setBounds(148, 155, 192, 42);
getContentPane().add(passwordField);

final JButton button_1 = new JButton();
button_1.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {

String phone = new String(textField_1.getText()).trim();
String password = new String(passwordField.getPassword()).trim();
if (!phone.equals("") && !password.equals("")) {
try {
request = "login";
dos.writeUTF(request);
response = dis.readUTF();
if (response.equals("login")) {
dos.writeUTF(phone);
dos.writeUTF(password);
String flag=dis.readUTF();
if(flag.equals("success")) {
javax.swing.JOptionPane.showMessageDialog(LoginDialog.this, "登录成功");
//把登陆成功的用户发送给服务端,作为好友列表信息
dos.writeUTF(phone);
dos.flush();
//登陆窗消失
LoginDialog.this.dispose();
//好友列表窗出现
new FriendsFrame(phone,s);

}else if(flag.equals("fail")) {
javax.swing.JOptionPane.showMessageDialog(LoginDialog.this, "登录失败");
}
}
} catch (IOException e1) {
e1.printStackTrace();
}
} else {
javax.swing.JOptionPane.showMessageDialog(LoginDialog.this, "用户名密码必须填写...");
return;
}
}
});
button_1.setText("登录");
button_1.setBounds(230, 222, 106, 36);
getContentPane().add(button_1);

final JButton button = new JButton();
button.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
if (LoginDialog.this.getHeight() == 301) {
LoginDialog.this.setSize(427, 578);
} else {
LoginDialog.this.setSize(427, 301);
}
// 设置窗口不断居中
LoginDialog.this.setLocation(Center.getPoint(LoginDialog.this.getSize()));
}
});
button.setText("注册");
button.setBounds(76, 222, 106, 36);
getContentPane().add(button);

final JPanel panel = new JPanel();
panel.setLayout(null);
panel.setBorder(new TitledBorder(null, "注册用户", TitledBorder.DEFAULT_JUSTIFICATION,
TitledBorder.DEFAULT_POSITION, null, null));
panel.setBounds(10, 278, 401, 226);
getContentPane().add(panel);

final JLabel label_2 = new JLabel();
label_2.setBounds(44, 41, 65, 18);
label_2.setText("手机号:");
panel.add(label_2);

textField = new JTextField();
textField.setBounds(115, 35, 225, 30);
panel.add(textField);

final JButton button_2 = new JButton();
button_2.setText("发送验证");
button_2.setBounds(243, 75, 97, 30);
panel.add(button_2);

textField_2 = new JTextField();
textField_2.setBounds(115, 104, 95, 30);
panel.add(textField_2);

final JLabel label_3 = new JLabel();
label_3.setText("验证码:");
label_3.setBounds(44, 110, 65, 18);
panel.add(label_3);

passwordField_1 = new JPasswordField();
passwordField_1.setBounds(115, 143, 231, 30);
panel.add(passwordField_1);

passwordField_2 = new JPasswordField();
passwordField_2.setBounds(115, 175, 231, 30);
panel.add(passwordField_2);

final JLabel label_4 = new JLabel();
label_4.setText("密        码:");
label_4.setBounds(44, 149, 65, 18);
panel.add(label_4);

final JLabel label_5 = new JLabel();
label_5.setText("验证密码:");
label_5.setBounds(44, 181, 65, 18);
panel.add(label_5);

final JButton button_3 = new JButton();
button_3.setBounds(47, 510, 97, 30);
getContentPane().add(button_3);
button_3.setText("放弃");

final JButton button_4 = new JButton();
button_4.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {

String phone = textField.getText();
String password = null;
String str1 = new String(passwordField_1.getPassword()).trim();
String str2 = new String(passwordField_2.getPassword()).trim();
if (!phone.equals("") && !str1.equals("") && !str2.equals("")) {
if (str1.equals(str2)) {
password = new String(passwordField_2.getPassword()).trim();
try {
request = "reg";
dos.writeUTF(request);
String response = dis.readUTF();
if (response.equals("reg")) {
dos.writeUTF(phone);
dos.writeUTF(password);
}
javax.swing.JOptionPane.showMessageDialog(LoginDialog.this, "注册成功...");
} catch (IOException e1) {
e1.printStackTrace();
}
} else {
javax.swing.JOptionPane.showMessageDialog(LoginDialog.this, "输入密码不一致...");
System.out.println("输入密码不一致...");
passwordField_1.setText("");
passwordField_2.setText("");
}

} else {
javax.swing.JOptionPane.showMessageDialog(LoginDialog.this, "用户名密码必须填写...");
return;
}
}
});

button_4.setBounds(262, 510, 97, 30);
getContentPane().add(button_4);
button_4.setText("注册用户");

connect();

}

public void connect() {
try {
s = new Socket("127.0.0.1", 8888);//以本机做server
System.out.println("一个客户端登陆中....!");
dos = new DataOutputStream(s.getOutputStream());
dis = new DataInputStream(s.getInputStream());

} catch (ConnectException e) {
System.out.println("服务端异常.........");
System.out.println("请确认服务端是否开启.........");
} catch (IOException e) {
e.printStackTrace();
}
}

}


1.3版服务端新增好友列表Vector集合,以及每当有成功登陆的用户就向各个客户端发送完整列表的功能

代码如下:

package com.swift.server;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import com.swift.jdbc.DBAdd;
import com.swift.jdbc.DBLogin;
import com.swift.other.User;

public class Server {

boolean started = false;
ServerSocket ss = null;
Socket s = null;
String request = null;
String response = null;
List<Client> clients = new ArrayList<Client>();
Vector<String> list = new Vector<String>();

public static void main(String[] args) {
new Server().fun();
}

private void fun() {
try {
ss = new ServerSocket(8888);
started = true;
} catch (BindException e) {
System.out.println("端口使用中......");
} catch (IOException e1) {
e1.printStackTrace();
}
try {
while (started) {
s = ss.accept();
System.out.println("a client connected success");
Client c = new Client(s);
clients.add(c);
new Thread(c).start();

}
} catch (EOFException e) {
System.out.println("client has closed.");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
ss.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

class Client implements Runnable {

public Socket s;
public DataInputStream dis;
public DataOutputStream dos;
private boolean connected = false;

public Client(Socket s) {
this.s = s;
try {
this.dis = new DataInputStream(s.getInputStream());
this.dos = new DataOutputStream(s.getOutputStream());
connected = true;
} catch (IOException e) {
e.printStackTrace();
}
}

@Override
public void run() {
try {
while (connected) {
// 接收客户端请求
request = dis.readUTF();
// 发回对此请求的响应
response = request;
dos.writeUTF(response);
dos.flush();
if (request.equals("login")) {

String phone = dis.readUTF();
String password = dis.readUTF();
System.out.println(phone);
System.out.println(password);

User user = new User(phone, password);
boolean login = DBLogin.login(user);
if (login) {
dos.writeUTF("success");
dos.flush();
String userName=dis.readUTF();
//添加进好友列表Vector
list.addElement(userName);

System.out.println();
//每当有成功登陆就向各个客户端发送完整列表
for (int i = 0; i < clients.size(); i++) {
Client c = clients.get(i);
System.out.println(c.s.getPort());
for (int j = 0; j < list.size(); j++) {
String name = list.get(j);
System.out.println(name);
c.send(name);
}
}

} else {
dos.writeUTF("fail");
dos.flush();
}

} else if (request.equals("reg")) {
String phone = dis.readUTF();
String password = dis.readUTF();
System.out.println(phone);
System.out.println(password);

User user = new User(phone, password);
DBAdd.add(user);
} else if (request.equals("chat")) {
String str = dis.readUTF();
System.out.println(str);
for (int i = 0; i < clients.size(); i++) {
Client c = clients.get(i);
c.send(str);
}
}

}
} catch (SocketException e) {
System.out.println("一个登陆窗已经关闭....");
} catch (EOFException e) {
System.out.println("a client has been closed,can't read message from it.");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (s != null) {
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dis != null) {
try {
dis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dos != null) {
try {
dos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

private void send(String str) {
try {
this.dos.writeUTF(str);
this.dos.flush();
} catch (SocketException e) {
clients.remove(this);
} catch (IOException e) {
e.printStackTrace();
}
}

}
}


1.3版好友列表窗新增死循环等待接收线程,每当有新用户登陆则不断更新好友列表窗功能,标题设置为客户端端口做登陆区别

代码如下:

package com.swift.frame;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
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.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JTabbedPane;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class FriendsFrame extends JFrame {

private static final long serialVersionUID = 1L;
private Socket s;
private DataOutputStream dos;
private DataInputStream dis;
private boolean connected=false;
Vector<String> names = new Vector<String>();
JList<String> list=null;

public FriendsFrame(String name,Socket socket) {
super("欢迎 "+":"+socket.getLocalPort());
this.s=socket;
connected=true;
try {
this.dos=new DataOutputStream(s.getOutputStream());
this.dis=new DataInputStream(s.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
JFrame.setDefaultLookAndFeelDecorated(true);
JDialog.setDefaultLookAndFeelDecorated(true);

try {
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
} catch (InstantiationException e1) {
e1.printStackTrace();
} catch (IllegalAccessException e1) {
e1.printStackTrace();
} catch (UnsupportedLookAndFeelException e1) {
e1.printStackTrace();
}

setBounds(100, 100, 247, 581);
setVisible(true);
final JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
getContentPane().add(panel, BorderLayout.NORTH);

final JLabel label = new JLabel(new ImageIcon("Images/logo.jpg"));
label.setText("New JLabel");
panel.add(label, BorderLayout.WEST);
label.setPreferredSize(new Dimension(74,74));

final JPanel panel_1 = new JPanel();
panel_1.setLayout(new BorderLayout());
panel.add(panel_1, BorderLayout.CENTER);

final JLabel advancingSwiftLabel = new JLabel();
advancingSwiftLabel.setText(name);
panel_1.add(advancingSwiftLabel, BorderLayout.CENTER);

final JLabel neverWasterLabel = new JLabel();
neverWasterLabel.setText("Never waste time any more");
panel_1.add(neverWasterLabel, BorderLayout.SOUTH);

final JPanel panel_2 = new JPanel();
panel_2.setLayout(new BorderLayout());
getContentPane().add(panel_2, BorderLayout.SOUTH);

final JPanel panel_3 = new JPanel();
final FlowLayout flowLayout = new FlowLayout();
flowLayout.setAlignment(FlowLayout.LEFT);
panel_3.setLayout(flowLayout);
panel_2.add(panel_3);

final JButton button = new JButton();
panel_3.add(button);
button.setHorizontalTextPosition(SwingConstants.LEFT);
button.setHorizontalAlignment(SwingConstants.LEFT);
button.setText("设置");

final JButton button_1 = new JButton();
panel_3.add(button_1);
button_1.setText("查找");

final JPanel panel_4 = new JPanel();
panel_2.add(panel_4, BorderLayout.EAST);

final JButton button_2 = new JButton();
panel_4.add(button_2);
button_2.setText("退出");

final JTabbedPane tabbedPane = new JTabbedPane();
getContentPane().add(tabbedPane, BorderLayout.CENTER);

final JPanel panel_5 = new JPanel();
tabbedPane.addTab("好友列表", null, panel_5, null);
list=new JList<String>();

panel_5.add(list);

final JPanel panel_6 = new JPanel();
tabbedPane.addTab("群聊", null, panel_6, null);

final JPanel panel_7 = new JPanel();
tabbedPane.addTab("聊天记录", null, panel_7, null);

this.setDefaultCloseOperation(EXIT_ON_CLOSE);

final JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);

final JMenu menu = new JMenu();
menu.setText("操作");
menuBar.add(menu);

final JMenuItem newItemMenuItem = new JMenuItem();
newItemMenuItem.setText("设置");
menu.add(newItemMenuItem);

final JMenuItem newItemMenuItem_1 = new JMenuItem();
newItemMenuItem_1.setText("空间");
menu.add(newItemMenuItem_1);

final JMenuItem newItemMenuItem_2 = new JMenuItem();
newItemMenuItem_2.setText("邮箱");
menu.add(newItemMenuItem_2);

final JMenu menu_1 = new JMenu();
menu_1.setText("会员");
menu.add(menu_1);

final JMenuItem newItemMenuItem_3 = new JMenuItem();
newItemMenuItem_3.setText("会员官网");
menu_1.add(newItemMenuItem_3);

final JMenuItem newItemMenuItem_4 = new JMenuItem();
newItemMenuItem_4.setText("会员专区");
menu_1.add(newItemMenuItem_4);

menu.addSeparator();

final JMenu menu_2 = new JMenu();
menu_2.setText("安全");
menu.add(menu_2);

final JMenuItem newItemMenuItem_5 = new JMenuItem();
newItemMenuItem_5.setText("紧急冻结");
menu_2.add(newItemMenuItem_5);

final JMenuItem newItemMenuItem_6 = new JMenuItem();
newItemMenuItem_6.setText("密码保护");
menu_2.add(newItemMenuItem_6);

final JMenuItem newItemMenuItem_7 = new JMenuItem();
newItemMenuItem_7.setText("退出");
menu.add(newItemMenuItem_7);
final FlowLayout flowLayout_1 = new FlowLayout();
flowLayout_1.setAlignment(FlowLayout.RIGHT);

this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
disconnect();
System.exit(0);
}
});

//调用傻傻的等待接收列表信息
new Thread(new WaitingReceive()).start();

list.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if(e.getClickCount()==2) {
new ChatFrame(s);
}
}
});

}

public void disconnect() {
try {
if (dos != null)
dos.close();
if (dis != null)
dis.close();
if (s != null)
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}

class WaitingReceive implements Runnable {

@Override
public void run() {
try {
while (connected) {
String name=dis.readUTF();
System.out.println(name);
names.add(name);
list.setListData(names);
}
} catch (SocketException e) {
System.out.println("a client has been closed!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* WindowBuilder generated method.<br>
* Please don't remove this method or its invocations.<br>
* It used by WindowBuilder to associate the {@link javax.swing.JPopupMenu} with
* parent.
*/
private static void addPopup(Component component, final JPopupMenu popup) {
component.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
if (e.isPopupTrigger())
showMenu(e);
}

public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger())
showMenu(e);
}

private void showMenu(MouseEvent e) {
popup.show(e.getComponent(), e.getX(), e.getY());
}
});
}
}


聊天窗口功能有异常待解决

代码如下:

package com.swift.frame;

import java.awt.BorderLayout;
import java.awt.Color;
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.ConnectException;
import java.net.Socket;
import java.net.SocketException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class ChatFrame extends JFrame {

private static final long serialVersionUID = -118470059355655240L;
private Socket s;
private DataOutputStream dos;
private DataInputStream dis;
private boolean connected = false;
private String request = null;
private String response = null;
JLabel label_shang = new JLabel();
JLabel label_xia = new JLabel();
JTextField tf = new JTextField(38);
JTextArea ta = new JTextArea(15, 45);
JButton button = new JButton();

public ChatFrame(Socket socket) {
setBounds(200, 200, 500, 400);
setTitle("客户端聊天工具 —— 1.0");
// 对窗口进行大的布局,分为三行一列,在pBasic面板上添加三个面板shang zhong xia
JPanel pBasic = new JPanel();
pBasic.setLayout(new BorderLayout());// 不设置默认也是这种布局模式
setContentPane(pBasic);// 把面板放在窗口上,不记得用this.关键字
JPanel shang = new JPanel();
JPanel zhong = new JPanel();
JPanel xia = new JPanel();
// 设置JPanel面板的大小
shang.setSize(470, 25);
zhong.setSize(470, 180);
xia.setSize(470, 40);
pBasic.add(shang, BorderLayout.NORTH);
pBasic.add(zhong, BorderLayout.CENTER);
pBasic.add(xia, BorderLayout.SOUTH);
shang.setBackground(Color.red);
zhong.setBackground(Color.yellow);
xia.setBackground(Color.blue);

label_shang.setText("聊天记录");
shang.add(label_shang);
ta.setLineWrap(true);// 自动换行
JScrollPane scroll = new JScrollPane(ta);// 增加滚动条,以便不增加行数
zhong.add(scroll);
label_xia.setText("输入信息");
xia.add(label_xia, BorderLayout.WEST);
/*
* 增加功能,窗口监听事件,窗口打开时设置光标焦点在tf文本域中
*/
this.addWindowListener(new WindowAdapter() {
@Override
public void windowOpened(WindowEvent e) {
tf.requestFocus();
}
});
xia.add(tf, BorderLayout.CENTER);
button.setText("发送");
xia.add(button, BorderLayout.EAST);

button.addActionListener(new MyListener());
tf.addActionListener(new MyListener());
pack();

setVisible(true);
// 创建窗体直接调用连接服务器
this.s = socket;
connected = true;
try {
dos = new DataOutputStream(s.getOutputStream());
dis = new DataInputStream(s.getInputStream());
} catch (ConnectException e) {
System.out.println("服务端异常.........");
System.out.println("请确认服务端是否开启.........");
} catch (IOException e1) {
e1.printStackTrace();
}
new Thread(new WaitingReceive()).start();
}

class MyListener implements ActionListener {

@Override
public void actionPerformed(ActionEvent e) {
String tfText1 = tf.getText();
tf.setText("");
// 当回车或发送按钮时,tfText发送到服务器
try {
request = "chat";
//发送聊天请求
dos.writeUTF(request);
dos.flush();
//接收服务端反馈
response = dis.readUTF();
if (response.equals("chat")) {
dos.writeUTF(tfText1);
dos.flush();
}
} catch (IOException e1) {
e1.printStackTrace();
}

}
}

class WaitingReceive implements Runnable {

@Override
public void run() {
try {
while (connected) {
String str = dis.readUTF();
System.out.println(str);
ta.setText(ta.getText() + str + "\r\n");
}
} catch (SocketException e) {
System.out.println("a client has been closed!");
} catch (IOException e) {
e.printStackTrace();
}
}
}

}


数据库相关类没有修改:

DBUtil类

package com.swift.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBUtil {

public static Connection getConn() {
Connection conn=null;
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
String url="jdbc:mysql://localhost:3306/sw_database";
String user="root";
String password="root";
conn=DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}

public static void closeAll(Connection conn,PreparedStatement ps,ResultSet rs) {

if(conn!=null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(ps!=null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(rs!=null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}


DBLogin类

package com.swift.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.swift.other.User;

public class DBLogin {

public static boolean login(User user) {

Connection conn=DBUtil.getConn();
PreparedStatement ps=null;
ResultSet rs=null;
try {
ps=conn.prepareStatement("select * from sw_user where username=? and password=?");
ps.setString(1, user.getUsername());
ps.setString(2, user.getPassword());
rs=ps.executeQuery();
if(rs.next()) {
return true;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DBUtil.closeAll(conn, ps, rs);
return false;
}
}


DBAdd类

package com.swift.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import com.swift.other.User;

public class DBAdd {

public static void add(User user) {

String phone = user.getUsername();
String password = user.getPassword();

Connection conn = DBUtil.getConn();
PreparedStatement ps=null;
try {
ps = conn.prepareStatement("insert into sw_user(username,password) values(?,?)");
ps.setString(1, phone);
ps.setString(2, password);
int count = ps.executeUpdate();
if (count == 1) {
System.out.println("用户添加成功");
} else {
System.out.println("用户添加失败");
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
DBUtil.closeAll(conn, ps, null);
}

}

}


工具类User Center没变

package com.swift.other;

public class User {

private int id;
private String username;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public User(int id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
public User() {
super();
}
public User(String username, String password) {
this.username = username;
this.password = password;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", password=" + password + "]";
}

}


Center类

package com.swift.util;

import java.awt.Dimension;
import java.awt.Point;
import java.awt.Toolkit;

public class Center {
public static Point getPoint(int width,int height) {
Toolkit toolkit=Toolkit.getDefaultToolkit();//应该是单例
int screenW=toolkit.getScreenSize().width;
int screenH=toolkit.getScreenSize().height;
int x=(screenW-width)/2;
int y=(screenH-height)/2;
Point p=new Point(x,y);
return p;
}
//函数的重载,参数是包装类尺寸——Dimension
public static Point getPoint(Dimension d) {
Point p=getPoint(d.width,d.height);
return p;
}
}


连接数据库所需包

mysql-connector-java-5.1.7-bin.jar

下载地址:

链接: https://pan.baidu.com/s/1boYv6DT 密码: j91g

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐