|
|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
x
1. 环境准备与项目创建
1.1 安装必要的软件
在开始编写Java程序之前,我们需要确保计算机上已经安装了必要的软件:
1. Java Development Kit (JDK):Java开发工具包,是Java程序开发的基础。访问Oracle官网(https://www.oracle.com/java/technologies/downloads/)下载最新版本的JDK。按照安装向导完成安装,并记住安装路径。配置环境变量:在系统环境变量中添加JAVA_HOME变量,值为JDK安装路径;在Path变量中添加%JAVA_HOME%\bin。
2. 访问Oracle官网(https://www.oracle.com/java/technologies/downloads/)下载最新版本的JDK。
3. 按照安装向导完成安装,并记住安装路径。
4. 配置环境变量:在系统环境变量中添加JAVA_HOME变量,值为JDK安装路径;在Path变量中添加%JAVA_HOME%\bin。
5. Eclipse IDE:集成开发环境,提供代码编写、调试和运行的功能。访问Eclipse官网(https://www.eclipse.org/downloads/)下载EclipseIDE for Java Developers。解压下载的文件到指定目录,运行eclipse.exe启动Eclipse。
6. 访问Eclipse官网(https://www.eclipse.org/downloads/)下载EclipseIDE for Java Developers。
7. 解压下载的文件到指定目录,运行eclipse.exe启动Eclipse。
Java Development Kit (JDK):Java开发工具包,是Java程序开发的基础。
• 访问Oracle官网(https://www.oracle.com/java/technologies/downloads/)下载最新版本的JDK。
• 按照安装向导完成安装,并记住安装路径。
• 配置环境变量:在系统环境变量中添加JAVA_HOME变量,值为JDK安装路径;在Path变量中添加%JAVA_HOME%\bin。
Eclipse IDE:集成开发环境,提供代码编写、调试和运行的功能。
• 访问Eclipse官网(https://www.eclipse.org/downloads/)下载EclipseIDE for Java Developers。
• 解压下载的文件到指定目录,运行eclipse.exe启动Eclipse。
1.2 创建Java项目
1. 启动Eclipse后,选择工作空间(Workspace)路径,这是你项目存放的文件夹。
2. 创建新项目:点击菜单栏的File>New>Java Project。在弹出的对话框中,输入项目名称,例如ChinesePoetryDisplay。确保JRE版本正确(通常Eclipse会自动检测已安装的JDK)。点击Finish完成项目创建。
3. 点击菜单栏的File>New>Java Project。
4. 在弹出的对话框中,输入项目名称,例如ChinesePoetryDisplay。
5. 确保JRE版本正确(通常Eclipse会自动检测已安装的JDK)。
6. 点击Finish完成项目创建。
7. 创建Java类:在左侧的Package Explorer中,右键点击项目名称 >New>Class。输入包名(Package),例如com.poetry.display。输入类名(Class name),例如PoetryDisplay。勾选public static void main(String[] args)选项,自动生成main方法。点击Finish完成类的创建。
8. 在左侧的Package Explorer中,右键点击项目名称 >New>Class。
9. 输入包名(Package),例如com.poetry.display。
10. 输入类名(Class name),例如PoetryDisplay。
11. 勾选public static void main(String[] args)选项,自动生成main方法。
12. 点击Finish完成类的创建。
启动Eclipse后,选择工作空间(Workspace)路径,这是你项目存放的文件夹。
创建新项目:
• 点击菜单栏的File>New>Java Project。
• 在弹出的对话框中,输入项目名称,例如ChinesePoetryDisplay。
• 确保JRE版本正确(通常Eclipse会自动检测已安装的JDK)。
• 点击Finish完成项目创建。
创建Java类:
• 在左侧的Package Explorer中,右键点击项目名称 >New>Class。
• 输入包名(Package),例如com.poetry.display。
• 输入类名(Class name),例如PoetryDisplay。
• 勾选public static void main(String[] args)选项,自动生成main方法。
• 点击Finish完成类的创建。
2. 基础:简单的诗歌输出
2.1 使用System.out.println输出诗歌
最简单的方式是使用System.out.println()方法直接输出诗歌文本。让我们以李白的《静夜思》为例:
- package com.poetry.display;
- public class PoetryDisplay {
- public static void main(String[] args) {
- // 输出李白的《静夜思》
- System.out.println("静夜思");
- System.out.println("李白");
- System.out.println("床前明月光,");
- System.out.println("疑是地上霜。");
- System.out.println("举头望明月,");
- System.out.println("低头思故乡。");
- }
- }
复制代码
运行这个程序:
• 右键点击代码编辑器 >Run As>Java Application。
• 在下方的Console窗口中,你将看到诗歌的输出。
2.2 使用转义字符优化格式
为了更好地控制诗歌的格式,我们可以使用转义字符:
- package com.poetry.display;
- public class PoetryDisplay {
- public static void main(String[] args) {
- // 使用转义字符输出李白的《静夜思》
- System.out.println("静夜思\n李白\n床前明月光,\n疑是地上霜。\n举头望明月,\n低头思故乡。");
-
- // 或者使用更清晰的格式
- System.out.println("\n\n春晓\n孟浩然\n春眠不觉晓,\n处处闻啼鸟。\n夜来风雨声,\n花落知多少。");
- }
- }
复制代码
在这个例子中,\n表示换行符,使得诗歌的格式更加整齐。
3. 进阶:格式化输出诗歌
3.1 使用字符串变量存储诗歌
为了更好地管理诗歌内容,我们可以使用字符串变量来存储诗歌:
- package com.poetry.display;
- public class PoetryDisplay {
- public static void main(String[] args) {
- // 使用字符串变量存储诗歌
- String title = "登鹳雀楼";
- String author = "王之涣";
- String line1 = "白日依山尽,";
- String line2 = "黄河入海流。";
- String line3 = "欲穷千里目,";
- String line4 = "更上一层楼。";
-
- // 输出诗歌
- System.out.println(title);
- System.out.println(author);
- System.out.println(line1);
- System.out.println(line2);
- System.out.println(line3);
- System.out.println(line4);
- }
- }
复制代码
3.2 使用字符串数组存储诗歌
使用数组可以更有效地管理多首诗歌或诗歌的多行:
- package com.poetry.display;
- public class PoetryDisplay {
- public static void main(String[] args) {
- // 使用字符串数组存储诗歌
- String[] poetry = {
- "望庐山瀑布",
- "李白",
- "日照香炉生紫烟,",
- "遥看瀑布挂前川。",
- "飞流直下三千尺,",
- "疑是银河落九天。"
- };
-
- // 使用循环输出诗歌
- for (int i = 0; i < poetry.length; i++) {
- System.out.println(poetry[i]);
- }
-
- // 或者使用增强for循环
- System.out.println("\n使用增强for循环输出:");
- for (String line : poetry) {
- System.out.println(line);
- }
- }
- }
复制代码
3.3 使用StringBuilder构建诗歌
对于需要频繁修改的字符串,使用StringBuilder更加高效:
- package com.poetry.display;
- public class PoetryDisplay {
- public static void main(String[] args) {
- // 使用StringBuilder构建诗歌
- StringBuilder poetryBuilder = new StringBuilder();
-
- // 添加诗歌内容
- poetryBuilder.append("江雪\n");
- poetryBuilder.append("柳宗元\n");
- poetryBuilder.append("千山鸟飞绝,\n");
- poetryBuilder.append("万径人踪灭。\n");
- poetryBuilder.append("孤舟蓑笠翁,\n");
- poetryBuilder.append("独钓寒江雪。");
-
- // 输出诗歌
- System.out.println(poetryBuilder.toString());
-
- // 修改诗歌内容
- poetryBuilder.insert(0, "【唐诗】"); // 在开头插入
- poetryBuilder.append("\n\n赏析:这是一首描写江边雪景的诗,表达了诗人孤高不屈的品格。"); // 在末尾追加
-
- // 输出修改后的诗歌
- System.out.println("\n修改后的诗歌:");
- System.out.println(poetryBuilder.toString());
- }
- }
复制代码
4. 更高级:从文件读取诗歌
4.1 创建诗歌文本文件
1. 在项目中创建一个新的文件夹:右键点击项目名称 >New>Folder。输入文件夹名称,例如poems。
2. 右键点击项目名称 >New>Folder。
3. 输入文件夹名称,例如poems。
4. 在该文件夹中创建文本文件:右键点击poems文件夹 >New>File。输入文件名,例如qingye_siu.txt。在文件中输入《静夜思》的内容:静夜思
李白
床前明月光,
疑是地上霜。
举头望明月,
低头思故乡。
5. 右键点击poems文件夹 >New>File。
6. 输入文件名,例如qingye_siu.txt。
7. 在文件中输入《静夜思》的内容:静夜思
李白
床前明月光,
疑是地上霜。
举头望明月,
低头思故乡。
在项目中创建一个新的文件夹:
• 右键点击项目名称 >New>Folder。
• 输入文件夹名称,例如poems。
在该文件夹中创建文本文件:
• 右键点击poems文件夹 >New>File。
• 输入文件名,例如qingye_siu.txt。
• 在文件中输入《静夜思》的内容:静夜思
李白
床前明月光,
疑是地上霜。
举头望明月,
低头思故乡。
- 静夜思
- 李白
- 床前明月光,
- 疑是地上霜。
- 举头望明月,
- 低头思故乡。
复制代码
4.2 使用FileReader读取诗歌文件
- package com.poetry.display;
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileReader;
- import java.io.IOException;
- public class PoetryDisplay {
- public static void main(String[] args) {
- // 指定诗歌文件路径
- String filePath = "poems/qingye_siu.txt";
-
- // 使用FileReader读取文件
- try {
- File file = new File(filePath);
- FileReader fileReader = new FileReader(file);
- BufferedReader bufferedReader = new BufferedReader(fileReader);
-
- String line;
- System.out.println("从文件读取的诗歌:");
- while ((line = bufferedReader.readLine()) != null) {
- System.out.println(line);
- }
-
- // 关闭资源
- bufferedReader.close();
- fileReader.close();
- } catch (IOException e) {
- System.out.println("读取文件时出错:" + e.getMessage());
- }
- }
- }
复制代码
4.3 使用相对路径和类加载器读取资源
为了使程序更加健壮,我们可以使用类加载器来读取资源文件:
- package com.poetry.display;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- public class PoetryDisplay {
- public static void main(String[] args) {
- // 使用类加载器读取资源文件
- String resourcePath = "poems/qingye_siu.txt";
-
- // 获取类加载器
- ClassLoader classLoader = PoetryDisplay.class.getClassLoader();
-
- try (InputStream inputStream = classLoader.getResourceAsStream(resourcePath);
- InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
- BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
-
- if (inputStream == null) {
- System.out.println("无法找到资源文件:" + resourcePath);
- return;
- }
-
- String line;
- System.out.println("从资源文件读取的诗歌:");
- while ((line = bufferedReader.readLine()) != null) {
- System.out.println(line);
- }
- } catch (IOException e) {
- System.out.println("读取资源文件时出错:" + e.getMessage());
- }
- }
- }
复制代码
5. 高级应用:创建诗歌对象和集合
5.1 创建Poetry类
为了更好地表示诗歌,我们可以创建一个专门的Poetry类:
- package com.poetry.model;
- public class Poetry {
- private String title;
- private String author;
- private String dynasty;
- private String[] lines;
-
- // 构造方法
- public Poetry(String title, String author, String dynasty, String[] lines) {
- this.title = title;
- this.author = author;
- this.dynasty = dynasty;
- this.lines = lines;
- }
-
- // Getter和Setter方法
- public String getTitle() {
- return title;
- }
-
- public void setTitle(String title) {
- this.title = title;
- }
-
- public String getAuthor() {
- return author;
- }
-
- public void setAuthor(String author) {
- this.author = author;
- }
-
- public String getDynasty() {
- return dynasty;
- }
-
- public void setDynasty(String dynasty) {
- this.dynasty = dynasty;
- }
-
- public String[] getLines() {
- return lines;
- }
-
- public void setLines(String[] lines) {
- this.lines = lines;
- }
-
- // 输出诗歌的方法
- public void display() {
- System.out.println(title);
- System.out.println("【" + dynasty + "】" + author);
- for (String line : lines) {
- System.out.println(line);
- }
- }
-
- // 获取诗歌的完整文本
- public String getFullText() {
- StringBuilder sb = new StringBuilder();
- sb.append(title).append("\n");
- sb.append("【").append(dynasty).append("】").append(author).append("\n");
- for (String line : lines) {
- sb.append(line).append("\n");
- }
- return sb.toString();
- }
- }
复制代码
5.2 创建PoetryCollection类管理多首诗歌
- package com.poetry.collection;
- import java.util.ArrayList;
- import java.util.List;
- import com.poetry.model.Poetry;
- public class PoetryCollection {
- private List<Poetry> poems;
-
- // 构造方法
- public PoetryCollection() {
- poems = new ArrayList<>();
- }
-
- // 添加诗歌
- public void addPoetry(Poetry poem) {
- poems.add(poem);
- }
-
- // 获取所有诗歌
- public List<Poetry> getAllPoems() {
- return poems;
- }
-
- // 根据标题查找诗歌
- public Poetry findPoetryByTitle(String title) {
- for (Poetry poem : poems) {
- if (poem.getTitle().equals(title)) {
- return poem;
- }
- }
- return null;
- }
-
- // 根据作者查找诗歌
- public List<Poetry> findPoemsByAuthor(String author) {
- List<Poetry> result = new ArrayList<>();
- for (Poetry poem : poems) {
- if (poem.getAuthor().equals(author)) {
- result.add(poem);
- }
- }
- return result;
- }
-
- // 显示所有诗歌
- public void displayAllPoems() {
- for (Poetry poem : poems) {
- poem.display();
- System.out.println(); // 添加空行分隔不同诗歌
- }
- }
- }
复制代码
5.3 使用Poetry和PoetryCollection类
- package com.poetry.display;
- import com.poetry.collection.PoetryCollection;
- import com.poetry.model.Poetry;
- public class PoetryDisplay {
- public static void main(String[] args) {
- // 创建诗歌集合
- PoetryCollection collection = new PoetryCollection();
-
- // 创建并添加第一首诗
- String[] lines1 = {"床前明月光,", "疑是地上霜。", "举头望明月,", "低头思故乡。"};
- Poetry poetry1 = new Poetry("静夜思", "李白", "唐", lines1);
- collection.addPoetry(poetry1);
-
- // 创建并添加第二首诗
- String[] lines2 = {"白日依山尽,", "黄河入海流。", "欲穷千里目,", "更上一层楼。"};
- Poetry poetry2 = new Poetry("登鹳雀楼", "王之涣", "唐", lines2);
- collection.addPoetry(poetry2);
-
- // 创建并添加第三首诗
- String[] lines3 = {"春眠不觉晓,", "处处闻啼鸟。", "夜来风雨声,", "花落知多少。"};
- Poetry poetry3 = new Poetry("春晓", "孟浩然", "唐", lines3);
- collection.addPoetry(poetry3);
-
- // 显示所有诗歌
- System.out.println("===== 所有诗歌 =====");
- collection.displayAllPoems();
-
- // 根据标题查找诗歌
- System.out.println("===== 查找诗歌《静夜思》 =====");
- Poetry foundPoem = collection.findPoetryByTitle("静夜思");
- if (foundPoem != null) {
- foundPoem.display();
- } else {
- System.out.println("未找到该诗歌。");
- }
-
- // 根据作者查找诗歌
- System.out.println("\n===== 查找李白的诗歌 =====");
- java.util.List<Poetry> liBaiPoems = collection.findPoemsByAuthor("李白");
- for (Poetry poem : liBaiPoems) {
- poem.display();
- System.out.println();
- }
- }
- }
复制代码
6. 结合GUI显示诗歌
6.1 创建简单的GUI窗口显示诗歌
- package com.poetry.display;
- import javax.swing.JFrame;
- import javax.swing.JLabel;
- import javax.swing.JOptionPane;
- import javax.swing.JPanel;
- import javax.swing.JTextArea;
- import javax.swing.SwingConstants;
- import java.awt.BorderLayout;
- import java.awt.Font;
- import java.awt.GridLayout;
- import com.poetry.model.Poetry;
- public class PoetryGUIDisplay {
- public static void main(String[] args) {
- // 创建诗歌对象
- String[] lines = {"床前明月光,", "疑是地上霜。", "举头望明月,", "低头思故乡。"};
- Poetry poetry = new Poetry("静夜思", "李白", "唐", lines);
-
- // 创建主窗口
- JFrame frame = new JFrame("中国古典诗歌展示");
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- frame.setSize(500, 400);
- frame.setLocationRelativeTo(null); // 居中显示
-
- // 创建标题标签
- JLabel titleLabel = new JLabel(poetry.getTitle(), SwingConstants.CENTER);
- titleLabel.setFont(new Font("宋体", Font.BOLD, 24));
-
- // 创建作者和朝代标签
- JLabel authorLabel = new JLabel("【" + poetry.getDynasty() + "】" + poetry.getAuthor(), SwingConstants.CENTER);
- authorLabel.setFont(new Font("宋体", Font.ITALIC, 18));
-
- // 创建诗歌内容文本区域
- JTextArea contentArea = new JTextArea(10, 30);
- contentArea.setFont(new Font("宋体", Font.PLAIN, 20));
- contentArea.setEditable(false); // 不可编辑
-
- // 添加诗歌内容
- StringBuilder content = new StringBuilder();
- for (String line : poetry.getLines()) {
- content.append(line).append("\n");
- }
- contentArea.setText(content.toString());
-
- // 设置布局并添加组件
- frame.setLayout(new BorderLayout(10, 10));
- frame.add(titleLabel, BorderLayout.NORTH);
- frame.add(contentArea, BorderLayout.CENTER);
- frame.add(authorLabel, BorderLayout.SOUTH);
-
- // 显示窗口
- frame.setVisible(true);
- }
- }
复制代码
6.2 创建带按钮的诗歌浏览器
- package com.poetry.display;
- import javax.swing.JButton;
- import javax.swing.JFrame;
- import javax.swing.JLabel;
- import javax.swing.JPanel;
- import javax.swing.JTextArea;
- import javax.swing.SwingConstants;
- import java.awt.BorderLayout;
- import java.awt.Font;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import com.poetry.collection.PoetryCollection;
- import com.poetry.model.Poetry;
- public class PoetryBrowser {
- private static PoetryCollection collection;
- private static int currentIndex = 0;
- private static JFrame frame;
- private static JLabel titleLabel;
- private static JLabel authorLabel;
- private static JTextArea contentArea;
-
- public static void main(String[] args) {
- // 初始化诗歌集合
- initializePoetryCollection();
-
- // 创建主窗口
- frame = new JFrame("中国古典诗歌浏览器");
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- frame.setSize(500, 400);
- frame.setLocationRelativeTo(null); // 居中显示
-
- // 创建标题标签
- titleLabel = new JLabel("", SwingConstants.CENTER);
- titleLabel.setFont(new Font("宋体", Font.BOLD, 24));
-
- // 创建作者和朝代标签
- authorLabel = new JLabel("", SwingConstants.CENTER);
- authorLabel.setFont(new Font("宋体", Font.ITALIC, 18));
-
- // 创建诗歌内容文本区域
- contentArea = new JTextArea(10, 30);
- contentArea.setFont(new Font("宋体", Font.PLAIN, 20));
- contentArea.setEditable(false); // 不可编辑
-
- // 创建按钮面板
- JPanel buttonPanel = new JPanel();
- JButton prevButton = new JButton("上一首");
- JButton nextButton = new JButton("下一首");
-
- // 添加按钮事件监听器
- prevButton.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- if (currentIndex > 0) {
- currentIndex--;
- displayPoetry(currentIndex);
- }
- }
- });
-
- nextButton.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- if (currentIndex < collection.getAllPoems().size() - 1) {
- currentIndex++;
- displayPoetry(currentIndex);
- }
- }
- });
-
- buttonPanel.add(prevButton);
- buttonPanel.add(nextButton);
-
- // 设置布局并添加组件
- frame.setLayout(new BorderLayout(10, 10));
- frame.add(titleLabel, BorderLayout.NORTH);
- frame.add(contentArea, BorderLayout.CENTER);
- frame.add(authorLabel, BorderLayout.SOUTH);
- frame.add(buttonPanel, BorderLayout.AFTER_LAST_LINE);
-
- // 显示第一首诗歌
- displayPoetry(0);
-
- // 显示窗口
- frame.setVisible(true);
- }
-
- // 初始化诗歌集合
- private static void initializePoetryCollection() {
- collection = new com.poetry.collection.PoetryCollection();
-
- // 添加诗歌
- String[] lines1 = {"床前明月光,", "疑是地上霜。", "举头望明月,", "低头思故乡。"};
- collection.addPoetry(new Poetry("静夜思", "李白", "唐", lines1));
-
- String[] lines2 = {"白日依山尽,", "黄河入海流。", "欲穷千里目,", "更上一层楼。"};
- collection.addPoetry(new Poetry("登鹳雀楼", "王之涣", "唐", lines2));
-
- String[] lines3 = {"春眠不觉晓,", "处处闻啼鸟。", "夜来风雨声,", "花落知多少。"};
- collection.addPoetry(new Poetry("春晓", "孟浩然", "唐", lines3));
-
- String[] lines4 = {"千山鸟飞绝,", "万径人踪灭。", "孤舟蓑笠翁,", "独钓寒江雪。"};
- collection.addPoetry(new Poetry("江雪", "柳宗元", "唐", lines4));
- }
-
- // 显示指定索引的诗歌
- private static void displayPoetry(int index) {
- Poetry poetry = collection.getAllPoems().get(index);
- titleLabel.setText(poetry.getTitle());
- authorLabel.setText("【" + poetry.getDynasty() + "】" + poetry.getAuthor());
-
- StringBuilder content = new StringBuilder();
- for (String line : poetry.getLines()) {
- content.append(line).append("\n");
- }
- contentArea.setText(content.toString());
-
- // 更新窗口标题
- frame.setTitle("中国古典诗歌浏览器 - " + (index + 1) + "/" + collection.getAllPoems().size());
- }
- }
复制代码
7. 扩展功能:诗歌随机展示与搜索
7.1 添加随机展示功能
- package com.poetry.display;
- import javax.swing.JButton;
- import javax.swing.JFrame;
- import javax.swing.JLabel;
- import javax.swing.JPanel;
- import javax.swing.JTextArea;
- import javax.swing.SwingConstants;
- import java.awt.BorderLayout;
- import java.awt.Font;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import java.util.Random;
- import com.poetry.collection.PoetryCollection;
- import com.poetry.model.Poetry;
- public class PoetryRandomDisplay {
- private static PoetryCollection collection;
- private static JFrame frame;
- private static JLabel titleLabel;
- private static JLabel authorLabel;
- private static JTextArea contentArea;
- private static Random random = new Random();
-
- public static void main(String[] args) {
- // 初始化诗歌集合
- initializePoetryCollection();
-
- // 创建主窗口
- frame = new JFrame("中国古典诗歌随机展示");
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- frame.setSize(500, 400);
- frame.setLocationRelativeTo(null); // 居中显示
-
- // 创建标题标签
- titleLabel = new JLabel("", SwingConstants.CENTER);
- titleLabel.setFont(new Font("宋体", Font.BOLD, 24));
-
- // 创建作者和朝代标签
- authorLabel = new JLabel("", SwingConstants.CENTER);
- authorLabel.setFont(new Font("宋体", Font.ITALIC, 18));
-
- // 创建诗歌内容文本区域
- contentArea = new JTextArea(10, 30);
- contentArea.setFont(new Font("宋体", Font.PLAIN, 20));
- contentArea.setEditable(false); // 不可编辑
-
- // 创建按钮
- JButton randomButton = new JButton("随机展示");
-
- // 添加按钮事件监听器
- randomButton.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- displayRandomPoetry();
- }
- });
-
- // 设置布局并添加组件
- frame.setLayout(new BorderLayout(10, 10));
- frame.add(titleLabel, BorderLayout.NORTH);
- frame.add(contentArea, BorderLayout.CENTER);
- frame.add(authorLabel, BorderLayout.SOUTH);
- frame.add(randomButton, BorderLayout.AFTER_LAST_LINE);
-
- // 显示随机诗歌
- displayRandomPoetry();
-
- // 显示窗口
- frame.setVisible(true);
- }
-
- // 初始化诗歌集合
- private static void initializePoetryCollection() {
- collection = new com.poetry.collection.PoetryCollection();
-
- // 添加多首诗歌
- String[] lines1 = {"床前明月光,", "疑是地上霜。", "举头望明月,", "低头思故乡。"};
- collection.addPoetry(new Poetry("静夜思", "李白", "唐", lines1));
-
- String[] lines2 = {"白日依山尽,", "黄河入海流。", "欲穷千里目,", "更上一层楼。"};
- collection.addPoetry(new Poetry("登鹳雀楼", "王之涣", "唐", lines2));
-
- String[] lines3 = {"春眠不觉晓,", "处处闻啼鸟。", "夜来风雨声,", "花落知多少。"};
- collection.addPoetry(new Poetry("春晓", "孟浩然", "唐", lines3));
-
- String[] lines4 = {"千山鸟飞绝,", "万径人踪灭。", "孤舟蓑笠翁,", "独钓寒江雪。"};
- collection.addPoetry(new Poetry("江雪", "柳宗元", "唐", lines4));
-
- String[] lines5 = {"日照香炉生紫烟,", "遥看瀑布挂前川。", "飞流直下三千尺,", "疑是银河落九天。"};
- collection.addPoetry(new Poetry("望庐山瀑布", "李白", "唐", lines5));
-
- String[] lines6 = {"锄禾日当午,", "汗滴禾下土。", "谁知盘中餐,", "粒粒皆辛苦。"};
- collection.addPoetry(new Poetry("悯农", "李绅", "唐", lines6));
- }
-
- // 显示随机诗歌
- private static void displayRandomPoetry() {
- int index = random.nextInt(collection.getAllPoems().size());
- Poetry poetry = collection.getAllPoems().get(index);
- titleLabel.setText(poetry.getTitle());
- authorLabel.setText("【" + poetry.getDynasty() + "】" + poetry.getAuthor());
-
- StringBuilder content = new StringBuilder();
- for (String line : poetry.getLines()) {
- content.append(line).append("\n");
- }
- contentArea.setText(content.toString());
- }
- }
复制代码
7.2 添加搜索功能
- package com.poetry.display;
- import javax.swing.*;
- import javax.swing.event.DocumentEvent;
- import javax.swing.event.DocumentListener;
- import java.awt.*;
- import java.util.List;
- import com.poetry.collection.PoetryCollection;
- import com.poetry.model.Poetry;
- public class PoetrySearch {
- private static PoetryCollection collection;
- private static JFrame frame;
- private static DefaultListModel<String> listModel;
- private static JList<String> poetryList;
- private static JTextArea contentArea;
-
- public static void main(String[] args) {
- // 初始化诗歌集合
- initializePoetryCollection();
-
- // 创建主窗口
- frame = new JFrame("中国古典诗歌搜索");
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- frame.setSize(800, 600);
- frame.setLocationRelativeTo(null); // 居中显示
-
- // 创建搜索框
- JTextField searchField = new JTextField();
- searchField.setFont(new Font("宋体", Font.PLAIN, 16));
-
- // 创建诗歌列表
- listModel = new DefaultListModel<>();
- poetryList = new JList<>(listModel);
- poetryList.setFont(new Font("宋体", Font.PLAIN, 16));
- JScrollPane listScrollPane = new JScrollPane(poetryList);
-
- // 创建诗歌内容显示区域
- contentArea = new JTextArea();
- contentArea.setFont(new Font("宋体", Font.PLAIN, 20));
- contentArea.setEditable(false);
- JScrollPane contentScrollPane = new JScrollPane(contentArea);
-
- // 初始化诗歌列表
- updatePoetryList(collection.getAllPoems());
-
- // 添加搜索功能
- searchField.getDocument().addDocumentListener(new DocumentListener() {
- @Override
- public void insertUpdate(DocumentEvent e) {
- searchPoetry(searchField.getText());
- }
-
- @Override
- public void removeUpdate(DocumentEvent e) {
- searchPoetry(searchField.getText());
- }
-
- @Override
- public void changedUpdate(DocumentEvent e) {
- searchPoetry(searchField.getText());
- }
- });
-
- // 添加列表选择事件
- poetryList.addListSelectionListener(e -> {
- if (!e.getValueIsAdjusting()) {
- String selectedValue = poetryList.getSelectedValue();
- if (selectedValue != null) {
- String title = selectedValue.split(" - ")[0];
- Poetry poetry = collection.findPoetryByTitle(title);
- if (poetry != null) {
- displayPoetry(poetry);
- }
- }
- }
- });
-
- // 设置布局
- frame.setLayout(new BorderLayout(5, 5));
-
- // 顶部面板 - 搜索框
- JPanel topPanel = new JPanel(new BorderLayout());
- topPanel.add(new JLabel("搜索:"), BorderLayout.WEST);
- topPanel.add(searchField, BorderLayout.CENTER);
-
- // 分割面板
- JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, listScrollPane, contentScrollPane);
- splitPane.setDividerLocation(250);
-
- // 添加组件到主窗口
- frame.add(topPanel, BorderLayout.NORTH);
- frame.add(splitPane, BorderLayout.CENTER);
-
- // 显示窗口
- frame.setVisible(true);
- }
-
- // 初始化诗歌集合
- private static void initializePoetryCollection() {
- collection = new com.poetry.collection.PoetryCollection();
-
- // 添加多首诗歌
- String[] lines1 = {"床前明月光,", "疑是地上霜。", "举头望明月,", "低头思故乡。"};
- collection.addPoetry(new Poetry("静夜思", "李白", "唐", lines1));
-
- String[] lines2 = {"白日依山尽,", "黄河入海流。", "欲穷千里目,", "更上一层楼。"};
- collection.addPoetry(new Poetry("登鹳雀楼", "王之涣", "唐", lines2));
-
- String[] lines3 = {"春眠不觉晓,", "处处闻啼鸟。", "夜来风雨声,", "花落知多少。"};
- collection.addPoetry(new Poetry("春晓", "孟浩然", "唐", lines3));
-
- String[] lines4 = {"千山鸟飞绝,", "万径人踪灭。", "孤舟蓑笠翁,", "独钓寒江雪。"};
- collection.addPoetry(new Poetry("江雪", "柳宗元", "唐", lines4));
-
- String[] lines5 = {"日照香炉生紫烟,", "遥看瀑布挂前川。", "飞流直下三千尺,", "疑是银河落九天。"};
- collection.addPoetry(new Poetry("望庐山瀑布", "李白", "唐", lines5));
-
- String[] lines6 = {"锄禾日当午,", "汗滴禾下土。", "谁知盘中餐,", "粒粒皆辛苦。"};
- collection.addPoetry(new Poetry("悯农", "李绅", "唐", lines6));
- }
-
- // 更新诗歌列表
- private static void updatePoetryList(List<Poetry> poems) {
- listModel.clear();
- for (Poetry poetry : poems) {
- listModel.addElement(poetry.getTitle() + " - " + poetry.getAuthor() + " (" + poetry.getDynasty() + ")");
- }
- }
-
- // 搜索诗歌
- private static void searchPoetry(String keyword) {
- if (keyword == null || keyword.trim().isEmpty()) {
- updatePoetryList(collection.getAllPoems());
- return;
- }
-
- List<Poetry> result = collection.findPoemsByAuthor(keyword);
- if (result.isEmpty()) {
- // 如果按作者搜索没有结果,尝试按标题搜索
- Poetry poetry = collection.findPoetryByTitle(keyword);
- if (poetry != null) {
- result.add(poetry);
- }
- }
-
- updatePoetryList(result);
- }
-
- // 显示诗歌内容
- private static void displayPoetry(Poetry poetry) {
- StringBuilder content = new StringBuilder();
- content.append(poetry.getTitle()).append("\n\n");
- content.append("【").append(poetry.getDynasty()).append("】").append(poetry.getAuthor()).append("\n\n");
- for (String line : poetry.getLines()) {
- content.append(line).append("\n");
- }
- contentArea.setText(content.toString());
- }
- }
复制代码
8. 总结与展望
通过本教程,我们从基础到进阶,系统地学习了如何在Eclipse集成开发环境中通过Java程序输出显示中国古典诗歌。我们涵盖了以下内容:
1. 环境准备与项目创建:安装必要的软件,创建Java项目和类。
2. 基础输出:使用System.out.println()和转义字符简单输出诗歌。
3. 格式化输出:使用字符串变量、数组和StringBuilder优化诗歌的存储和输出。
4. 文件读取:从文本文件中读取诗歌内容,使用相对路径和类加载器提高程序的健壮性。
5. 面向对象设计:创建Poetry类和PoetryCollection类,更好地组织和管理诗歌数据。
6. GUI展示:使用Swing创建图形界面,更美观地展示诗歌。
7. 扩展功能:实现随机展示和搜索功能,提高程序的实用性。
这个项目不仅帮助初学者学习了Java编程的基础知识,如变量、数组、字符串、文件操作、面向对象编程等,还结合了中国传统文化,让编程学习变得更加有趣和有意义。
未来扩展方向
1. 数据库支持:将诗歌存储在数据库中,实现更高效的数据管理和查询。
2. 网络功能:从网络获取诗歌资源,或创建诗歌分享网站。
3. 多媒体支持:为诗歌添加朗诵音频或相关图片。
4. 诗歌分析:实现简单的诗歌内容分析,如字数统计、韵律分析等。
5. 移动应用:将项目移植到Android平台,创建移动诗歌应用。
通过不断扩展和完善这个项目,初学者可以逐步掌握更多的编程技能,同时深入欣赏和理解中国古典诗歌的魅力,实现技术与文化的完美结合。 |
|