Java实战(计算机、文件拷贝、图书管理)

只含部分代码

//计算机
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.DecimalFormat;

public class test_5_1 extends JFrame {
    // 定义面板组件
    JPanel jp1 = null;
    JPanel jp2 = null;
    JPanel jp3 = null;
    JPanel jp4 = null;
    JPanel jp5 = null;
    JPanel jp6 = null;

    public static void main(String[] args) {

        test_5_1 window = new test_5_1();
    }

    public test_5_1() {

        jp1 = new JPanel();
        jp2 = new JPanel();
        jp3 = new JPanel();
        jp4 = new JPanel();
        jp5 = new JPanel();
        jp6 = new JPanel();

        JLabel jl1 = new JLabel("简易计算器");
        JLabel jl2 = new JLabel("运算数一");
        JLabel jl3 = new JLabel("运算数二");
        JLabel jl4 = new JLabel("运算结果");
        JLabel jl5 = new JLabel("       ");
        JTextField jtf1 = new JTextField(8);
        JTextField jtf2 = new JTextField(8);
        JTextField jtf3 = new JTextField(8);


        JButton jb1 = new JButton("相加");
        jb1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
//                double num1 = Double.parseDouble(jtf1.getText());
//                double num2 = Double.parseDouble(jtf2.getText());
//                jtf3.setText(String.valueOf(num1 + num2));
                String num1 = jtf1.getText().trim();
                String num2 = jtf2.getText().trim();
                double num3 = Double.parseDouble(num1) + Double.parseDouble(num2);
                DecimalFormat decimalFormat = new DecimalFormat("#.######");
                jtf3.setText(decimalFormat.format(num3));
            }
        });

        JButton jb2 = new JButton("相减");
        jb2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                String num1 = jtf1.getText().trim();
                String num2 = jtf2.getText().trim();
                double num3 = Double.parseDouble(num1) - Double.parseDouble(num2);
                DecimalFormat decimalFormat = new DecimalFormat("#.######");
                jtf3.setText(decimalFormat.format(num3));

            }
        });

        JButton jb3 = new JButton("全部清零");
        jb3.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                jtf1.setText("");
                jtf2.setText("");
                jtf3.setText("");
            }
        });

        // 添加组件到面板
        jp1.add(jl1);
        jp2.add(jl2);
        jp2.add(jtf1);
        jp3.add(jl3);
        jp3.add(jtf2);
        jp4.add(jl4);
        jp4.add(jtf3);
        jp5.add(jb1);
        jp5.add(jl5);
        jp5.add(jb2);
        jp6.add(jb3);

        // 添加面板到窗体(框架)
        this.add(jp1);
        this.add(jp2);
        this.add(jp3);
        this.add(jp4);
        this.add(jp5);
        this.add(jp6);

        // 设置contentPane布局
        this.setLayout(new GridLayout(6, 1, 1, 1));
        this.setTitle("简单计算器"); // 标题
        this.setSize(300, 350); // 窗口大小
        this.setLocationRelativeTo(null); // 窗口居中显示
        this.setResizable(false); // 不可缩放
        this.setVisible(true); // 窗口可见
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// 关闭窗口时退出程序
    }
}







//计算机监听
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.DecimalFormat;


public class test_5_2 extends JFrame {
    // 定义面板组件
    JPanel jp1 = null;
    JPanel jp2 = null;
    JPanel jp3 = null;
    JPanel jp4 = null;
    JPanel jp5 = null;
    JPanel jp6 = null;

    public static void main(String[] args) {

        test_5_2 window = new test_5_2();
    }

    public test_5_2() {

        jp1 = new JPanel();
        jp2 = new JPanel();
        jp3 = new JPanel();
        jp4 = new JPanel();
        jp5 = new JPanel();
        jp6 = new JPanel();

        JLabel jl1 = new JLabel("简易计算器");
        JLabel jl2 = new JLabel("运算数一");
        JLabel jl3 = new JLabel("运算数二");
        JLabel jl4 = new JLabel("运算结果");
        JLabel jl5 = new JLabel("       ");
        JTextField jtf1 = new JTextField(8);
        JTextField jtf2 = new JTextField(8);
        JTextField jtf3 = new JTextField(8);


        JButton jb1 = new JButton("相加");


        jb1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                String num1 = jtf1.getText().trim();
                String num2 = jtf2.getText().trim();

                if (num1.isEmpty() || num2.isEmpty()) { // 运算数未输入
                    JOptionPane.showMessageDialog(null, "请输入运算数!", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                int dot1 = num1.indexOf(".");
                int dot2 = num2.indexOf(".");
                if (dot1 >= 0 && num1.substring(dot1 + 1).indexOf(".") >= 0 || dot2 >= 0 && num2.substring(dot2 + 1).indexOf(".") >= 0) { // 小数点个数超过1个
                    JOptionPane.showMessageDialog(null, "小数点的个数不能超过1个!", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                if (!isNumeric(num1) || !isNumeric(num2)) { // 非法字符
                    JOptionPane.showMessageDialog(null, "输入的数据含有非法字符!", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                if (num1.startsWith(".") || num1.endsWith(".") || num2.startsWith(".") || num2.endsWith(".")) { // 小数点位置不正确
                    JOptionPane.showMessageDialog(null, "小数点的位置不正确!", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }



//                    double result = Double.parseDouble(num1) + Double.parseDouble(num2);
//                    jtf3.setText(String.valueOf(result));
                double num3 = Double.parseDouble(num1) + Double.parseDouble(num2);
                DecimalFormat decimalFormat = new DecimalFormat("#.######");
                jtf3.setText(decimalFormat.format(num3));
            }
        });

        JButton jb2 = new JButton("相减");
        jb2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                String num1 = jtf1.getText().trim();
                String num2 = jtf2.getText().trim();

                if (num1.isEmpty() || num2.isEmpty()) { // 运算数未输入
                    JOptionPane.showMessageDialog(null, "请输入运算数!", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                int dot1 = num1.indexOf(".");
                int dot2 = num2.indexOf(".");
                if (dot1 >= 0 && num1.substring(dot1 + 1).indexOf(".") >= 0 || dot2 >= 0 && num2.substring(dot2 + 1).indexOf(".") >= 0) { // 小数点个数超过1个
                    JOptionPane.showMessageDialog(null, "小数点的个数不能超过1个!", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                if (!isNumeric(num1) || !isNumeric(num2)) { // 非法字符
                    JOptionPane.showMessageDialog(null, "输入的数据含有非法字符!", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                if (num1.startsWith(".") || num1.endsWith(".") || num2.startsWith(".") || num2.endsWith(".")) { // 小数点位置不正确
                    JOptionPane.showMessageDialog(null, "小数点的位置不正确!", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

//                    double result = Double.parseDouble(num1) - Double.parseDouble(num2);
//                    jtf3.setText(String.valueOf(result));
                double num3 = Double.parseDouble(num1) - Double.parseDouble(num2);
                DecimalFormat decimalFormat = new DecimalFormat("#.######");
                jtf3.setText(decimalFormat.format(num3));
            }

        });

        JButton jb3 = new JButton("全部清零");
        jb3.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                jtf1.setText("");
                jtf2.setText("");
                jtf3.setText("");
            }
        });


        // 添加组件到面板
        jp1.add(jl1);
        jp2.add(jl2);
        jp2.add(jtf1);
        jp3.add(jl3);
        jp3.add(jtf2);
        jp4.add(jl4);
        jp4.add(jtf3);
        jp5.add(jb1);
        jp5.add(jl5);
        jp5.add(jb2);
        jp6.add(jb3);

        // 添加面板到窗体(框架)
        this.add(jp1);
        this.add(jp2);
        this.add(jp3);
        this.add(jp4);
        this.add(jp5);
        this.add(jp6);

        // 设置contentPane布局
        this.setLayout(new GridLayout(6, 1, 1, 1));
        this.setTitle("简单计算器"); // 标题
        this.setSize(300, 350); // 窗口大小
        this.setLocationRelativeTo(null); // 窗口居中显示
        this.setResizable(false); // 不可缩放
        this.setVisible(true); // 窗口可见
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// 关闭窗口时退出程序
    }

    public boolean isNumeric(String str) {
        if (str.isEmpty()) {
            return false;
        }

        int i = 0;
        if (str.charAt(0) == '-') {
            if (str.length() > 1 && Character.isDigit(str.charAt(1))) {
                i++;
            } else {
                return false;
            }
        }

        boolean hasDot = false; // 是否出现了小数点
        for (; i < str.length(); i++) {
            char ch = str.charAt(i);
            if (ch == '.') {
                if (hasDot) { // 如果已经出现过小数点,返回false
                    return false;
                }
                hasDot = true;
            } else if (!Character.isDigit(ch)) {
                return false;
            }
        }

        return true;
    }

}




1、编写一个 Java 程序,能将硬盘上某个文件夹下的一个文件拷贝到另一个指定的文件 
夹中。注意,测试时要能通过小文件和大文件测试,验证你的程序具有通用性,保证不管 
文件大小都要能拷贝成功,且速度不会太慢。 








import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Scanner;
import java.io.InputStream;
import java.io.OutputStream;

public class test_6_1 {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        String str1 = sc.next();
        String str2 = sc.next();
        String str3 = sc.next();

//        C:/Users/chenshiyu/Desktop/文件1
//        C:/Users/chenshiyu/Desktop/文件2
//        123.png
//        test.zip
//        String sourceDir = str1;
//        String targetDir = str2;

        try {



            // 获取源文件夹和目标文件夹的目录
            File sourceDirFile = new File(str1);
            File targetDirFile = new File(str2);

            // 如果源文件夹不存在,则创建
            if (!sourceDirFile.exists()) {
                sourceDirFile.mkdir();
            }

            // 如果目标文件夹不存在,则创建
            if (!targetDirFile.exists()) {
                targetDirFile.mkdir();
            }


            long startTime = System.currentTimeMillis();
            startTime = System.currentTimeMillis();

            // 获取源文件的路径和文件名
            String sourceFile = str1 + File.separator + str3;

            // 打开输入流读取源文件
            FileInputStream input = new FileInputStream(sourceFile);

            // 打开输出流写入目标文件
            FileOutputStream output = new FileOutputStream(str2 + File.separator + str3);

            // 创建缓冲区
            byte[] buffer = new byte[4096];

            // 将文件从输入流写入输出流
            int bytesRead;
            while ((bytesRead = input.read(buffer)) != -1) {
                output.write(buffer, 0, bytesRead);
            }

            // 关闭输入流和输出流
            input.close();
            output.close();

            System.out.println("文件已成功复制。");
            System.out.println("缓冲字节流使用byte缓冲数组完成复制,耗时"+(System.currentTimeMillis()-startTime)+"毫秒");

        } catch (Exception e) {
            System.out.println("复制文件时出现错误:" + e.getMessage());
        }
    }
}


//2、假设已经有一个文本文件中存放着职工的工资记录。每个职工的记录包含姓名、工 
//资、津贴三项。每条记录可以存放于一行(三项之间的间隔符可以自己决定),也可以将 
//每条记录的三项依次分别存放在文本文件中的每一行。请设计一个程序,可以让用户选择 
//打开这个文件查看其内容。也可以让用户选择批量给职工加工资(例如把每个职工的工资 
//增加一定比例如 10%),又存回原来的文件。注意:(1)职工工资记录的条数可能成百上 
//千条甚至更多,要能通过你所设计的程序,批量地一次性修改所有职工工资记录;(
//2) 
//Java 中有 JTbale 之类的组件,可以以表格等形式较好的展示数据。如果想使得自己设计的 
//软件外观更漂亮交互性更好,可考虑选择使用(非必须),具体用法可查阅相关帮助文 
//档。


import javax.swing.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;

public class test_6_2_1 {
    public static void main(String args[]) {
        File5Frm file5Frm = new File5Frm();
    }
}

class File5Frm extends Frame implements ActionListener {
    FileDialog sv, op;
    JButton button1, button2, button3, button4,button5;
    JTextArea textArea = new JTextArea();

    File5Frm() {
        super("工资记录修改器");
        setLayout(null);
        setBackground(Color.GRAY);
        setSize(700, 350);
        setVisible(true);
        button1 = new JButton("打开");
        button2 = new JButton("保存");
        button3 = new JButton("关闭");
        button4 = new JButton("按比例增加");
        button5 = new JButton("按固定增加");
        textArea = new JTextArea("姓名\t工资\t津贴\n");
        add(button1);
        add(button2);
        add(button3);
        add(button4);
        add(button5);
        add(textArea);
        textArea.setBounds(30, 50, 460, 220);
        button1.setBounds(560, 60, 120, 30);
        button2.setBounds(560, 120, 120, 30);
        button3.setBounds(560, 180, 120, 30);
        button4.setBounds(560, 240, 120, 30);
        button5.setBounds(560, 300, 120, 30);
        sv = new FileDialog(this, "保存", FileDialog.SAVE); //保存功能
        op = new FileDialog(this, "打开", FileDialog.LOAD);//打开功能
        button1.addActionListener(this);
        button2.addActionListener(this);
        button3.addActionListener(this);
        button4.addActionListener(this);
        button5.addActionListener(this);
        addWindowListener(new WindowAdapter() {//定义事件适配器实现图形界面窗口的关闭功能
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }

    public void actionPerformed(ActionEvent e) {//界面上的事件处理
        if (e.getSource() == button1) {
            String str;
            op.setVisible(true);
            try {//将文件打开读取到界面上的TextArea组件中显示出来
                File f1 = new File(op.getDirectory(), op.getFile());
                FileReader fr = new FileReader(f1);
                BufferedReader br = new BufferedReader(fr);
                textArea.setText("");
                while ((str = br.readLine()) != null) textArea.append(str + '\n');
                fr.close();
            } catch (Exception e1) {
            }
        }
        if (e.getSource() == button2) {//如果点击的是save按钮
            sv.setVisible(true);
            try {//将TextArea中的内容写入到文件中保存
                File fl = new File(sv.getDirectory(), sv.getFile());
                FileWriter fw = new FileWriter(fl);
                BufferedWriter bw = new BufferedWriter(fw);
                String gt = textArea.getText();
                bw.write(gt, 0, gt.length());
                bw.flush();
                fw.close();
            } catch (Exception e1) {
            }
        }
        if (e.getSource() == button3) {//如果点击的是close按钮
            System.exit(0);
        }
        if (e.getSource() == button4) {//如果点击的比例增加
            String gt = textArea.getText();
            String s[];
            s = gt.split("\t|\n");
            textArea.setText("姓名\t工资\t津贴\n");
            try {
                for (int i = 1; i < s.length; i++) {
                    s[3 * i + 1] = String.valueOf((int) (Integer.parseInt((s[3 * i + 1])) * 1.1));
                    textArea.append(s[3 * i + 0] + "\t");
                    textArea.append(s[3 * i + 1] + "\t");
                    textArea.append(s[3 * i + 2] + "\n");
                }
            } catch (Exception e1) {
            }
        }
        if (e.getSource() == button5) {//如果点击的工资增加
            String gt = textArea.getText();
            String s[];
            s = gt.split("\t|\n");
            textArea.setText("姓名\t工资\t津贴\n");
            try {
                for (int i = 1; i < s.length; i++) {
                    s[3 * i + 1] = String.valueOf((int) (Integer.parseInt((s[3 * i + 1])) +100));
                    textArea.append(s[3 * i + 0] + "\t");
                    textArea.append(s[3 * i + 1] + "\t");
                    textArea.append(s[3 * i + 2] + "\n");
                }
            } catch (Exception e1) {
            }
        }
    }
}





//线程


//
//public class test_7_1 {
//    public static void main(String[] args) {
//        MyThread01 m1 = new MyThread01();
//        Thread thread1 = new Thread(m1,"2100301210");
//        Thread thread2 = new Thread(m1,"chenshiyu");
        thread1.setName("2100301210");
        thread2.setName("陈世宇");
//        thread1.start();
//        thread2.start();
//    }
//}
//
//class MyThread01 implements Runnable {
//    int num = 1;
//
//    public void run() {
//        synchronized (this) {
//            while (true) {
//                // 唤醒wait()的一个或所有线程
//                notify();
//                if (num <= 10) {
//                    System.out.println(Thread.currentThread().getName() );
//                    num++;
//                } else {
//                    break;
//                }
//                try {
//                    // wait会释放当前的锁,让另一个线程可以进入
//                    wait();
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//    }
//}



public class test_7_1 {
    public static void main(String[] args) {
        MyThread01 m1 = new MyThread01();
//        MyThread01 m2 =new MyThread01();
        Thread thread1 = new Thread(m1,"2100301210");
        Thread thread2 = new Thread(m1,"chenshiyu");

        thread1.start();
        thread2.start();
    }
}

class MyThread01 implements Runnable {
    int num = 1;
    public void run() {

                while (true) {
                    if (num <= 4) {
                        num++;
                        System.out.println(Thread.currentThread().getName() );

                    } else {
                        break;
                    }
                }
    }
}

//import java.util.concurrent.locks.Lock;
//import java.util.concurrent.locks.ReentrantLock;
//
//public class test_7_1 {
//    public static void main(String[] args) {
//        MyThread01 m1 = new MyThread01();
//        MyThread01 m2 =new MyThread01();
//        Thread thread1 = new Thread(m1,"2100301210");
//        Thread thread2 = new Thread(m2,"chenshiyu");
//        thread1.start();
//        thread2.start();
//    }
//}
//
//class MyThread01 implements Runnable {
//    Lock lock=new ReentrantLock();
//    int num = 1;
//    public void run() {
//        lock.lock();
//        try{
//            while (true) {
//                if (num <= 4) {
//                    num++;
//                    System.out.println(Thread.currentThread().getName() );
//
//                } else {
//                    break;
//                }
//
//            }
//        }catch (Exception e){
//        }finally {
//            lock.unlock();
//        }
//    }
//}







//登录
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class task {
	public static void main(String[] args) {
		//第(1)处要添加的代码起始  (2分)
		MyWindow t=new MyWindow();
		t.setSize(300, 250);//此代码可以写在第(2)处
		t.setVisible(true); //此代码可以写在第(2)处
	    //第(1)处要添加的代码结束
       t.setDefaultCloseOperation(MyWindow.EXIT_ON_CLOSE);
	}
}
class MyWindow extends JFrame implements ActionListener
{
	JLabel lb1=new JLabel("账号:");
	JLabel lb2=new JLabel("密码:");
	JTextField txtUid=new JTextField(20);
	JPasswordField txtPwd=new JPasswordField(20);
	JButton btnLogin=new JButton("登录");
	JButton btnReset=new JButton("重置");
	public MyWindow()
	{
		GridLayout layout=new GridLayout(5,1);
		setLayout(layout);
		add(new JLabel(""));
		JPanel pnl=new JPanel();
		pnl.add(lb1);
		pnl.add(txtUid);
		add(pnl);
		pnl=new JPanel();
		pnl.add(lb2);
		pnl.add(txtPwd);
		add(pnl);
		pnl=new JPanel();
		pnl.add(btnLogin);
		pnl.add(btnReset);
		add(pnl);
		add(new JLabel(""));
		//第(2)处要添加的代码起始(本部分3分)
		btnLogin.addActionListener(this);
		btnReset.addActionListener(this);
		//第(2)处要添加的代码结束
		setTitle("用户登录");
		
	}
	
	public void actionPerformed(ActionEvent e) {
		//第(3)处要添加的代码起始(本部分10分)
		String msg="";
		if(e.getSource()==btnLogin)
		{
			if(txtUid.getText().equals("admin")&&txtPwd.getText().equals("java")){
				msg="登录成功";
			}
			else	{
				msg="用户名或密码错";
			}
			JOptionPane.showMessageDialog(this, msg);	
		}
		else if(e.getSource()==btnReset){
			txtUid.setText("");
			txtPwd.setText("");
		}
		//第(3)处要添加的代码结束
	}
}


//素数判断


import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
//import javax.swing.border.*;
//import java.awt.event.*;
import javax.swing.border.EmptyBorder;

public class test extends JFrame {

    private JPanel contentPane;
    private JTextField txtNumber;
    private JButton btnCompute;
    private JTextArea txtAreaResult;
    private BtnComputeActionListener listener;
    private JScrollPane scrollPane;
    private JButton btnExit;

    //第 1 处补充代码开始:定义 isPrime 方法,判断一个数是否为素数(3 分)
    public static boolean isPrime(int n) {
        if (n <= 1) {
            return false;
        }
        for (int i = 2; i <= Math.sqrt(n); i++) {
            if (n % i == 0) {
                return false;
            }
        }
        return true;
    }
    //第 1 处补充代码结束

    public static void main(String[] args) {
        //第 2 处补充代码开始:创建主窗口,显示主窗口(3 分)
        test frame = new test();
        frame.setVisible(true);
        //第 2 处补充代码结束
    }

    public test() {
        setResizable(false);
        setTitle("素数判断程序");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 612, 314);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
        JLabel lblNewLabel = new JLabel("输入一个整数:");
        lblNewLabel.setFont(new Font("宋体", Font.PLAIN, 14));
        getContentPane().add(lblNewLabel);
        txtNumber = new JTextField();
        contentPane.add(txtNumber);
        txtNumber.setColumns(10);
        btnCompute = new JButton("执行判断");
        this.listener = new BtnComputeActionListener();
        //第 3 处补充代码开始:将事件监听器 listener 添加到 “执行判断”按钮上,从而为单击该按钮
        //添加事件处理(2 分)
        btnCompute.addActionListener(this.listener);
        //第 3 处补充代码结束
        contentPane.add(btnCompute);
        scrollPane = new JScrollPane();
        contentPane.add(scrollPane);
        txtAreaResult = new JTextArea();
        scrollPane.setViewportView(txtAreaResult);
        txtAreaResult.setLineWrap(true);
        txtAreaResult.setWrapStyleWord(true);
        txtAreaResult.setColumns(50);
        txtAreaResult.setRows(10);
        btnExit = new JButton("退出");
        btnExit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                //第 4 处补充代码开始(2 分)
                System.exit(0);
                //第 4 处补充代码结束
            }
        });
        contentPane.add(btnExit);
        this.setLocationRelativeTo(null);
    }

    //第 5 处补充代码开始:定义一个实现 ActionListener 接口的内部类,该类用于实现对单击“执行判断”
    private class BtnComputeActionListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            String inputStr = txtNumber.getText();
            try {
                int inputNum = Integer.valueOf(inputStr);
                if (isPrime(inputNum)) {
                    txtAreaResult.setText(inputNum + " 是素数。");
                } else {
                    txtAreaResult.setText(inputNum + " 不是素数。");
                }
            } catch (NumberFormatException exception) {
                txtAreaResult.setText("请输入整数!");
            }
        }
    }
    //第 5 处补充代码结束
}




//图书管理


import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.*;

public class task_2 {

    // 初始化一个空的书籍列表
    private List<Book> bookList = new ArrayList<>();

    // 登录窗口组件
    private JFrame loginFrame;
    private JLabel usernameLabel;
    private JLabel passwordLabel;
    private JTextField usernameField;
    private JPasswordField passwordField;
    private JButton loginButton;

    // 主窗口组件
    private JFrame mainFrame;
    private JLabel titleLabel;
    private JLabel idLabel;
    private JLabel nameLabel;
    private JLabel authorLabel;
    private JLabel yearLabel;
    private JTextField idField;
    private JTextField nameField;
    private JTextField authorField;
    private JTextField yearField;
    private JButton addButton;
    private JButton searchButton;
    private JButton borrowButton;
    private JButton deleteButton;

    public task_2() {
        initializeLoginFrame();
    }

    private void initializeLoginFrame() {
        // 登录窗口标题
        loginFrame = new JFrame("Login");

        // 组件初始化
        usernameLabel = new JLabel("Username:");
        passwordLabel = new JLabel("Password:");
        usernameField = new JTextField();
        passwordField = new JPasswordField();
        loginButton = new JButton("Login");

        // 组件布局
        usernameLabel.setBounds(50, 50, 80, 30);
        passwordLabel.setBounds(50, 100, 80, 30);
        usernameField.setBounds(130, 50, 200, 30);
        passwordField.setBounds(130, 100, 200, 30);
        loginButton.setBounds(150, 150, 100, 30);

        // 登录按钮绑定事件监听器
        loginButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 登录验证逻辑
                if (usernameField.getText().equals("admin") && passwordField.getText().equals("admin")) {
                    // 登录成功后进入主窗口
                    initializeMainFrame();
                    loginFrame.dispose();
                } else {
                    JOptionPane.showMessageDialog(loginFrame, "Incorrect username or password!", "Login Failed", JOptionPane.ERROR_MESSAGE);
                }
            }
        });

        // 添加组件到登录窗口
        loginFrame.add(usernameLabel);
        loginFrame.add(passwordLabel);
        loginFrame.add(usernameField);
        loginFrame.add(passwordField);
        loginFrame.add(loginButton);

        // 日常操作
        loginFrame.setSize(400, 250);
        loginFrame.setLayout(null);
        loginFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        loginFrame.setVisible(true);
    }

    private void initializeMainFrame() {
        // 主窗口标题
        mainFrame = new JFrame("Library Management System");

        // 组件初始化
        titleLabel = new JLabel("Book List");
        titleLabel.setFont(new Font("Arial", Font.BOLD, 24));
        idLabel = new JLabel("Book ID:");
        nameLabel = new JLabel("Book Name:");
        authorLabel = new JLabel("Author:");
        yearLabel = new JLabel("Year:");
        idField = new JTextField();
        nameField = new JTextField();
        authorField = new JTextField();
        yearField = new JTextField();
        addButton = new JButton("Add");
        searchButton = new JButton("Search");
        borrowButton = new JButton("Borrow");
        deleteButton = new JButton("Delete");

        // 组件布局
        titleLabel.setBounds(200, 50, 150, 30);
        idLabel.setBounds(50, 100, 80, 30);
        nameLabel.setBounds(50, 150, 80, 30);
        authorLabel.setBounds(50, 200, 80, 30);
        yearLabel.setBounds(50, 250, 80, 30);
        idField.setBounds(130, 100, 200, 30);
        nameField.setBounds(130, 150, 200, 30);
        authorField.setBounds(130, 200, 200, 30);
        yearField.setBounds(130, 250, 200, 30);
        addButton.setBounds(50, 350, 100, 30);
        searchButton.setBounds(200, 350, 100, 30);
        borrowButton.setBounds(350, 350, 100, 30);
        deleteButton.setBounds(500, 350, 100, 30);

        // 添加图书按钮绑定事件监听器
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                addBook();
            }
        });

        // 查询图书按钮绑定事件监听器
        searchButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                searchBook();
            }
        });

        // 借阅图书按钮绑定事件监听器
        borrowButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                borrowBook();
            }
        });

        // 删除图书按钮绑定事件监听器
        deleteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                deleteBook();
            }
        });

        // 添加组件到主窗口
        mainFrame.add(titleLabel);
        mainFrame.add(idLabel);
        mainFrame.add(nameLabel);
        mainFrame.add(authorLabel);
        mainFrame.add(yearLabel);
        mainFrame.add(idField);
        mainFrame.add(nameField);
        mainFrame.add(authorField);
        mainFrame.add(yearField);
        mainFrame.add(addButton);
        mainFrame.add(searchButton);
        mainFrame.add(borrowButton);
        mainFrame.add(deleteButton);

        // 日常操作
        mainFrame.setSize(700, 500);
        mainFrame.setLayout(null);
        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        mainFrame.setVisible(true);
    }

    // 添加图书
    private void addBook() {
        String id = idField.getText();
        String name = nameField.getText();
        String author = authorField.getText();
        String year = yearField.getText();
        Book book = new Book(id, name, author, year);
        bookList.add(book);
        JOptionPane.showMessageDialog(mainFrame, "Book added successfully!", "Add Book", JOptionPane.INFORMATION_MESSAGE);
    }

    // 查询图书
    private void searchBook() {
        String id = idField.getText();
        for (Book book : bookList) {
            if (book.getId().equals(id)) {
                nameField.setText(book.getName());
                authorField.setText(book.getAuthor());
                yearField.setText(book.getYear());
                return;
            }
        }
        JOptionPane.showMessageDialog(mainFrame, "Book not found!", "Search Book", JOptionPane.ERROR_MESSAGE);
    }

    // 借阅图书
    private void borrowBook() {
        String id = idField.getText();
        for (Book book : bookList) {
            if (book.getId().equals(id)) {
                if (book.isBorrowed()) {
                    JOptionPane.showMessageDialog(mainFrame, "Book has been borrowed!", "Borrow Book", JOptionPane.ERROR_MESSAGE);
                } else {
                    book.setBorrowed(true);
                    JOptionPane.showMessageDialog(mainFrame, "Book borrowed successfully!", "Borrow Book", JOptionPane.INFORMATION_MESSAGE);
                }
                return;
            }
        }
        JOptionPane.showMessageDialog(mainFrame, "Book not found!", "Borrow Book", JOptionPane.ERROR_MESSAGE);
    }

    // 删除图书
    private void deleteBook() {
        String id = idField.getText();
        for (Book book : bookList) {
            if (book.getId().equals(id)) {
                bookList.remove(book);
                JOptionPane.showMessageDialog(mainFrame, "Book deleted successfully!", "Delete Book", JOptionPane.INFORMATION_MESSAGE);
                idField.setText("");
                nameField.setText("");
                authorField.setText("");
                yearField.setText("");
                return;
            }
        }
        JOptionPane.showMessageDialog(mainFrame, "Book not found!", "Delete Book", JOptionPane.ERROR_MESSAGE);
    }

    // 图书类
    private class Book {
        private String id;
        private String name;
        private String author;
        private String year;
        private boolean borrowed;

        public Book(String id, String name, String author, String year) {
            this.id = id;
            this.name = name;
            this.author = author;
            this.year = year;
        }

        public String getId() {
            return id;
        }

        public String getName() {
            return name;
        }

        public String getAuthor() {
            return author;
        }

        public String getYear() {
            return year;
        }

        public boolean isBorrowed() {
            return borrowed;
        }

        public void setBorrowed(boolean borrowed) {
            this.borrowed = borrowed;
        }
    }

    public static void main(String[] args) {
        task_2 libraryManagementSystem = new task_2();
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值