问题描述
我正在尝试制作一个模拟社交媒体应用程序,用户可以在其中创建一个帐户,使用密码和用户(不必是安全的或任何东西)并存储在服务器中。他们能够使用一些基本变量创建个人资料并设置个人资料图片。全部通过 JavaSwing 使用 GUI。这也是在服务器上运行的。
登录客户端
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.socket;
//Todo: ADD WELCOME MESSAGE
//Todo: FIX MESSAGES TO SERVER BASED ON WHAT YOU WROTE IN GOOGLE DOCS
public class LoginClient extends JComponent implements Runnable {
private static JTextField userLog;
private static JTextField passLog;
private static JTextField userCreate;
private static JTextField passCreate;
private static JButton loginButton;
private static JButton createButton;
LoginClient logClient;
public static boolean bool = true;
public static User receive;
public static boolean loop = false;
public static InputStream input;
public static OutputStream output;
public static ObjectOutputStream writer;
public static ObjectInputStream reader;
public static Socket socket;
public static String username;
public void run() {
JFrame frame = new JFrame();
frame.setTitle("");
Container content = frame.getContentPane();
content.setLayout(null);
logClient = new LoginClient();
content.add(logClient,BorderLayout.CENTER);
content.add(logClient);
frame.setSize(600,400);
frame.setLocationRelativeto(null);
frame.setDefaultCloSEOperation(JFrame.disPOSE_ON_CLOSE);
frame.setVisible(true);
loginButton = new JButton("Login");
createButton = new JButton("Create");
userLog = new JTextField(25);
passLog = new JTextField(25);
userCreate = new JTextField(25);
passCreate = new JTextField(25);
userLog.setBounds(60,100,170,30);
content.add(userLog);
passLog.setBounds(60,160,30);
content.add(passLog);
loginButton.setBounds(100,220,50);
content.add(loginButton);
userCreate.setBounds(360,30);
content.add(userCreate);
passCreate.setBounds(360,30);
content.add(passCreate);
createButton.setBounds(400,50);
content.add(createButton);
JSeparator line = new JSeparator(JSeparator.VERTICAL);
line.setBounds(300,5,150);
content.add(line);
JLabel signInText = new JLabel("Sign In");
signInText.setFont(new Font("serif",Font.BOLD,20));
signInText.setBounds(115,30,200,50);
content.add(signInText);
JLabel createText = new JLabel("Create Account");
createText.setFont(new Font("serif",20));
createText.setBounds(380,300,50);
content.add(createText);
loginButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
User anotherLog = new User(userLog.getText(),passLog.getText());
anotherLog.setPhase(0);
writer.writeObject(anotherLog);
writer.flush();
//writer.reset();
receive = (User) reader.readobject();
if(receive != null) {
System.out.println(receive);
}
if ((userLog.getText().equals("") || passLog.getText().equals(""))) {
JOptionPane.showMessageDialog(null,"Please enter your username and password.","Null Login",JOptionPane.ERROR_MESSAGE);
} else if (receive.getUsername() == null) {
JOptionPane.showMessageDialog(null,"Your account does not exist. Please Check your username and password.","Incorrect Login",JOptionPane.ERROR_MESSAGE);
} else if (receive.getUsername().equals(userLog.getText()) &&
!receive.getpassword().equals(passLog.getText())) {
JOptionPane.showMessageDialog(null,"Your password is incorrect.","Incorrect Password",JOptionPane.ERROR_MESSAGE);
} else if (receive.getUsername().equals(userLog.getText()) &&
receive.getpassword().equals(passLog.getText())) {
//writer.writeObject(new User());
// writer.flush();
System.out.println("log done");
username = receive.getUsername();
MainClient main = new MainClient();
SwingUtilities.invokelater(main);
main.setUsername(username);
frame.setVisible(false);
}
} catch (IOException | ClassNotFoundException ioException) {
ioException.printstacktrace();
}
}
});
createButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
User anotherCreate = new User(userCreate.getText(),passCreate.getText());
anotherCreate.setPhase(3);
writer.writeObject(anotherCreate);
writer.flush();
receive = (User) reader.readobject();
if ((userCreate.getText().equals("") || passCreate.getText().equals(""))) {
JOptionPane.showMessageDialog(null,"Please enter a valid username and password.","Null Account Info",JOptionPane.ERROR_MESSAGE);
}
else if (receive.getUsername() == null) {
JOptionPane.showMessageDialog(null,"Your username has already been taken. Please enter another one.","Existing Account",JOptionPane.ERROR_MESSAGE);
} else if (receive.getUsername().equals(userCreate.getText())){
JOptionPane.showMessageDialog(null,"Your account has been created","Congratulations!",JOptionPane.PLAIN_MESSAGE);
return;
}
} catch (IOException | ClassNotFoundException ioException) {
ioException.printstacktrace();
}
}
});
}
public static void main(String[] args) throws IOException {
//all this goes in main driver class once we have it
socket = new Socket("localhost",4242);
input = socket.getInputStream();
output = socket.getoutputStream();
writer = new ObjectOutputStream(output);
reader = new ObjectInputStream(input);
SwingUtilities.invokelater(new LoginClient());
}
}
主要客户
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.InputStream;
import java.io.OutputStream;
public class MainClient extends JFrame implements ActionListener,Runnable {
//instance data for the fields of the popup
Container container = getContentPane();
public static InputStream input;
public static OutputStream output;
JButton viewProfile = new JButton("View Profile");
JButton editProfile = new JButton("Edit Profile");
JButton createProfile = new JButton("Create/Edit Profile");
JButton deleteProfile = new JButton("Delete Profile");
JButton userSearch = new JButton("User Search");
JButton importProfile = new JButton("Import Profile");
JButton exportProfile = new JButton("Export Profile");
JButton friends = new JButton("Friends List");
JButton homeButton = new JButton("Home");
public static String username;
//constructor that calls the methods and generates the GUI
public void run() {
setTitle("Main Page");
setVisible(true);
setBounds(10,10,800,600);
setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setLayoutManager();
setLocationAndSize();
addComponents();
addActionEvent();
}
public void setUsername(String username) {
this.username = username;
}
//methods that initialize the popup fields
public void setLayoutManager() {
container.setLayout(null);
}
public void setLocationAndSize() {
//center of the screen
createProfile.setBounds(300,180,100);
viewProfile.setBounds(300,280,100);
//top left of screen
userSearch.setBounds(50,50,150,30);
friends.setBounds(50,30);
//bottom right and left of the screen
importProfile.setBounds(50,500,30);
exportProfile.setBounds(600,30);
}
public void addComponents() {
container.add(viewProfile);
container.add(editProfile);
container.add(createProfile);
container.add(deleteProfile);
container.add(userSearch);
container.add(importProfile);
container.add(exportProfile);
container.add(friends);
}
public void addActionEvent() {
viewProfile.addActionListener(this);
createProfile.addActionListener(this);
friends.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
try {
if (e.getSource() == viewProfile) {
viewProfilePage viewProfilePage = new viewProfilePage();
SwingUtilities.invokelater(viewProfilePage);
viewProfilePage.setUsername(username);
} else if (e.getSource() == createProfile) {
createProfilePage createProfilePage = new createProfilePage();
SwingUtilities.invokelater(createProfilePage);
createProfilePage.setUsername(username);
} else if (e.getSource() == friends) {
FriendGUI friendGUI = new FriendGUI();
SwingUtilities.invokelater(friendGUI);
friendGUI.setUsername(username);
}
} catch (Exception g) {
g.printstacktrace();
}
}
}
服务器
import java.io.IOException;
import java.net.ServerSocket;
import java.net.socket;
public class Server implements Runnable{
protected int serverPort = 4242;
protected ServerSocket serverSocket = null;
protected boolean isstopped = false;
protected Thread runningThread = null;
public Server(int port){
this.serverPort = port;
}
public void run() {
synchronized(this){
this.runningThread = Thread.currentThread();
}
openServerSocket();
while(!isstopped()){
Socket clientSocket = null;
try {
clientSocket = this.serverSocket.accept();
System.out.println("accepted");
} catch (IOException e) {
if(isstopped()) {
System.out.println("Server Stopped.") ;
return;
}
throw new RuntimeException(
"Error accepting client connection",e);
}
new Thread(new ClientHandler(clientSocket)).start();
}
System.out.println("Server Stopped.") ;
}
private synchronized boolean isstopped() {
return this.isstopped;
}
public synchronized void stop(){
this.isstopped = true;
try {
this.serverSocket.close();
System.out.println("closed");
} catch (IOException e) {
throw new RuntimeException("Error closing server",e);
}
}
private void openServerSocket() {
try {
this.serverSocket = new ServerSocket(this.serverPort);
} catch (IOException e) {
throw new RuntimeException("Cannot open port 4242",e);
}
}
}
服务器驱动
public class ServerDriver {
public static void main(String[] args) {
Server server = new Server(4242);
new Thread(server).start();
}
}
用户类
import java.io.*;
import java.util.ArrayList;
/**
* This is the User class which contains the building blocks of the base user of
* our overall module.
*/
public class User implements Serializable {
private String username;
private String password;
private String name;
private int age;
private long phone;
private String interest;
private ArrayList<String> friendsList;
private String aboutMe;
private ArrayList<String> friendrequests;
private ArrayList<String> incomingrequst;
private int phase;
/**
* Constructor for brand new user. New users will have to manually add interests,friends,and
* about me using setters.
*
*/
public User(String username,String password) {
this.username = username;
this.password = password;
this.name = null;
this.age = 0;
this.phone = 0;
this.interest = null;
this.friendsList = null;
this.aboutMe = null;
this.phase = 0;
}
public User(String username) {
this.username = username;
this.password = null;
this.name = null;
this.age = 0;
this.phone = 0;
this.interest = null;
this.friendsList = null;
this.aboutMe = null;
this.phase = 0;
}
public User() {
this.username = null;
this.password = null;
this.name = null;
this.age = 0;
this.phone = 0;
this.interest = null;
this.friendsList = null;
this.aboutMe = null;
this.phase = 0;
}
public User(String username,String password,String name,int age,long phone) {
this.username = username;
this.password = password;
this.name = name;
this.age = age;
friendsList = new ArrayList<String>();
this.aboutMe = null;
this.phase = 0;
}
/**
* This constructor is for a user who may have a prepopulated set all qualities.
*
* @param name: full name of user (string)
* @param age: age of user (int)
* @param phone: phone number of user (long)
* @param interest: array list of interests (ArrayList<String>)
* //@param array list where each index is a friend (ArrayList<String>)
* @param aboutMe: array list describing the user (ArrayList<String>)
*/
public User(String username,long phone,String interest,String aboutMe) {
this.username = username;
this.name = name;
this.age = age;
this.phone = phone;
this.interest = interest;
this.friendsList = friendsList;
this.aboutMe = aboutMe;
this.phase = 0;
}
public ArrayList<String> getFriendrequests() {
return this.friendrequests;
}
public void setFriendrequests(ArrayList<String> friendrequests) {
this.friendrequests = friendrequests;
}
public ArrayList<String> getIncomingrequst() {
return this.incomingrequst;
}
public void setIncomingrequst(ArrayList<String> incomingrequst) {
this.incomingrequst = incomingrequst;
}
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
public String getpassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return this.age;
}
public void setAge(int age) {
this.age = age;
}
public long getPhone() {
return this.phone;
}
public void setPhone(long phone) {
this.phone = phone;
}
public String getInterest() {
return this.interest;
}
public void setInterest(String interest) {
this.interest = interest;
}
public ArrayList<String> getFriendsList() {
return this.friendsList;
}
public void setFriendsList(ArrayList<String> friendsList) {
this.friendsList = friendsList;
}
public String getAboutMe() {
return this.aboutMe;
}
public void setAboutMe(String aboutMe) {
this.aboutMe = aboutMe;
}
public int getPhase() {
return this.phase;
}
public void setPhase(int phase) {
this.phase = phase;
}
public User(File fileName) {
FileReader fr = null;
try {
fr = new FileReader(fileName);
} catch (FileNotFoundException e) {
e.printstacktrace();
}
BufferedReader bfr = new BufferedReader(fr);
try {
String line = bfr.readLine();
while (line != null) {
this.username = line;
line = bfr.readLine();
this.password = line;
line = bfr.readLine();
this.name = line;
line = bfr.readLine();
this.age = Integer.parseInt(line);
line = bfr.readLine();
this.phone = Long.parseLong(line);
line = bfr.readLine();
this.interest = line;
line = bfr.readLine();
this.aboutMe = line;
line = bfr.readLine();
/*** ArrayList<String> interests = new ArrayList<String>();
String interestArray[];
interestArray = line.split(",");
for (int i = 0; i < interestArray.length; i++) {
interests.add(interestArray[i]);
}
this.interest = interests; ***/
ArrayList<String> friendsList = new ArrayList<String>();
String friendsArray[];
friendsArray = line.split(",");
for (int i = 0; i < friendsArray.length; i++) {
friendsList.add(friendsArray[i]);
}
this.friendsList = friendsList;
/*** ArrayList<String> aboutMe = new ArrayList<String>();
String aboutMeArray[];
aboutMeArray = line.split(",");
for (int i = 0; i < aboutMeArray.length; i++) {
aboutMe.add(aboutMeArray[i]);
}
this.aboutMe = aboutMe; ***/
bfr.close();
}
} catch (IOException e1) {
e1.printstacktrace();
}
}
}
创建配置文件类
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.socket;
import java.nio.ByteBuffer;
class createProfilePage extends JFrame implements ActionListener,Runnable {
Container container = getContentPane();
static User user;
public String username;
JLabel name = new JLabel("Name: ");
JTextField nameField = new JTextField();
JLabel age = new JLabel("Age: ");
JTextField ageField = new JTextField();
JLabel interest = new JLabel("Interests: ");
JTextField interestField = new JTextField();
JLabel aboutMe = new JLabel("About me: ");
JTextField aboutMeField = new JTextField();
JLabel phoneNum = new JLabel("Phone Number: ");
JTextField phoneNumberField = new JTextField();
JLabel picLabel = new JLabel();
JButton submit = new JButton("Save Profile");
JButton deleteProfile = new JButton("Delete Profile");
JButton uploadPic = new JButton("Upload Profile Picture");
public static ObjectInputStream reader;
public static ObjectOutputStream writer;
public static Socket socket;
public void run()
{
setDefaultCloSEOperation(javax.swing.WindowConstants.disPOSE_ON_CLOSE);
//setting container
setLayoutManager();
setLocationAndSize();
addComponents();
addActionEvent();
setVisible(true);
setTitle("Create Profile");
setSize(600,500);
}
public void setLayoutManager() {
container.setLayout(null);
}
public void setLocationAndSize()
{
//Setting location and Size of each components using setBounds() method.
name.setBounds(50,30);
age.setBounds(50,30);
phoneNum.setBounds(50,240,30);
interest.setBounds(50,310,30);
aboutMe.setBounds(50,380,30);
submit.setBounds(350,30);
deleteProfile.setBounds(350,30);
uploadPic.setBounds(350,30);
nameField.setBounds(150,30);
ageField.setBounds(150,30);
phoneNumberField.setBounds(150,30);
interestField.setBounds(150,30);
aboutMeField.setBounds(150,30);
picLabel.setBounds(350,150);
}
public void addComponents() {
container.add(name);
container.add(age);
container.add(phoneNum);
container.add(interest);
container.add(aboutMe);
container.add(nameField);
container.add(ageField);
container.add(phoneNumberField);
container.add(interestField);
container.add(aboutMeField);
container.add(submit);
container.add(deleteProfile);
container.add(uploadPic);
container.add(picLabel);
}
public void addActionEvent() {
submit.addActionListener(this);
deleteProfile.addActionListener(this);
uploadPic.addActionListener(this);
}
public void setUsername(String username) {
this.username = username;
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == submit) {
String name = nameField.getText();
String age = ageField.getText();
String phoneNum = phoneNumberField.getText();
String interest = interestField.getText();
String aboutMe = aboutMeField.getText();
try {
Socket socket = new Socket("localhost",4242);
//creating user object to send to the server
//Todo
user = new User(username,name,Integer.valueOf(age),Long.valueOf(phoneNum),interest,aboutMe);
writer = new ObjectOutputStream(socket.getoutputStream());
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
user.setPhase(1);
writer.writeObject(user);
reader = new ObjectInputStream(socket.getInputStream());
user = (User) reader.readobject();
String username = user.getUsername();
// User user = new User(username,aboutMe);
setVisible(false);
} catch (IOException | ClassNotFoundException b) {
b.printstacktrace();
}
JOptionPane.showMessageDialog(this,"Profile Creation Successful");
} else if (e.getSource() == deleteProfile) {
String name = null;
String age = null;
String phoneNum = null;
String interest = null;
String aboutMe = null;
JOptionPane.showMessageDialog(this,"Profile Deletion Successful");
} else if (e.getSource() == uploadPic) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
int result = fileChooser.showOpenDialog(getParent());
if (result == JFileChooser.APPROVE_OPTION) {
try {
//getting file from directory
File file = fileChooser.getSelectedFile();
BufferedImage picture = ImageIO.read(file);
//sending image to server
Socket socket = new Socket("localhost",4242);
writer = new ObjectOutputStream(socket.getoutputStream());
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//String filename = file.toString();
ImageIO.write(picture,"png",byteArrayOutputStream);
byte[] size = ByteBuffer.allocate(4).putInt(byteArrayOutputStream.size()).array();
//writer.write(size);
// writer.write(byteArrayOutputStream.toByteArray());
//adds pic to screen
picLabel.setIcon(new ImageIcon(picture.getScaledInstance(100,Image.SCALE_FAST)));
add(picLabel);
//flushes outputstream and closes Socket
writer.flush();
//socket.close();
//sets picture
} catch (IOException g) {
g.printstacktrace();
JOptionPane.showMessageDialog(null,"ERROR");
}
}
}
}
}
查看个人资料类
import javax.swing.*;
import java.awt.*;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.socket;
class viewProfilePage extends JFrame implements Runnable
{
JLabel profilePic = new JLabel();
Container container = getContentPane();
static User user;
JLabel about = new JLabel("About me:");
JTextArea aboutMe;
JTextField name;
JTextField age;
JTextField interestField;
JTextField phoneNumberField;
public static ObjectInputStream reader;
public static ObjectOutputStream writer;
public static Socket socket;
public static String username;
public void run()
{
setDefaultCloSEOperation(javax.swing.WindowConstants.disPOSE_ON_CLOSE);
setLayoutManager();
setVisible(true);
try {
loadProfilePic();
Socket socket = new Socket("localhost",4242);
writer = new ObjectOutputStream(socket.getoutputStream());
User anotherUser = new User(username);
anotherUser.setPhase(0);
writer.writeObject(anotherUser);
reader = new ObjectInputStream(socket.getInputStream());
user = (User) reader.readobject();
//fills in section of Profile
String aboutMeSection = user.getAboutMe();
aboutMe = new JTextArea(aboutMeSection,30);
String interestSection = user.getInterest();
interestField = new JTextField(interestSection);
String nameSpace = user.getName();
name = new JTextField(nameSpace);
String ageSpace = String.valueOf(user.getAge());
age = new JTextField(ageSpace);
String phoneNumSpace = String.valueOf(user.getPhone());
//setting bounds
phoneNumberField = new JTextField(phoneNumSpace);
aboutMe.setBounds(150,200);
name.setBounds(150,20,30);
interestField.setBounds(150,250,200);
age.setBounds( 300,30);
phoneNumberField.setBounds(400,30);
profilePic.setBounds(350,150);
//addint to container
container.add(name);
container.add(interestField);
container.add(age);
container.add(phoneNumberField);
container.add(profilePic);
} catch ( Exception e) {
e.printstacktrace();
}
setTitle("View Profile");
setSize(800,800);
}
public void setUsername(String username) {
this.username = username;
}
public void setLayoutManager() {
container.setLayout(null);
}
public void loadProfilePic() throws Exception {
JLabel profilePic = new JLabel();
Socket socket = new Socket("localhost",4242);
ClientHandler hand = new ClientHandler(socket);
profilePic.setIcon(new ImageIcon(hand.getimage().getScaledInstance(100,Image.SCALE_FAST)));
add(profilePic);
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)