功能要求:
- 为图书馆的馆藏品管理设计一个图书类,实现主要的属性和方法。(如图书的书名、作者等属性,显示图书信息、借阅、归还等操作)。类与接口(设计)
- 设计并实现类体系,对图书馆管理系统中馆藏品(书籍、报刊、杂志等)进行管理,实现主要的功能。继承与多态(设计)
- 设计实现一个简单的图形用户界面程序,如登录程序、属性设置程序、文本编辑程序、四则运算程序等。GUI组件
代码实现:
- 首先,这是一个Book类,它实现了书籍的基本属性和方法:
public class Book {
private String title;
private String author;
private int pages;
private boolean borrowed;
public Book(String bookTitle, String bookAuthor, int numPages) {
title = bookTitle;
author = bookAuthor;
pages = numPages;
borrowed = false;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public int getPages() {
return pages;
}
public void borrowBook() {
borrowed = true;
}
public void returnBook() {
borrowed = false;
}
public boolean isBorrowed() {
return borrowed;
}
public void printBookInfo() {
System.out.println("Title: " + title);
System.out.println("Author: " + author);
System.out.println("Pages: " + pages);
if (borrowed) {
System.out.println("This book is currently borrowed.");
} else {
System.out.println("This book is currently available to borrow.");
}
}
}
- Library类,实现了对馆藏品(包括书籍、报刊、杂志等)进行管理的方法:
import java.util.ArrayList;
public class Library {
private ArrayList<Book> books;
public Library() {
books = new ArrayList<Book>();
}
public void addBook(Book book) {
books.add(book);
}
public void borrowBook(String title) {
for (Book book : books) {
if (book.getTitle().equals(title)) {
if (!book.isBorrowed()) {
book.borrowBook();
System.out.println("You have successfully borrowed " + title);
} else {
System.out.println("Sorry, this book is already borrowed.");
}
return;
}
}
System.out.println("Sorry, this book is not in our library.");
}
public void returnBook(String title) {
for (Book book : books) {
if (book.getTitle().equals(title)) {
if (book.isBorrowed()) {
book.returnBook();
System.out.println("You have successfully returned " + title);
} else {
System.out.println("This book has not been borrowed and cannot be returned.");
}
return;
}
}
System.out.println("Sorry, this book is not in our library.");
}
public void printLibrary() {
if (books.isEmpty()) {
System.out.println("The library is currently empty.");
} else {
for (Book book : books) {
book.printBookInfo();
System.out.println();
}
}
}
}
- 简单的Demo程序,演示了如何使用上面定义的类来进行图书馆管理系统:
public class LibraryDemo {
public static void main(String[] args) {
Book book1 = new Book("The Lord of the Rings", "J.R.R. Tolkien", 1178);
Book book2 = new Book("To Kill a Mockingbird", "Harper Lee", 281);
Book book3 = new Book("1984", "George Orwell", 328);
Library library = new Library();
library.addBook(book1);
library.addBook(book2);
library.addBook(book3);
library.printLibrary();
library.borrowBook("The Lord of the Rings");
library.borrowBook("To Kill a Mockingbird");
library.borrowBook("1984");
library.printLibrary();
library.returnBook("To Kill a Mockingbird");
library.printLibrary();
}
}
在这个Demo程序中,我们先创建了三本书,并将它们添加到图书馆中。然后我们显示了整个图书馆的内容,接着我们借阅了三本书(其中一本已经被借走了),再次显示了整个图书馆的内容,最后归还了一本书,并再次显示了整个图书馆的内容。
- 图形用户界面程序示例。它包含了登录程序和属性设置程序:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GUIExample extends JFrame {
private JLabel usernameLabel, passwordLabel, nameLabel, ageLabel;
private JTextField usernameField, passwordField, nameField, ageField;
private JButton loginButton, saveButton;
public GUIExample() {
super("Login & Settings Example");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 创建顶部面板,包含标题和登录表单
JPanel topPanel = new JPanel(new BorderLayout());
JLabel titleLabel = new JLabel("Login Form", JLabel.CENTER);
usernameLabel = new JLabel("Username:");
passwordLabel = new JLabel("Password:");
usernameField = new JTextField(10);
passwordField = new JPasswordField(10);
loginButton = new JButton("Login");
// 添加登录按钮监听器,当点击时执行登录方法
loginButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
login();
}
});
// 将标题和表单添加到顶部面板中
JPanel loginFormPanel = new JPanel(new GridLayout(2, 2));
loginFormPanel.add(usernameLabel);
loginFormPanel.add(usernameField);
loginFormPanel.add(passwordLabel);
loginFormPanel.add(passwordField);
topPanel.add(titleLabel, BorderLayout.NORTH);
topPanel.add(loginFormPanel, BorderLayout.CENTER);
topPanel.add(loginButton, BorderLayout.SOUTH);
// 创建底部面板,包含属性设置表单和保存按钮
JPanel bottomPanel = new JPanel(new BorderLayout());
nameLabel = new JLabel("Name:");
ageLabel = new JLabel("Age:");
nameField = new JTextField(10);
ageField = new JTextField(3);
saveButton = new JButton("Save");
// 添加保存按钮监听器,当点击时执行保存方法
saveButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
saveSettings();
}
});
// 将属性设置表单和保存按钮添加到底部面板中
JPanel settingsPanel = new JPanel(new GridLayout(2, 2));
settingsPanel.add(nameLabel);
settingsPanel.add(nameField);
settingsPanel.add(ageLabel);
settingsPanel.add(ageField);
bottomPanel.add(settingsPanel, BorderLayout.CENTER);
bottomPanel.add(saveButton, BorderLayout.SOUTH);
// 将顶部和底部面板添加到主面板中
add(topPanel, BorderLayout.NORTH);
add(bottomPanel, BorderLayout.CENTER);
setVisible(true);
}
private void login() {
String username = usernameField.getText();
String password = passwordField.getText();
// 进行登录验证
if (username.equals("admin") && password.equals("password")) {
JOptionPane.showMessageDialog(this, "Login successful!");
} else {
JOptionPane.showMessageDialog(this, "Invalid username or password.");
}
}
private void saveSettings() {
String name = nameField.getText();
int age;
try {
age = Integer.parseInt(ageField.getText());
} catch (NumberFormatException e) { // 当输入不是整数时抛出异常
JOptionPane.showMessageDialog(this, "Please enter a valid age.");
return;
}
// 将属性设置保存到数据库或文件等
JOptionPane.showMessageDialog(this, "Settings saved: Name - " + name + ", Age - " + age);
}
public static void main(String[] args) {
new GUIExample();
}
}
这个程序创建了一个包含两个面板的窗口。第一个面板是登录表单,包含用户名、密码和登录按钮;第二个面板是属性设置表单,包含姓名、年龄和保存按钮。
当用户点击登录按钮时,程序会验证用户名和密码是否正确,并在弹出对话框中显示结果。当用户点击保存按钮时,程序会读取姓名和年龄文本框中的值,并将它们保存到数据库或文件等,同样也会在弹出对话框中显示结果。
- 文本编辑程序示例。它允许用户打开、保存和编辑纯文本文件:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
public class TextEditor extends JFrame {
private JTextArea textArea;
private JFileChooser fileChooser;
public TextEditor() {
super("Text Editor");
setSize(800, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 创建菜单条和菜单项
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenuItem openMenuItem = new JMenuItem("Open");
JMenuItem saveMenuItem = new JMenuItem("Save");
// 添加打开和保存按钮监听器
openMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
openFile();
}
});
saveMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
saveFile();
}
});
// 将菜单项添加到菜单中,并将菜单添加到菜单条中
fileMenu.add(openMenuItem);
fileMenu.add(saveMenuItem);
menuBar.add(fileMenu);
setJMenuBar(menuBar);
// 创建文本区域和文件选择器
textArea = new JTextArea();
fileChooser = new JFileChooser();
add(new JScrollPane(textArea), BorderLayout.CENTER);
setVisible(true);
}
private void openFile() {
int returnVal = fileChooser.showOpenDialog(this); // 显示文件选择对话框
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile(); // 获取用户选择的文件
try {
BufferedReader reader = new BufferedReader(new FileReader(file)); // 创建文件读取器
textArea.read(reader, null); // 将文件内容读取到文本区域中
reader.close();
} catch (IOException e) {
JOptionPane.showMessageDialog(this, "Error reading file: " + e.getMessage());
}
}
}
private void saveFile() {
int returnVal = fileChooser.showSaveDialog(this); // 显示保存文件对话框
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile(); // 获取用户选择的文件
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(file)); // 创建文件写入器
textArea.write(writer); // 将文本区域中的内容写入文件中
writer.close();
} catch (IOException e) {
JOptionPane.showMessageDialog(this, "Error saving file: " + e.getMessage());
}
}
}
public static void main(String[] args) {
new TextEditor();
}
}
这个程序创建了一个简单的文本编辑器窗口,包含一个菜单条、一个文本区域和一个文件选择器。通过菜单可以打开纯文本文件并将其内容显示在文本区域中,也可以将文本区域中的内容保存到纯文本文件中。
- 四则运算程序示例:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Calculator extends JFrame {
private JTextField resultField;
private double operand1, operand2;
private char operator;
private boolean isResult;
public Calculator() {
super("Calculator");
setSize(300, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel topPanel = new JPanel(new BorderLayout());
resultField = new JTextField();
resultField.setEditable(false);
resultField.setHorizontalAlignment(JTextField.RIGHT);
topPanel.add(resultField, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel(new GridLayout(4, 4));
JButton button0 = new JButton("0");
JButton button1 = new JButton("1");
JButton button2 = new JButton("2");
JButton button3 = new JButton("3");
JButton button4 = new JButton("4");
JButton button5 = new JButton("5");
JButton button6 = new JButton("6");
JButton button7 = new JButton("7");
JButton button8 = new JButton("8");
JButton button9 = new JButton("9");
JButton buttonAdd = new JButton("+");
JButton buttonSubtract = new JButton("-");
JButton buttonMultiply = new JButton("*");
JButton buttonDivide = new JButton("/");
JButton buttonClear = new JButton("C");
JButton buttonEquals = new JButton("=");
// 添加数字和操作符按钮监听器
button0.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
appendToResult("0");
}
});
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
appendToResult("1");
}
});
button2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
appendToResult("2");
}
});
button3.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
appendToResult("3");
}
});
button4.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
appendToResult("4");
}
});
button5.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
appendToResult("5");
}
});
button6.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
appendToResult("6");
}
});
button7.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
appendToResult("7");
}
});
button8.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
appendToResult("8");
}
});
button9.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
appendToResult("9");
}
});
buttonAdd.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setOperator('+');
}
});
buttonSubtract.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setOperator('-');
}
});
buttonMultiply.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setOperator('*');
}
});
buttonDivide.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setOperator('/');
}
});
// 添加清空和计算按钮监听器
buttonClear.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
clearResult();
}
});
buttonEquals.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
calculateResult();
}
});
// 将按钮添加到面板中
buttonPanel.add(button7);
buttonPanel.add(button8);
buttonPanel.add(button9);
buttonPanel.add(buttonDivide);
buttonPanel.add(button4);
buttonPanel.add(button5);
buttonPanel.add(button6);
buttonPanel.add(buttonMultiply);
buttonPanel.add(button1);
buttonPanel.add(button2);
buttonPanel.add(button3);
buttonPanel.add(buttonSubtract);
buttonPanel.add(button0);
buttonPanel.add(buttonClear);
buttonPanel.add(buttonEquals);
buttonPanel.add(buttonAdd);
add(topPanel, BorderLayout.NORTH);
add(buttonPanel, BorderLayout.CENTER);
setVisible(true);
}
private void appendToResult(String text){ if (isResult) { // 如果之前已经计算出结果,先清除结果再输入新数字 resultField.setText(""); isResult = false; } resultField.setText(resultField.getText() + text); // 在结果文本框中追加数字或操作符 }
private void setOperator(char op) {
operand1 = Double.parseDouble(resultField.getText()); // 获取文本框中的第一个操作数
operator = op; // 设置操作符
resultField.setText(""); // 清空结果文本框,等待输入第二个操作数
}
private void calculateResult() {
operand2 = Double.parseDouble(resultField.getText()); // 获取文本框中的第二个操作数
double result = 0.0;
switch (operator) { // 根据操作符计算结果
case '+':
result = operand1 + operand2;
break;
case '-':
result = operand1 - operand2;
break;
case '*':
result = operand1 * operand2;
break;
case '/':
result = operand1 / operand2;
break;
}
resultField.setText(Double.toString(result)); // 在结果文本框中显示结果
isResult = true; // 标记已经计算出结果
}
private void clearResult() {
operand1 = 0.0;
operand2 = 0.0;
operator = ' ';
resultField.setText(""); // 清空结果文本框和操作数变量
}
public static void main(String[] args) {
new Calculator();
}
}