JAVA.SWING实现的简单日记系统Swing+Mysql

实现用java的swing和数据库的操作,保存日记信息(图片+字符数据)。实现从保存过的日期字段修改数据。

展示效果

1,登录页面

 2,注册页面

 3,记录,功能页面

 4,mysql提前存进去的数据(user,data)

 5,mysql表的结构(user,data)

 

1,登录页面swing

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.awt.event.*;
/**
Created by Liang 2023/4/23
**/
public class Login extends JFrame implements ActionListener{
		JTextField user;
		JPasswordField password;
		public Login(){
 
       
        super("Diary");
		
       
        this.setSize(900,507);
 
       
        this.setLayout(null);
 
        
        JLabel diary = new JLabel("Welcome to the Diary");
        diary.setForeground(new Color(0x0010FF));
        diary.setFont(new Font("黑体", Font.PLAIN,50));
        diary.setBounds(200,50,800,100);
        this.add(diary);
 
   
        JLabel textUser = new JLabel("用户名:");
        textUser.setForeground(new Color(0xFF0000));
        textUser.setFont(new Font("黑体", Font.PLAIN,30));
        textUser.setBounds(200,140,200,100);
        this.add(textUser);
 
      
         user = new JTextField(20);
        user.setFont(new Font("黑体", Font.PLAIN,18));
        user.setSelectedTextColor(new Color(0xFF0000));
        user.setBounds(330,170,280,40);
        this.add(user);
 
   
        JLabel textPassword = new JLabel("密码  :");
        textPassword.setForeground(new Color(0xFF0000));
        textPassword.setFont(new Font("黑体", Font.PLAIN,30));
        textPassword.setBounds(200,200,200,100);
        this.add(textPassword);
 
       
         password = new JPasswordField(20);
        password.setBounds(330,230,280,40);
        this.add(password);
 
        
        JButton jButton = new JButton("登录");
        jButton.setForeground(new Color(0x023BF6));
        jButton.setBackground(new Color(0x38FF00));
        jButton.setFont(new Font("黑体", Font.PLAIN,20));
        jButton.setBorderPainted(false);
        jButton.setBounds(200,330,100,50);
        this.add(jButton);
 
        
        JButton register = new JButton("注册");
        register.setForeground(new Color(0x0029FF));
        register.setBackground(new Color(0xECA871));
        register.setFont(new Font("黑体", Font.PLAIN,20));
        register.setBorderPainted(false);
        register.setBounds(400,330,100,50);
        this.add(register);
		
		JButton exit=new JButton("退出");
		exit.setForeground(Color.WHITE);
        exit.setBackground(Color.RED);
        exit.setFont(new Font("黑体", Font.PLAIN,20));
        exit.setBorderPainted(false);
        exit.setBounds(600,330,100,50);
		this.add(exit);
		
        jButton.addActionListener(this);
		
		register.addActionListener(this);
		
		exit.addActionListener(this);
		
		jButton.setActionCommand("登录");
		
		register.setActionCommand("注册");
     
		exit.setActionCommand("退出");
		
        this.setLocationRelativeTo(null);
 
       
        
 
     
        this.setResizable(false);
 
    
        this.setVisible(true);
		}
		
	
		public void actionPerformed(ActionEvent e){
			if(e.getActionCommand().equals("登录")){
				
			int id=Integer.parseInt(user.getText());
			int ps=Integer.parseInt(String.valueOf(password.getPassword()));
			System.out.println(id+"  "+ps);
			if(SqlConnect.LoginSql(id,ps)==1){
			
			JOptionPane.showMessageDialog(null, "Welcome", "登陆成功",JOptionPane.PLAIN_MESSAGE);
				new DiaryPage(id);
		}else{
			JOptionPane.showMessageDialog(null, "登陆失败", "错误",JOptionPane.ERROR_MESSAGE);
		}
		user.setText("");
		password.setText("");
			
		}
		if(e.getActionCommand().equals("注册")){
			 new Register();
			
			
		}
		if(e.getActionCommand().equals("退出")){
			System.exit(0);
		}
	}
	public static void main(String args[]){
		new Login();
	}
}

2,注册页面

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.awt.event.*;
/**
create by Liang 2023/4/23
**/
public class Register extends JFrame implements ActionListener{
		Choice cC = new Choice();
		Choice cC2= new Choice();
		JPanel panel = new JPanel();
		JLabel userLabel = new JLabel("User:");          
		JTextField userText = new JTextField();           
		JLabel passLabel = new JLabel("Password:");        
		JTextField passText = new JTextField(); 		     
		JButton registerButton = new JButton("register"); 
		
	  public Register() {
       super("Register");
        this.setSize(300, 300);
        this.setLocationRelativeTo(null);                     
        this.add(panel);                                      
		this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        placeComponents(panel);                                
        this.setVisible(true); 
		registerButton.addActionListener(this);
		registerButton.setActionCommand("register");
	 }

    
   
    private void placeComponents(JPanel panel) {

        panel.setLayout(null); 

       
        userLabel.setBounds(30, 30, 80, 25);
        panel.add(userLabel);

        userText.setBounds(105, 30, 165, 25);
        panel.add(userText);


        passLabel.setBounds(30, 60, 80, 25);
        panel.add(passLabel);
   
        passText.setBounds(105, 60, 165, 25);
        panel.add(passText);

   
        
        registerButton.setBounds(120, 100, 80, 25);
        panel.add(registerButton);
		
		
		JLabel jlabel=new JLabel("选择出生日期");
		cC.add("2023-1-1");
		cC.add("1999-1-21");
		cC.add("1999-1-22");
		cC.add("1999-1-23");
		cC.add("2022-4-24");
		cC.add("2023-4-23");
		JPanel jpanel=new JPanel();
		jpanel.setBounds(30,120,80,50);
		jpanel.add(jlabel);
		jpanel.add(cC);
		
		
		JLabel jlabel2=new JLabel("选择性别");
		cC2.add("男");
		cC2.add("女");
		JPanel jpanel2=new JPanel();
		jpanel2.setBounds(200,120,80,50);
		jpanel2.add(jlabel2);
		jpanel2.add(cC2);
		
	
		panel.add(jpanel);
		panel.add(jpanel2);
    }
	public void actionPerformed(ActionEvent e)
	{
		if(e.getActionCommand().equals("register"))
		{
			int id=Integer.parseInt(userText.getText());
			int ps=Integer.parseInt(passText.getText());
			String date=cC.getSelectedItem();
			String sex=cC2.getSelectedItem();
			if(SqlConnect.ReqisterSql(id,ps,date,sex)==0)
			{
				JOptionPane.showMessageDialog(null, "输入错误", "提示框",JOptionPane.ERROR_MESSAGE);
			}else{
				JOptionPane.showMessageDialog(null, "输入正确", "提示框",JOptionPane.PLAIN_MESSAGE);
			}
		}
	}
	
	


	
}


3,操作日记页面和实现功能

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import javax.swing.text.*;
import java.io.*;
import java.awt.image.*;
import javax.imageio.*;
import java.time.*;
import java.time.format.*;
/**
create by Liang 2023/4/23
**/
@SuppressWarnings("unchecked")
public class DiaryPage extends JFrame  {
			private JTextArea contentTextArea;
			int id;
			Object[] options;  
			JTextPane textPane = new JTextPane();
			JScrollPane scrollPane;
			String filePath;
			ArrayList arr2;
			ArrayList arr3= new ArrayList();
	
			public DiaryPage(int id) {
				super("Diary");
				
				this.id=id;
				JPanel panel = new JPanel(new BorderLayout());
				add(panel);
				
				FileDialog fileDialog = new FileDialog(this, "本地文件");
				JMenuBar menuBar = new JMenuBar();
				JMenu fileMenu = new JMenu("菜单");
				JMenuItem saveMenuItem = new JMenuItem("保存");
				JMenuItem exitMenuItem = new JMenuItem("退出");
				JMenuItem changeMenuItem = new JMenuItem("修改");
				exitMenuItem.addActionListener(new ActionListener() {		//退出
					@Override
					public void actionPerformed(ActionEvent e) {
						System.exit(0);
					}
				});
				saveMenuItem.addActionListener(new ActionListener() {		//保存
					@Override
					public void actionPerformed(ActionEvent e) {
					
						String filePath="";
						for(int i=0;i<arr3.size();i++){
							filePath=filePath+arr3.get(i)+"#";
						}	
						String values=textPane.getText();
						
						values =values.replaceAll("ignored text","");
						System.out.println(values);
						if(filePath=="")
						{
							SqlConnect.contentSave(id,values,null);
						}else{
						SqlConnect.contentSave(id,values,filePath);
						}
						
						ArrayList a= SqlConnect.showDate(id);				//校准时间
						options=new Object[a.size()];
						a.toArray(options);
						filePath=null;
						}
						});
		
			changeMenuItem.addActionListener(new ActionListener() {		//修改
            @Override
            public void actionPerformed(ActionEvent e) {
				ArrayList a= SqlConnect.showDate(id);				//校准时间
				options=new Object[a.size()];
				a.toArray(options);
				
				textPane.setText(""); // 将文本设为空字符串

			    String s = (String) JOptionPane.showInputDialog(null,"请选择修改日期:\n", "日期", JOptionPane.PLAIN_MESSAGE, new ImageIcon("xx.png"), options, "xx");
				if(s!=null){
					
				arr2=SqlConnect.showData(id,s);}
				if(arr2.get(1)!=null){
				
				Style style=textPane.getStyledDocument().addStyle(null,null);
				
				String FilePath=(String)arr2.get(1);
				String [] path=FilePath.split("#");
				Image image=null;
				for(int i=0;i<path.length;i++){
				File file=new File(path[i]);
				try
				{
				image=ImageIO.read(file);
				}
				catch (Exception ssss)
				{
				}
				
				
				ImageIcon  imageIcon =new ImageIcon(image);
				
				imageIcon.setImage(imageIcon.getImage().getScaledInstance(200, -1, Image.SCALE_SMOOTH)); //设置图片大小
			 
			  
				StyleConstants.setIcon(style,imageIcon);
			
				StyleConstants.setAlignment(style, StyleConstants.ALIGN_RIGHT);
			  
				try{
				 textPane.getStyledDocument().insertString(textPane.getStyledDocument().getLength(), "ignored text", style);
				 }
				 catch (Exception es){
					 es.printStackTrace();
				 }finally{
					 
				 }
			     }  
				 try
				 {
				 textPane.getStyledDocument().insertString(textPane.getStyledDocument().getLength(), (String)arr2.get(0), null);
				 }
				 catch (Exception sss)
				 {
					 
				 }
				
				
				}else{
					try
					{
					textPane.getStyledDocument().insertString(textPane.getStyledDocument().getLength(), (String)arr2.get(0), null);
					}
					catch (Exception exx)
					{
						exx.printStackTrace();
					}
					
					}
								
					
				 scrollPane.setViewportView(textPane);
				
				}
        });
        fileMenu.add(saveMenuItem);
        fileMenu.addSeparator();
        fileMenu.add(exitMenuItem);
		fileMenu.addSeparator();
		
		
		
		
		
		
		
		
		
		fileMenu.add(changeMenuItem);
        menuBar.add(fileMenu);
        setJMenuBar(menuBar);



        contentTextArea = new JTextArea();
        contentTextArea.setLineWrap(true);  // 设置自动换行
		 
         scrollPane = new JScrollPane(contentTextArea);
        panel.add(scrollPane, BorderLayout.CENTER);
		
       
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        panel.add(buttonPanel, BorderLayout.SOUTH);

       
     
        JButton imageButton = new JButton("添加图片");
        imageButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
			   fileDialog.setVisible(true);
        
        filePath =  fileDialog.getDirectory() + fileDialog.getFile();
		
		
		arr3.add(filePath);
		
        StyledDocument doc = textPane.getStyledDocument();
		
		Style styles=textPane.getStyledDocument().addStyle(null,null);	
		ImageIcon imageIcon = new ImageIcon(filePath);
		imageIcon.setImage(imageIcon.getImage().getScaledInstance(200, -1, Image.SCALE_SMOOTH)); //设置图片大小
		StyleConstants.setIcon(styles,imageIcon);
		StyleConstants.setAlignment(styles, StyleConstants.ALIGN_CENTER);
		

        try {
			        
           doc.insertString(doc.getLength(), "  ", styles); 
           		
        } catch (BadLocationException eeee) {
            eeee.printStackTrace();
        }

      
        scrollPane.setViewportView(textPane);
					
			   
            }
        });
        buttonPanel.add(imageButton);

       
        setSize(600, 400);
        setLocationRelativeTo(null);
       this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setVisible(true);
		LocalDate date = LocalDate.now();
		
		int month = date.getMonthValue();			//判断生日
		int day =date.getDayOfMonth();
		
		String birthday=SqlConnect.getbd(id);
		DateTimeFormatter fmt =DateTimeFormatter.ofPattern("yyyy-MM-dd");
		LocalDate date2=LocalDate.parse(birthday,fmt);
		int month2 = date2.getMonthValue();
		int day2 =date2.getDayOfMonth();
		if(month==month2 && day2==day){
		JOptionPane.showMessageDialog(null, "生日快乐", "官方提示",JOptionPane.PLAIN_MESSAGE);}
    }

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

  

	
}

4,链接数据库和操作数据库

import java.sql.*;
import java.util.*;
import java.io.*;
import java.awt.*;
import javax.imageio.*;
import javax.swing.*;
/**
create by Liang 2023/4/23
**/
@SuppressWarnings("unchecked")
class SqlConnect 
{		
		static Connection connect;
		static  String url;
		static  int rows;
		static Statement statement;
		static ResultSet result ;
		public static int ReqisterSql(int id,int ps,String bd,String sex){				//注册
		try{
		url = "jdbc:mysql://localhost:3306/user?useUnicode=true&characterEncoding=UTF-8";
		connect=DriverManager.getConnection(url,"root","hsp");
		rows=0;
		Class.forName("com.mysql.jdbc.Driver");	
		String sql="insert into user values("+id+","+ps+",'"+bd+"','"+sex+"')";	
		Statement statement=connect.createStatement();
		 rows=statement.executeUpdate(sql);
		statement.close();
		connect.close();
		}
		catch (Exception e){
			e.printStackTrace();
		}

		if(rows!=0){
			return 1;
		}
		return 0;
		
	}
	public static int LoginSql(int id,int ps){								//登录
		try{
			url = "jdbc:mysql://localhost:3306/user?useUnicode=true&characterEncoding=UTF-8";
			connect=DriverManager.getConnection(url,"root","hsp");
			Class.forName("com.mysql.jdbc.Driver");	
			int rows=0;
			String sql="select * from user";
			statement=connect.createStatement();
			result =statement.executeQuery(sql);
			while(result.next())
			{
				int id2=result.getInt("id");
				int ps2=result.getInt("ps");
				if(id==id2 && ps2==ps)
				{
						result.close();
						statement.close();
						connect.close();
						return 1;
					}
				}
				result.close();
				statement.close();
				connect.close();
				
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return 0; 
		
	}
	public static int contentSave(int id,String content,String in){
		try																					//保存
		{
		url = "jdbc:mysql://localhost:3306/user?useUnicode=true&characterEncoding=UTF-8";
		connect=DriverManager.getConnection(url,"root","hsp");
		rows=0;
		Class.forName("com.mysql.jdbc.Driver");	
		String sql="insert into data(id,content,picture) values(?,?,?)";	
		PreparedStatement statement=connect.prepareStatement(sql);
		statement.setInt(1,id);
		statement.setString(2,content);
		if(in!=null){
		statement.setString(3,in);}
		else{
			statement.setString(3,null);
		}
		rows=statement.executeUpdate();
		statement.close();
		connect.close();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

		if(rows!=0)
		{
			return 1;
		}
		return 0;
	}
	
	
	
	
	
				
	public static ArrayList showDate(int id){							//取出图片和内容
		ArrayList<String> list=new ArrayList<>();
		int i=0;
		try
		{
		url = "jdbc:mysql://localhost:3306/user?useUnicode=true&characterEncoding=UTF-8";
		connect=DriverManager.getConnection(url,"root","hsp");
		Class.forName("com.mysql.jdbc.Driver");	
		int rows=0;
		String sql="select * from data";
		 statement=connect.createStatement();
		 result =statement.executeQuery(sql);
		 while(result.next()){
			int id2=result.getInt("id");
			if(id2==id){		
			String time=result.getString("login_time");
			list.add(time);
			}
		}
				result.close();
				statement.close();
				connect.close();		
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return list;
		
	}
	
	public static ArrayList showData(int id,String date){					//同步时间
		ArrayList arr=new ArrayList();				
		try
		{
			url = "jdbc:mysql://localhost:3306/user?useUnicode=true&characterEncoding=UTF-8";
			connect=DriverManager.getConnection(url,"root","hsp");
			Class.forName("com.mysql.jdbc.Driver");	
			int rows=0;
			String sql="select * from data";
			 statement=connect.createStatement();
			 result =statement.executeQuery(sql);
			while(result.next()){
			int id2=result.getInt("id");
			String date2=result.getString("login_time");
			
			if(id2==id && date2.equals(date))
			{
				
				String content=result.getString("content");
				
				String s=result.getString("picture");
				if(s==null){
					arr.add(content);
					arr.add(null);
					return arr;
				}
				
				 
				 arr.add(content);
				 
				 arr.add(s);
				return arr;
				
			}
			
		}
				result.close();
				statement.close();
				connect.close();		
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return null;
		
		
	}
	
  public static String getbd(int id){									//得到生日
		try
		{
		url = "jdbc:mysql://localhost:3306/user?useUnicode=true&characterEncoding=UTF-8";
		connect=DriverManager.getConnection(url,"root","hsp");
		Class.forName("com.mysql.jdbc.Driver");	
		
		String sql="select * from user";
		 statement=connect.createStatement();
		 result =statement.executeQuery(sql);
		 while(result.next()){
			int id2=result.getInt("id");
			if(id2==id){		
			String time=result.getString("bd");
			return time;
			}
		}
				result.close();
				statement.close();
				connect.close();		
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		
		return null;
	}
	
	
	
		
}

  • 12
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值