沸羊羊202_5

沸羊羊202_5

下面展示一些 内联代码片
1.多线程交替打印输出:ABABABABAB

// An highlighted block
package com;
import java.util.Scanner;
public class MyThread03 implements Runnable {
    private String name;
    private Object prev;
    private Object self;
    private MyThread03(String name, Object prev, Object self) {
        this.name = name;
        this.prev = prev;
        this.self = self;
    }
    public void run() {
        int count = 5;
        while (count > 0) {
            synchronized (prev) {
                synchronized (self) {
                    System.out.print(name);
                    count--;
                    self.notify();
                }
                try {
                    prev.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        System.exit(0);//退出jvm
    }
    public static void main(String[] args) throws Exception {
        Object a = new Object();
        Object b = new Object();
        Object c = new Object();
        MyThread03 ta = new MyThread03("A", b, a);
        MyThread03 tb = new MyThread03("B", a, b);
        new Thread(ta).start();
        Thread.sleep(100);  //确保按顺序A、B执行
        new Thread(tb).start();
        Thread.sleep(100);
    }
}

下面展示一些 内联代码片
2.多线程输出交替:读书 Rno

package test_7;
public class test_7_1 {
    public static void main(String[] args) {
        MyThread01 m1 = new MyThread01();
        Thread thread1 = new Thread(m1);
        Thread thread2 = new Thread(m1);
        thread1.setName("读书");
        thread2.setName("Rno");
        thread1.start();
        thread2.start();
    }
}

class MyThread01 implements Runnable {
    int num = 1;
    @Override
    public void run() {
        synchronized (this) {
            while (true) {
                // 唤醒wait()的一个或所有线程
                notify();
                if (num <= 20) {
                    System.out.println(Thread.currentThread().getName() );
                    num++;
                } else {
                    break;
                }
                try {
                    // wait会释放当前的锁,让另一个线程可以进入
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

下面展示一些 内联代码片
3.多线程售票

public class ThreadTest implements Runnable {
    // 车票
    private static int ticket = 1;
    /**
     * 加锁对象
     */
    Object lock = new Object();

    /**
     * 重写 Runnable 的 run 方法,调用卖票的操作方法
     * */
    @Override
    public void run() {
        // 限制150张票
        while (ticket <= 20) {
            shopping();
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 卖票的操作方法
     * */
    private void shopping() {
        // 根据lock对象加同步锁(内部会去判断是否有锁)
        synchronized (lock) {
            if (ticket <= 20) {
                System.out.println(Thread.currentThread().getName() + "卖出第" + ticket + "张票!");
                // 票号增加
                ticket++;
            } else {
                // 大于20说明票已经卖完了
                System.out.println("没票了!");
                return;
            }
        }
    }
}
// 内部类调用
class runThread {
    // 执行线程
    public static void main(String[] args) {
        ThreadTest threadTest = new ThreadTest();
        for (int i = 1; i <= 10; i++) {
            new Thread(threadTest, "售票窗口" + i).start();
        }
    }
} 

下面展示一些 内联代码片
4.三角形周长面积计算器

package gui;
//三角形

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


public class task_3 extends JFrame {

    private JPanel contentPane;
    private JTextField textFieldA;
    private JTextField textFieldB;
    private JTextField textFieldC;
    private JLabel lblResultMsg;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    task_3 frame = new task_3();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public task_3() {
        setTitle("三角形计算器");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JLabel lblSideA = new JLabel("边长A:");
        lblSideA.setBounds(69, 52, 54, 15);
        contentPane.add(lblSideA);

        JLabel lblSideB = new JLabel("边长B:");
        lblSideB.setBounds(69, 87, 54, 15);
        contentPane.add(lblSideB);

        JLabel lblSideC = new JLabel("边长C:");
        lblSideC.setBounds(69, 122, 54, 15);
        contentPane.add(lblSideC);

        textFieldA = new JTextField();
        textFieldA.setBounds(133, 49, 163, 21);
        contentPane.add(textFieldA);
        textFieldA.setColumns(10);

        textFieldB = new JTextField();
        textFieldB.setBounds(133, 84, 163, 21);
        contentPane.add(textFieldB);
        textFieldB.setColumns(10);

        textFieldC = new JTextField();
        textFieldC.setBounds(133, 119, 163, 21);
        contentPane.add(textFieldC);
        textFieldC.setColumns(10);

//        JLabel lblStudentID = new JLabel("学号:21123");
//        lblStudentID.setBounds(69, 12, 100, 15);
//        contentPane.add(lblStudentID);
//
//        JLabel lblName = new JLabel("姓名:小明");
//        lblName.setBounds(69, 27, 100, 15);
//        contentPane.add(lblName);



        JButton btnCalculate = new JButton("计算");
        btnCalculate.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                calculateTriangle();
            }
        });
        btnCalculate.setBounds(142, 172, 93, 23);
        contentPane.add(btnCalculate);

        lblResultMsg = new JLabel("");
        lblResultMsg.setBounds(69, 215, 341, 15);
        contentPane.add(lblResultMsg);
    }

    private void calculateTriangle() {
        try {
            double a = Double.parseDouble(textFieldA.getText());
            double b = Double.parseDouble(textFieldB.getText());
            double c = Double.parseDouble(textFieldC.getText());

            if (a + b > c && a + c > b && b + c > a) {
                // 计算周长
                double perimeter = a + b + c;
                // 计算面积
                double p = perimeter / 2; // 半周长
                double area = Math.sqrt(p * (p - a) * (p - b) * (p - c));
                lblResultMsg.setText("该三角形的周长为" + perimeter + ", 面积为" + area);
            } else {
                lblResultMsg.setText("输入的边长无法构成一个三角形");
            }
        } catch (NumberFormatException e) {
            lblResultMsg.setText("输入的边长不合法,请输入有效数字");
        }
    }
}

5.图书管理系统

// package com;
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 LibraryManagementSystem {

    // 初始化一个空的书籍列表
    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 LibraryManagementSystem() {
        initializeLoginFrame();
    }

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

        // 组件初始化
        usernameLabel = new JLabel("用户名:");
        passwordLabel = new JLabel("密码:");
        usernameField = new JTextField();
        passwordField = new JPasswordField();
        loginButton = new JButton("登陆");

        // 组件布局
        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("123456")) {
                    // 登录成功后进入主窗口
                    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("图书管理系统");

        // 组件初始化
        titleLabel = new JLabel("书籍清单");
        titleLabel.setFont(new Font("Arial", Font.BOLD, 24));
        idLabel = new JLabel("书号:");
        nameLabel = new JLabel("书名:");
        authorLabel = new JLabel("作者:");
        yearLabel = new JLabel("年份:");
        idField = new JTextField();
        nameField = new JTextField();
        authorField = new JTextField();
        yearField = new JTextField();
        addButton = new JButton("添加");
        searchButton = new JButton("查询");
        borrowButton = new JButton("借书");
        deleteButton = new JButton("删除");

        // 组件布局
        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) {
        LibraryManagementSystem libraryManagementSystem = new LibraryManagementSystem();
    }
}

6.银行管理系统

package gui;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import java.util.ArrayList;

public class BankManagementSystem implements ActionListener {

    JFrame frame;
    JPanel panel;
    JLabel accountLabel, balanceLabel, nameLabel, emailLabel, depositLabel, withdrawLabel;
    JTextField accountField, balanceField, nameField, emailField, depositField, withdrawField;
    JButton addButton, updateButton, deleteButton, searchButton, depositButton, withdrawButton, clearButton;
    JList accountList;
    ArrayList<Account> accounts;

    DecimalFormat decimalFormat;

    public BankManagementSystem() {
        accounts = new ArrayList<Account>();
        decimalFormat = new DecimalFormat("###,###.##");

        frame = new JFrame("Bank Management System");
        frame.setSize(800, 600);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        panel = new JPanel();
        frame.add(panel);

        panel.setLayout(null);

        accountLabel = new JLabel("Account Number:");
        accountLabel.setBounds(20, 20, 120, 20);
        panel.add(accountLabel);

        accountField = new JTextField();
        accountField.setBounds(140, 20, 120, 20);
        panel.add(accountField);

        balanceLabel = new JLabel("Balance:");
        balanceLabel.setBounds(20, 50, 120, 20);
        panel.add(balanceLabel);

        balanceField = new JTextField();
        balanceField.setBounds(140, 50, 120, 20);
        panel.add(balanceField);

        nameLabel = new JLabel("Name:");
        nameLabel.setBounds(20, 80, 120, 20);
        panel.add(nameLabel);

        nameField = new JTextField();
        nameField.setBounds(140, 80, 120, 20);
        panel.add(nameField);

        emailLabel = new JLabel("Email:");
        emailLabel.setBounds(20, 110, 120, 20);
        panel.add(emailLabel);

        emailField = new JTextField();
        emailField.setBounds(140, 110, 120, 20);
        panel.add(emailField);

        depositLabel = new JLabel("Deposit:");
        depositLabel.setBounds(20, 140, 120, 20);
        panel.add(depositLabel);

        depositField = new JTextField();
        depositField.setBounds(140, 140, 120, 20);
        panel.add(depositField);

        withdrawLabel = new JLabel("Withdraw:");
        withdrawLabel.setBounds(20, 170, 120, 20);
        panel.add(withdrawLabel);

        withdrawField = new JTextField();
        withdrawField.setBounds(140, 170, 120, 20);
        panel.add(withdrawField);

        addButton = new JButton("Add");
        addButton.setBounds(20, 200, 80, 20);
        addButton.addActionListener(this);
        panel.add(addButton);

        updateButton = new JButton("Update");
        updateButton.setBounds(110, 200, 80, 20);
        updateButton.addActionListener(this);
        panel.add(updateButton);

        deleteButton = new JButton("Delete");
        deleteButton.setBounds(200, 200, 80, 20);
        deleteButton.addActionListener(this);
        panel.add(deleteButton);

        searchButton = new JButton("Search");
        searchButton.setBounds(290, 200, 80, 20);
        searchButton.addActionListener(this);
        panel.add(searchButton);

        depositButton = new JButton("Deposit");
        depositButton.setBounds(110, 230, 80, 20);
        depositButton.addActionListener(this);
        panel.add(depositButton);

        withdrawButton = new JButton("Withdraw");
        withdrawButton.setBounds(200, 230, 80, 20);
        withdrawButton.addActionListener(this);
        panel.add(withdrawButton);

        clearButton = new JButton("Clear");
        clearButton.setBounds(290, 230, 80, 20);
        clearButton.addActionListener(this);
        panel.add(clearButton);

        accountList = new JList(accounts.toArray());
        accountList.setBounds(400, 20, 360, 450);
        panel.add(accountList);

        frame.setVisible(true);
    }

    public void actionPerformed(ActionEvent event) {
        if(event.getSource() == addButton) {
            String accountNumber = accountField.getText();
            double balance = Double.parseDouble(balanceField.getText());
            String name = nameField.getText();
            String email = emailField.getText();

            Account account = new Account(accountNumber, balance, name, email);
            accounts.add(account);

            accountList.setListData(accounts.toArray());
            clearFields();
        } else if(event.getSource() == updateButton) {
            int selectedIndex = accountList.getSelectedIndex();
            Account account = accounts.get(selectedIndex);

            double newBalance = Double.parseDouble(balanceField.getText());
            account.setBalance(newBalance);

            String newName = nameField.getText();
            account.setName(newName);

            String newEmail = emailField.getText();
            account.setEmail(newEmail);

            accountList.setListData(accounts.toArray());
            clearFields();
        } else if(event.getSource() == deleteButton) {
            int selectedIndex = accountList.getSelectedIndex();
            accounts.remove(selectedIndex);

            accountList.setListData(accounts.toArray());
            clearFields();
        } else if(event.getSource() == searchButton) {
            String accountNumber = accountField.getText();

            for(Account account : accounts) {
                if(account.getAccountNumber().equals(accountNumber)) {
                    balanceField.setText(decimalFormat.format(account.getBalance()));
                    nameField.setText(account.getName());
                    emailField.setText(account.getEmail());

                    return;
                }
            }

            JOptionPane.showMessageDialog(frame, "Account not found.");
        } else if(event.getSource() == depositButton) {
            int selectedIndex = accountList.getSelectedIndex();
            Account account = accounts.get(selectedIndex);

            double depositAmount = Double.parseDouble(depositField.getText());
            account.deposit(depositAmount);

            balanceField.setText(decimalFormat.format(account.getBalance()));
            depositField.setText("");
        } else if(event.getSource() == withdrawButton) {
            int selectedIndex = accountList.getSelectedIndex();
            Account account = accounts.get(selectedIndex);

            double withdrawAmount = Double.parseDouble(withdrawField.getText());
            boolean isSuccessful = account.withdraw(withdrawAmount);

            if(isSuccessful) {
                balanceField.setText(decimalFormat.format(account.getBalance()));
                withdrawField.setText("");
            } else {
                JOptionPane.showMessageDialog(frame, "Insufficient balance.");
            }
        } else if(event.getSource() == clearButton) {
            clearFields();
        }
    }

    private void clearFields() {
        accountField.setText("");
        balanceField.setText("");
        nameField.setText("");
        emailField.setText("");
        depositField.setText("");
        withdrawField.setText("");
    }

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

class Account {

    private String accountNumber;
    private double balance;
    private String name;
    private String email;

    public Account(String accountNumber, double balance, String name, String email) {
        this.accountNumber = accountNumber;
        this.balance = balance;
        this.name = name;
        this.email = email;
    }

    public String getAccountNumber() {
        return accountNumber;
    }

    public void setAccountNumber(String accountNumber) {
        this.accountNumber = accountNumber;
    }

    public double getBalance() {
        return balance;
    }

    public void setBalance(double balance) {
        this.balance = balance;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public void deposit(double amount) {
        balance += amount;
    }

    public boolean withdraw(double amount) {
        if(amount > balance) {
            return false;
        }

        balance -= amount;
        return true;
    }

    @Override
    public String toString() {
        return "Account " + accountNumber + ", " + name + ", " + email + ", Balance: " + balance;
    }
}

7.点击,你好

package com;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class MyWindow extends JFrame implements ActionListener {
    private JButton button;
    private JLabel label;

    public MyWindow() {
        super("My Window");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setSize(300, 200);

        JPanel panel = new JPanel(new BorderLayout());
        button = new JButton("Click me!");
        button.addActionListener(this);
        panel.add(button, BorderLayout.CENTER);

        label = new JLabel("");
        label.setHorizontalAlignment(JLabel.CENTER);
        panel.add(label, BorderLayout.NORTH);

        this.add(panel);
        this.setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == button) {
            label.setText("你好");
        }
    }

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

8.实验计算器

package gui;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Test_5_2 extends JFrame {
    // 定义面板组件,JPanel是面板容器类,可以加入到JFrame窗体中。
    JPanel jp1 = null;
    JPanel jp2 = null;
    JPanel jp3 = null;
    JPanel jp4 = null;
    JPanel jp5 = null;
    JPanel jp6 = null;
    //文本框,JTextField 用来编辑单行的文本
    // /*
    // * 参数说明:
    // *     text: 默认显示的文本
    // *     columns: 用来计算首选宽度的列数;如果列设置为 0,则首选宽度将是组件实现的自然结果
    // */
    JTextField jtf1 = new JTextField(8);
    JTextField jtf2 = new JTextField(8);
    JTextField jtf3 = new JTextField(8);

    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类的对象可以显示文本、图形或者同时显示二者。
        JLabel jl1 = new JLabel("简易计算器");
        JLabel jl2 = new JLabel("运算数一");
        JLabel jl3 = new JLabel("运算数二");
        JLabel jl4 = new JLabel("运算结果");
        JLabel jl5 = new JLabel("       ");
        //JButton是继承AbstractButton类而来,
        //
        //而AbstractButton本身就是一个抽象类,其中定义了许多组件设置的方法与组件事件驱动方法。
        //创建带有文本的按钮
        JButton jb1 = new JButton("相加");
        jb1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String input1 = jtf1.getText();
                String input2 = jtf2.getText();
                if (checkInput(input1) && checkInput(input2)) {
                    double num1 = Double.parseDouble(input1);
                    double num2 = Double.parseDouble(input2);
                    jtf3.setText(String.valueOf(num1 + num2));
                }
            }
        });
        //创建带有文本的按钮
        JButton jb2 = new JButton("相减");
        jb2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String input1 = jtf1.getText();
                String input2 = jtf2.getText();
                if (checkInput(input1) && checkInput(input2)) {
                    double num1 = Double.parseDouble(input1);
                    double num2 = Double.parseDouble(input2);
                    jtf3.setText(String.valueOf(num1 - num2));
                }
            }
        });
        //创建带有文本的按钮
        JButton jb3 = new JButton("全部清零");
        jb3.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                clearAll();
            }
        });

        // 添加组件到面板
        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);// 关闭窗口时退出程序
    }

    private boolean checkInput(String input) {
//        (1)1 个或 2 个运算数均未输入;
//        (2)输入的数据串中含有除小数点和数字之外的非
//             法字符;
//        (3)输入的数据串中不含有除小数点和数字之外的非法字符,但小数点的个数超
//        过 1 个或小数点的位置在数据的开头或结尾处。
        if (input.isEmpty()) {
            JOptionPane.showMessageDialog(this, "输入不能为空", "错误", JOptionPane.ERROR_MESSAGE);
            return false;
        }
        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            if (c == '.') {
                if (i == 0 || i == input.length() - 1) {
                    JOptionPane.showMessageDialog(this, "小数点位置不正确", "错误", JOptionPane.ERROR_MESSAGE);
                    return false;
                } else if (input.indexOf(".") != input.lastIndexOf(".")) {
                    JOptionPane.showMessageDialog(this, "小数点数量超过一个", "错误", JOptionPane.ERROR_MESSAGE);
                    return false;
                }
            } else if (!Character.isDigit(c)) {
                JOptionPane.showMessageDialog(this, "输入包含非法字符", "错误", JOptionPane.ERROR_MESSAGE);
                return false;
            }
        }
        return true;
    }

    private void clearAll() {
        jtf1.setText("");
        jtf2.setText("");
        jtf3.setText("");
    }
}

9.三角形计算

package ozl;

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


public class task_3 extends JFrame {
	
	private JTextField textFieldA;
	private JTextField textFieldB;
	private JTextField textFieldC;
	private JTextArea textField;
	
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    task_3 frame = new task_3();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public task_3() {
    	
    	setTitle("三角形计算器");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
    	JPanel titlepanel=new JPanel();
        JPanel a=new JPanel();
        JPanel b=new JPanel();
        JPanel c=new JPanel();
        JPanel resultpanel=new JPanel();
        JPanel calculate=new JPanel();
        
        JLabel xuehao=new JLabel("2100301129ozl");
        JLabel alabel=new JLabel("边长A:");
        JLabel blabel=new JLabel("边长B:");
        JLabel clabel=new JLabel("边长C:");
        JLabel resultlabel=new JLabel("计算结果为:");
        
        textFieldA = new JTextField(8);
        textFieldB = new JTextField(8);
        textFieldC = new JTextField(8);
        textField = new JTextArea(2,8);
        
        JButton calculatebutton =new JButton("计算");
        calculatebutton.addActionListener(e-> {
                calculateTriangle();
            
        });

        
        titlepanel.add(xuehao);
        
        a.add(alabel);
        a.add(textFieldA);
        
        b.add(blabel);
        b.add(textFieldB);
        
        c.add(clabel);
        c.add(textFieldC);
        
        resultpanel.add(resultlabel);
        resultpanel.add(textField);
        
        calculate.add(calculatebutton);
        
        this.add(titlepanel);
        this.add(a);
        this.add(b);
        this.add(c);
        this.add(resultpanel);
        this.add(calculate);
        
        
        this.setLayout(new GridLayout(6, 1, 1, 1));
        this.setTitle("简单计算器"); // 标题
        this.setSize(350, 450); // 窗口大小
        this.setLocationRelativeTo(null); // 窗口居中显示
        this.setResizable(false); // 不可缩放
        this.setVisible(true); // 窗口可见
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// 关闭窗口时退出程序
        

    }

    private void calculateTriangle() {
        try {
            double a = Double.parseDouble(textFieldA.getText());
            double b = Double.parseDouble(textFieldB.getText());
            double c = Double.parseDouble(textFieldC.getText());

            if (a + b > c && a + c > b && b + c > a) {
                // 计算周长
                double perimeter = a + b + c;
                // 计算面积
                double p = perimeter / 2; // 半周长
                double area = Math.sqrt(p * (p - a) * (p - b) * (p - c));
                textField.setText("周长为:" + perimeter + "\n面积为:" + String.format("%.2f", area));
            } else {
            	textField.setText("输入的边长无法构成一个三角形");
            }
        } catch (NumberFormatException e) {
        	textField.setText("输入的边长不合法,请输入有效数字");
        }
    }
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值