活动公告

系统通知
05-18 21:22
系统通知
通知:本站资源由网友上传分享,如有违规等问题请到版务模块进行投诉,资源失效请在帖子内回复要求补档,会尽快处理!
10-23 09:31

在Eclipse集成开发环境中通过编写Java程序代码输出显示中国古典诗歌文本的详细教程步骤从基础到进阶帮助初学者快速掌握编程技能同时欣赏传统文化之美

SunJu_FaceMall

3万

主题

2860

科技点

3万

积分

白金月票

碾压王

积分
32872

塔罗立华奏

<font color=白金月票" /> 发表于 2025-9-19 14:50:00 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

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()方法直接输出诗歌文本。让我们以李白的《静夜思》为例:
  1. package com.poetry.display;
  2. public class PoetryDisplay {
  3.     public static void main(String[] args) {
  4.         // 输出李白的《静夜思》
  5.         System.out.println("静夜思");
  6.         System.out.println("李白");
  7.         System.out.println("床前明月光,");
  8.         System.out.println("疑是地上霜。");
  9.         System.out.println("举头望明月,");
  10.         System.out.println("低头思故乡。");
  11.     }
  12. }
复制代码

运行这个程序:

• 右键点击代码编辑器 >Run As>Java Application。
• 在下方的Console窗口中,你将看到诗歌的输出。

2.2 使用转义字符优化格式

为了更好地控制诗歌的格式,我们可以使用转义字符:
  1. package com.poetry.display;
  2. public class PoetryDisplay {
  3.     public static void main(String[] args) {
  4.         // 使用转义字符输出李白的《静夜思》
  5.         System.out.println("静夜思\n李白\n床前明月光,\n疑是地上霜。\n举头望明月,\n低头思故乡。");
  6.         
  7.         // 或者使用更清晰的格式
  8.         System.out.println("\n\n春晓\n孟浩然\n春眠不觉晓,\n处处闻啼鸟。\n夜来风雨声,\n花落知多少。");
  9.     }
  10. }
复制代码

在这个例子中,\n表示换行符,使得诗歌的格式更加整齐。

3. 进阶:格式化输出诗歌

3.1 使用字符串变量存储诗歌

为了更好地管理诗歌内容,我们可以使用字符串变量来存储诗歌:
  1. package com.poetry.display;
  2. public class PoetryDisplay {
  3.     public static void main(String[] args) {
  4.         // 使用字符串变量存储诗歌
  5.         String title = "登鹳雀楼";
  6.         String author = "王之涣";
  7.         String line1 = "白日依山尽,";
  8.         String line2 = "黄河入海流。";
  9.         String line3 = "欲穷千里目,";
  10.         String line4 = "更上一层楼。";
  11.         
  12.         // 输出诗歌
  13.         System.out.println(title);
  14.         System.out.println(author);
  15.         System.out.println(line1);
  16.         System.out.println(line2);
  17.         System.out.println(line3);
  18.         System.out.println(line4);
  19.     }
  20. }
复制代码

3.2 使用字符串数组存储诗歌

使用数组可以更有效地管理多首诗歌或诗歌的多行:
  1. package com.poetry.display;
  2. public class PoetryDisplay {
  3.     public static void main(String[] args) {
  4.         // 使用字符串数组存储诗歌
  5.         String[] poetry = {
  6.             "望庐山瀑布",
  7.             "李白",
  8.             "日照香炉生紫烟,",
  9.             "遥看瀑布挂前川。",
  10.             "飞流直下三千尺,",
  11.             "疑是银河落九天。"
  12.         };
  13.         
  14.         // 使用循环输出诗歌
  15.         for (int i = 0; i < poetry.length; i++) {
  16.             System.out.println(poetry[i]);
  17.         }
  18.         
  19.         // 或者使用增强for循环
  20.         System.out.println("\n使用增强for循环输出:");
  21.         for (String line : poetry) {
  22.             System.out.println(line);
  23.         }
  24.     }
  25. }
复制代码

3.3 使用StringBuilder构建诗歌

对于需要频繁修改的字符串,使用StringBuilder更加高效:
  1. package com.poetry.display;
  2. public class PoetryDisplay {
  3.     public static void main(String[] args) {
  4.         // 使用StringBuilder构建诗歌
  5.         StringBuilder poetryBuilder = new StringBuilder();
  6.         
  7.         // 添加诗歌内容
  8.         poetryBuilder.append("江雪\n");
  9.         poetryBuilder.append("柳宗元\n");
  10.         poetryBuilder.append("千山鸟飞绝,\n");
  11.         poetryBuilder.append("万径人踪灭。\n");
  12.         poetryBuilder.append("孤舟蓑笠翁,\n");
  13.         poetryBuilder.append("独钓寒江雪。");
  14.         
  15.         // 输出诗歌
  16.         System.out.println(poetryBuilder.toString());
  17.         
  18.         // 修改诗歌内容
  19.         poetryBuilder.insert(0, "【唐诗】"); // 在开头插入
  20.         poetryBuilder.append("\n\n赏析:这是一首描写江边雪景的诗,表达了诗人孤高不屈的品格。"); // 在末尾追加
  21.         
  22.         // 输出修改后的诗歌
  23.         System.out.println("\n修改后的诗歌:");
  24.         System.out.println(poetryBuilder.toString());
  25.     }
  26. }
复制代码

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。
• 在文件中输入《静夜思》的内容:静夜思
李白
床前明月光,
疑是地上霜。
举头望明月,
低头思故乡。
  1. 静夜思
  2. 李白
  3. 床前明月光,
  4. 疑是地上霜。
  5. 举头望明月,
  6. 低头思故乡。
复制代码

4.2 使用FileReader读取诗歌文件
  1. package com.poetry.display;
  2. import java.io.BufferedReader;
  3. import java.io.File;
  4. import java.io.FileReader;
  5. import java.io.IOException;
  6. public class PoetryDisplay {
  7.     public static void main(String[] args) {
  8.         // 指定诗歌文件路径
  9.         String filePath = "poems/qingye_siu.txt";
  10.         
  11.         // 使用FileReader读取文件
  12.         try {
  13.             File file = new File(filePath);
  14.             FileReader fileReader = new FileReader(file);
  15.             BufferedReader bufferedReader = new BufferedReader(fileReader);
  16.             
  17.             String line;
  18.             System.out.println("从文件读取的诗歌:");
  19.             while ((line = bufferedReader.readLine()) != null) {
  20.                 System.out.println(line);
  21.             }
  22.             
  23.             // 关闭资源
  24.             bufferedReader.close();
  25.             fileReader.close();
  26.         } catch (IOException e) {
  27.             System.out.println("读取文件时出错:" + e.getMessage());
  28.         }
  29.     }
  30. }
复制代码

4.3 使用相对路径和类加载器读取资源

为了使程序更加健壮,我们可以使用类加载器来读取资源文件:
  1. package com.poetry.display;
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.io.InputStreamReader;
  6. public class PoetryDisplay {
  7.     public static void main(String[] args) {
  8.         // 使用类加载器读取资源文件
  9.         String resourcePath = "poems/qingye_siu.txt";
  10.         
  11.         // 获取类加载器
  12.         ClassLoader classLoader = PoetryDisplay.class.getClassLoader();
  13.         
  14.         try (InputStream inputStream = classLoader.getResourceAsStream(resourcePath);
  15.              InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
  16.              BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
  17.             
  18.             if (inputStream == null) {
  19.                 System.out.println("无法找到资源文件:" + resourcePath);
  20.                 return;
  21.             }
  22.             
  23.             String line;
  24.             System.out.println("从资源文件读取的诗歌:");
  25.             while ((line = bufferedReader.readLine()) != null) {
  26.                 System.out.println(line);
  27.             }
  28.         } catch (IOException e) {
  29.             System.out.println("读取资源文件时出错:" + e.getMessage());
  30.         }
  31.     }
  32. }
复制代码

5. 高级应用:创建诗歌对象和集合

5.1 创建Poetry类

为了更好地表示诗歌,我们可以创建一个专门的Poetry类:
  1. package com.poetry.model;
  2. public class Poetry {
  3.     private String title;
  4.     private String author;
  5.     private String dynasty;
  6.     private String[] lines;
  7.    
  8.     // 构造方法
  9.     public Poetry(String title, String author, String dynasty, String[] lines) {
  10.         this.title = title;
  11.         this.author = author;
  12.         this.dynasty = dynasty;
  13.         this.lines = lines;
  14.     }
  15.    
  16.     // Getter和Setter方法
  17.     public String getTitle() {
  18.         return title;
  19.     }
  20.    
  21.     public void setTitle(String title) {
  22.         this.title = title;
  23.     }
  24.    
  25.     public String getAuthor() {
  26.         return author;
  27.     }
  28.    
  29.     public void setAuthor(String author) {
  30.         this.author = author;
  31.     }
  32.    
  33.     public String getDynasty() {
  34.         return dynasty;
  35.     }
  36.    
  37.     public void setDynasty(String dynasty) {
  38.         this.dynasty = dynasty;
  39.     }
  40.    
  41.     public String[] getLines() {
  42.         return lines;
  43.     }
  44.    
  45.     public void setLines(String[] lines) {
  46.         this.lines = lines;
  47.     }
  48.    
  49.     // 输出诗歌的方法
  50.     public void display() {
  51.         System.out.println(title);
  52.         System.out.println("【" + dynasty + "】" + author);
  53.         for (String line : lines) {
  54.             System.out.println(line);
  55.         }
  56.     }
  57.    
  58.     // 获取诗歌的完整文本
  59.     public String getFullText() {
  60.         StringBuilder sb = new StringBuilder();
  61.         sb.append(title).append("\n");
  62.         sb.append("【").append(dynasty).append("】").append(author).append("\n");
  63.         for (String line : lines) {
  64.             sb.append(line).append("\n");
  65.         }
  66.         return sb.toString();
  67.     }
  68. }
复制代码

5.2 创建PoetryCollection类管理多首诗歌
  1. package com.poetry.collection;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import com.poetry.model.Poetry;
  5. public class PoetryCollection {
  6.     private List<Poetry> poems;
  7.    
  8.     // 构造方法
  9.     public PoetryCollection() {
  10.         poems = new ArrayList<>();
  11.     }
  12.    
  13.     // 添加诗歌
  14.     public void addPoetry(Poetry poem) {
  15.         poems.add(poem);
  16.     }
  17.    
  18.     // 获取所有诗歌
  19.     public List<Poetry> getAllPoems() {
  20.         return poems;
  21.     }
  22.    
  23.     // 根据标题查找诗歌
  24.     public Poetry findPoetryByTitle(String title) {
  25.         for (Poetry poem : poems) {
  26.             if (poem.getTitle().equals(title)) {
  27.                 return poem;
  28.             }
  29.         }
  30.         return null;
  31.     }
  32.    
  33.     // 根据作者查找诗歌
  34.     public List<Poetry> findPoemsByAuthor(String author) {
  35.         List<Poetry> result = new ArrayList<>();
  36.         for (Poetry poem : poems) {
  37.             if (poem.getAuthor().equals(author)) {
  38.                 result.add(poem);
  39.             }
  40.         }
  41.         return result;
  42.     }
  43.    
  44.     // 显示所有诗歌
  45.     public void displayAllPoems() {
  46.         for (Poetry poem : poems) {
  47.             poem.display();
  48.             System.out.println(); // 添加空行分隔不同诗歌
  49.         }
  50.     }
  51. }
复制代码

5.3 使用Poetry和PoetryCollection类
  1. package com.poetry.display;
  2. import com.poetry.collection.PoetryCollection;
  3. import com.poetry.model.Poetry;
  4. public class PoetryDisplay {
  5.     public static void main(String[] args) {
  6.         // 创建诗歌集合
  7.         PoetryCollection collection = new PoetryCollection();
  8.         
  9.         // 创建并添加第一首诗
  10.         String[] lines1 = {"床前明月光,", "疑是地上霜。", "举头望明月,", "低头思故乡。"};
  11.         Poetry poetry1 = new Poetry("静夜思", "李白", "唐", lines1);
  12.         collection.addPoetry(poetry1);
  13.         
  14.         // 创建并添加第二首诗
  15.         String[] lines2 = {"白日依山尽,", "黄河入海流。", "欲穷千里目,", "更上一层楼。"};
  16.         Poetry poetry2 = new Poetry("登鹳雀楼", "王之涣", "唐", lines2);
  17.         collection.addPoetry(poetry2);
  18.         
  19.         // 创建并添加第三首诗
  20.         String[] lines3 = {"春眠不觉晓,", "处处闻啼鸟。", "夜来风雨声,", "花落知多少。"};
  21.         Poetry poetry3 = new Poetry("春晓", "孟浩然", "唐", lines3);
  22.         collection.addPoetry(poetry3);
  23.         
  24.         // 显示所有诗歌
  25.         System.out.println("===== 所有诗歌 =====");
  26.         collection.displayAllPoems();
  27.         
  28.         // 根据标题查找诗歌
  29.         System.out.println("===== 查找诗歌《静夜思》 =====");
  30.         Poetry foundPoem = collection.findPoetryByTitle("静夜思");
  31.         if (foundPoem != null) {
  32.             foundPoem.display();
  33.         } else {
  34.             System.out.println("未找到该诗歌。");
  35.         }
  36.         
  37.         // 根据作者查找诗歌
  38.         System.out.println("\n===== 查找李白的诗歌 =====");
  39.         java.util.List<Poetry> liBaiPoems = collection.findPoemsByAuthor("李白");
  40.         for (Poetry poem : liBaiPoems) {
  41.             poem.display();
  42.             System.out.println();
  43.         }
  44.     }
  45. }
复制代码

6. 结合GUI显示诗歌

6.1 创建简单的GUI窗口显示诗歌
  1. package com.poetry.display;
  2. import javax.swing.JFrame;
  3. import javax.swing.JLabel;
  4. import javax.swing.JOptionPane;
  5. import javax.swing.JPanel;
  6. import javax.swing.JTextArea;
  7. import javax.swing.SwingConstants;
  8. import java.awt.BorderLayout;
  9. import java.awt.Font;
  10. import java.awt.GridLayout;
  11. import com.poetry.model.Poetry;
  12. public class PoetryGUIDisplay {
  13.     public static void main(String[] args) {
  14.         // 创建诗歌对象
  15.         String[] lines = {"床前明月光,", "疑是地上霜。", "举头望明月,", "低头思故乡。"};
  16.         Poetry poetry = new Poetry("静夜思", "李白", "唐", lines);
  17.         
  18.         // 创建主窗口
  19.         JFrame frame = new JFrame("中国古典诗歌展示");
  20.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  21.         frame.setSize(500, 400);
  22.         frame.setLocationRelativeTo(null); // 居中显示
  23.         
  24.         // 创建标题标签
  25.         JLabel titleLabel = new JLabel(poetry.getTitle(), SwingConstants.CENTER);
  26.         titleLabel.setFont(new Font("宋体", Font.BOLD, 24));
  27.         
  28.         // 创建作者和朝代标签
  29.         JLabel authorLabel = new JLabel("【" + poetry.getDynasty() + "】" + poetry.getAuthor(), SwingConstants.CENTER);
  30.         authorLabel.setFont(new Font("宋体", Font.ITALIC, 18));
  31.         
  32.         // 创建诗歌内容文本区域
  33.         JTextArea contentArea = new JTextArea(10, 30);
  34.         contentArea.setFont(new Font("宋体", Font.PLAIN, 20));
  35.         contentArea.setEditable(false); // 不可编辑
  36.         
  37.         // 添加诗歌内容
  38.         StringBuilder content = new StringBuilder();
  39.         for (String line : poetry.getLines()) {
  40.             content.append(line).append("\n");
  41.         }
  42.         contentArea.setText(content.toString());
  43.         
  44.         // 设置布局并添加组件
  45.         frame.setLayout(new BorderLayout(10, 10));
  46.         frame.add(titleLabel, BorderLayout.NORTH);
  47.         frame.add(contentArea, BorderLayout.CENTER);
  48.         frame.add(authorLabel, BorderLayout.SOUTH);
  49.         
  50.         // 显示窗口
  51.         frame.setVisible(true);
  52.     }
  53. }
复制代码

6.2 创建带按钮的诗歌浏览器
  1. package com.poetry.display;
  2. import javax.swing.JButton;
  3. import javax.swing.JFrame;
  4. import javax.swing.JLabel;
  5. import javax.swing.JPanel;
  6. import javax.swing.JTextArea;
  7. import javax.swing.SwingConstants;
  8. import java.awt.BorderLayout;
  9. import java.awt.Font;
  10. import java.awt.event.ActionEvent;
  11. import java.awt.event.ActionListener;
  12. import com.poetry.collection.PoetryCollection;
  13. import com.poetry.model.Poetry;
  14. public class PoetryBrowser {
  15.     private static PoetryCollection collection;
  16.     private static int currentIndex = 0;
  17.     private static JFrame frame;
  18.     private static JLabel titleLabel;
  19.     private static JLabel authorLabel;
  20.     private static JTextArea contentArea;
  21.    
  22.     public static void main(String[] args) {
  23.         // 初始化诗歌集合
  24.         initializePoetryCollection();
  25.         
  26.         // 创建主窗口
  27.         frame = new JFrame("中国古典诗歌浏览器");
  28.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  29.         frame.setSize(500, 400);
  30.         frame.setLocationRelativeTo(null); // 居中显示
  31.         
  32.         // 创建标题标签
  33.         titleLabel = new JLabel("", SwingConstants.CENTER);
  34.         titleLabel.setFont(new Font("宋体", Font.BOLD, 24));
  35.         
  36.         // 创建作者和朝代标签
  37.         authorLabel = new JLabel("", SwingConstants.CENTER);
  38.         authorLabel.setFont(new Font("宋体", Font.ITALIC, 18));
  39.         
  40.         // 创建诗歌内容文本区域
  41.         contentArea = new JTextArea(10, 30);
  42.         contentArea.setFont(new Font("宋体", Font.PLAIN, 20));
  43.         contentArea.setEditable(false); // 不可编辑
  44.         
  45.         // 创建按钮面板
  46.         JPanel buttonPanel = new JPanel();
  47.         JButton prevButton = new JButton("上一首");
  48.         JButton nextButton = new JButton("下一首");
  49.         
  50.         // 添加按钮事件监听器
  51.         prevButton.addActionListener(new ActionListener() {
  52.             @Override
  53.             public void actionPerformed(ActionEvent e) {
  54.                 if (currentIndex > 0) {
  55.                     currentIndex--;
  56.                     displayPoetry(currentIndex);
  57.                 }
  58.             }
  59.         });
  60.         
  61.         nextButton.addActionListener(new ActionListener() {
  62.             @Override
  63.             public void actionPerformed(ActionEvent e) {
  64.                 if (currentIndex < collection.getAllPoems().size() - 1) {
  65.                     currentIndex++;
  66.                     displayPoetry(currentIndex);
  67.                 }
  68.             }
  69.         });
  70.         
  71.         buttonPanel.add(prevButton);
  72.         buttonPanel.add(nextButton);
  73.         
  74.         // 设置布局并添加组件
  75.         frame.setLayout(new BorderLayout(10, 10));
  76.         frame.add(titleLabel, BorderLayout.NORTH);
  77.         frame.add(contentArea, BorderLayout.CENTER);
  78.         frame.add(authorLabel, BorderLayout.SOUTH);
  79.         frame.add(buttonPanel, BorderLayout.AFTER_LAST_LINE);
  80.         
  81.         // 显示第一首诗歌
  82.         displayPoetry(0);
  83.         
  84.         // 显示窗口
  85.         frame.setVisible(true);
  86.     }
  87.    
  88.     // 初始化诗歌集合
  89.     private static void initializePoetryCollection() {
  90.         collection = new com.poetry.collection.PoetryCollection();
  91.         
  92.         // 添加诗歌
  93.         String[] lines1 = {"床前明月光,", "疑是地上霜。", "举头望明月,", "低头思故乡。"};
  94.         collection.addPoetry(new Poetry("静夜思", "李白", "唐", lines1));
  95.         
  96.         String[] lines2 = {"白日依山尽,", "黄河入海流。", "欲穷千里目,", "更上一层楼。"};
  97.         collection.addPoetry(new Poetry("登鹳雀楼", "王之涣", "唐", lines2));
  98.         
  99.         String[] lines3 = {"春眠不觉晓,", "处处闻啼鸟。", "夜来风雨声,", "花落知多少。"};
  100.         collection.addPoetry(new Poetry("春晓", "孟浩然", "唐", lines3));
  101.         
  102.         String[] lines4 = {"千山鸟飞绝,", "万径人踪灭。", "孤舟蓑笠翁,", "独钓寒江雪。"};
  103.         collection.addPoetry(new Poetry("江雪", "柳宗元", "唐", lines4));
  104.     }
  105.    
  106.     // 显示指定索引的诗歌
  107.     private static void displayPoetry(int index) {
  108.         Poetry poetry = collection.getAllPoems().get(index);
  109.         titleLabel.setText(poetry.getTitle());
  110.         authorLabel.setText("【" + poetry.getDynasty() + "】" + poetry.getAuthor());
  111.         
  112.         StringBuilder content = new StringBuilder();
  113.         for (String line : poetry.getLines()) {
  114.             content.append(line).append("\n");
  115.         }
  116.         contentArea.setText(content.toString());
  117.         
  118.         // 更新窗口标题
  119.         frame.setTitle("中国古典诗歌浏览器 - " + (index + 1) + "/" + collection.getAllPoems().size());
  120.     }
  121. }
复制代码

7. 扩展功能:诗歌随机展示与搜索

7.1 添加随机展示功能
  1. package com.poetry.display;
  2. import javax.swing.JButton;
  3. import javax.swing.JFrame;
  4. import javax.swing.JLabel;
  5. import javax.swing.JPanel;
  6. import javax.swing.JTextArea;
  7. import javax.swing.SwingConstants;
  8. import java.awt.BorderLayout;
  9. import java.awt.Font;
  10. import java.awt.event.ActionEvent;
  11. import java.awt.event.ActionListener;
  12. import java.util.Random;
  13. import com.poetry.collection.PoetryCollection;
  14. import com.poetry.model.Poetry;
  15. public class PoetryRandomDisplay {
  16.     private static PoetryCollection collection;
  17.     private static JFrame frame;
  18.     private static JLabel titleLabel;
  19.     private static JLabel authorLabel;
  20.     private static JTextArea contentArea;
  21.     private static Random random = new Random();
  22.    
  23.     public static void main(String[] args) {
  24.         // 初始化诗歌集合
  25.         initializePoetryCollection();
  26.         
  27.         // 创建主窗口
  28.         frame = new JFrame("中国古典诗歌随机展示");
  29.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  30.         frame.setSize(500, 400);
  31.         frame.setLocationRelativeTo(null); // 居中显示
  32.         
  33.         // 创建标题标签
  34.         titleLabel = new JLabel("", SwingConstants.CENTER);
  35.         titleLabel.setFont(new Font("宋体", Font.BOLD, 24));
  36.         
  37.         // 创建作者和朝代标签
  38.         authorLabel = new JLabel("", SwingConstants.CENTER);
  39.         authorLabel.setFont(new Font("宋体", Font.ITALIC, 18));
  40.         
  41.         // 创建诗歌内容文本区域
  42.         contentArea = new JTextArea(10, 30);
  43.         contentArea.setFont(new Font("宋体", Font.PLAIN, 20));
  44.         contentArea.setEditable(false); // 不可编辑
  45.         
  46.         // 创建按钮
  47.         JButton randomButton = new JButton("随机展示");
  48.         
  49.         // 添加按钮事件监听器
  50.         randomButton.addActionListener(new ActionListener() {
  51.             @Override
  52.             public void actionPerformed(ActionEvent e) {
  53.                 displayRandomPoetry();
  54.             }
  55.         });
  56.         
  57.         // 设置布局并添加组件
  58.         frame.setLayout(new BorderLayout(10, 10));
  59.         frame.add(titleLabel, BorderLayout.NORTH);
  60.         frame.add(contentArea, BorderLayout.CENTER);
  61.         frame.add(authorLabel, BorderLayout.SOUTH);
  62.         frame.add(randomButton, BorderLayout.AFTER_LAST_LINE);
  63.         
  64.         // 显示随机诗歌
  65.         displayRandomPoetry();
  66.         
  67.         // 显示窗口
  68.         frame.setVisible(true);
  69.     }
  70.    
  71.     // 初始化诗歌集合
  72.     private static void initializePoetryCollection() {
  73.         collection = new com.poetry.collection.PoetryCollection();
  74.         
  75.         // 添加多首诗歌
  76.         String[] lines1 = {"床前明月光,", "疑是地上霜。", "举头望明月,", "低头思故乡。"};
  77.         collection.addPoetry(new Poetry("静夜思", "李白", "唐", lines1));
  78.         
  79.         String[] lines2 = {"白日依山尽,", "黄河入海流。", "欲穷千里目,", "更上一层楼。"};
  80.         collection.addPoetry(new Poetry("登鹳雀楼", "王之涣", "唐", lines2));
  81.         
  82.         String[] lines3 = {"春眠不觉晓,", "处处闻啼鸟。", "夜来风雨声,", "花落知多少。"};
  83.         collection.addPoetry(new Poetry("春晓", "孟浩然", "唐", lines3));
  84.         
  85.         String[] lines4 = {"千山鸟飞绝,", "万径人踪灭。", "孤舟蓑笠翁,", "独钓寒江雪。"};
  86.         collection.addPoetry(new Poetry("江雪", "柳宗元", "唐", lines4));
  87.         
  88.         String[] lines5 = {"日照香炉生紫烟,", "遥看瀑布挂前川。", "飞流直下三千尺,", "疑是银河落九天。"};
  89.         collection.addPoetry(new Poetry("望庐山瀑布", "李白", "唐", lines5));
  90.         
  91.         String[] lines6 = {"锄禾日当午,", "汗滴禾下土。", "谁知盘中餐,", "粒粒皆辛苦。"};
  92.         collection.addPoetry(new Poetry("悯农", "李绅", "唐", lines6));
  93.     }
  94.    
  95.     // 显示随机诗歌
  96.     private static void displayRandomPoetry() {
  97.         int index = random.nextInt(collection.getAllPoems().size());
  98.         Poetry poetry = collection.getAllPoems().get(index);
  99.         titleLabel.setText(poetry.getTitle());
  100.         authorLabel.setText("【" + poetry.getDynasty() + "】" + poetry.getAuthor());
  101.         
  102.         StringBuilder content = new StringBuilder();
  103.         for (String line : poetry.getLines()) {
  104.             content.append(line).append("\n");
  105.         }
  106.         contentArea.setText(content.toString());
  107.     }
  108. }
复制代码

7.2 添加搜索功能
  1. package com.poetry.display;
  2. import javax.swing.*;
  3. import javax.swing.event.DocumentEvent;
  4. import javax.swing.event.DocumentListener;
  5. import java.awt.*;
  6. import java.util.List;
  7. import com.poetry.collection.PoetryCollection;
  8. import com.poetry.model.Poetry;
  9. public class PoetrySearch {
  10.     private static PoetryCollection collection;
  11.     private static JFrame frame;
  12.     private static DefaultListModel<String> listModel;
  13.     private static JList<String> poetryList;
  14.     private static JTextArea contentArea;
  15.    
  16.     public static void main(String[] args) {
  17.         // 初始化诗歌集合
  18.         initializePoetryCollection();
  19.         
  20.         // 创建主窗口
  21.         frame = new JFrame("中国古典诗歌搜索");
  22.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  23.         frame.setSize(800, 600);
  24.         frame.setLocationRelativeTo(null); // 居中显示
  25.         
  26.         // 创建搜索框
  27.         JTextField searchField = new JTextField();
  28.         searchField.setFont(new Font("宋体", Font.PLAIN, 16));
  29.         
  30.         // 创建诗歌列表
  31.         listModel = new DefaultListModel<>();
  32.         poetryList = new JList<>(listModel);
  33.         poetryList.setFont(new Font("宋体", Font.PLAIN, 16));
  34.         JScrollPane listScrollPane = new JScrollPane(poetryList);
  35.         
  36.         // 创建诗歌内容显示区域
  37.         contentArea = new JTextArea();
  38.         contentArea.setFont(new Font("宋体", Font.PLAIN, 20));
  39.         contentArea.setEditable(false);
  40.         JScrollPane contentScrollPane = new JScrollPane(contentArea);
  41.         
  42.         // 初始化诗歌列表
  43.         updatePoetryList(collection.getAllPoems());
  44.         
  45.         // 添加搜索功能
  46.         searchField.getDocument().addDocumentListener(new DocumentListener() {
  47.             @Override
  48.             public void insertUpdate(DocumentEvent e) {
  49.                 searchPoetry(searchField.getText());
  50.             }
  51.             
  52.             @Override
  53.             public void removeUpdate(DocumentEvent e) {
  54.                 searchPoetry(searchField.getText());
  55.             }
  56.             
  57.             @Override
  58.             public void changedUpdate(DocumentEvent e) {
  59.                 searchPoetry(searchField.getText());
  60.             }
  61.         });
  62.         
  63.         // 添加列表选择事件
  64.         poetryList.addListSelectionListener(e -> {
  65.             if (!e.getValueIsAdjusting()) {
  66.                 String selectedValue = poetryList.getSelectedValue();
  67.                 if (selectedValue != null) {
  68.                     String title = selectedValue.split(" - ")[0];
  69.                     Poetry poetry = collection.findPoetryByTitle(title);
  70.                     if (poetry != null) {
  71.                         displayPoetry(poetry);
  72.                     }
  73.                 }
  74.             }
  75.         });
  76.         
  77.         // 设置布局
  78.         frame.setLayout(new BorderLayout(5, 5));
  79.         
  80.         // 顶部面板 - 搜索框
  81.         JPanel topPanel = new JPanel(new BorderLayout());
  82.         topPanel.add(new JLabel("搜索:"), BorderLayout.WEST);
  83.         topPanel.add(searchField, BorderLayout.CENTER);
  84.         
  85.         // 分割面板
  86.         JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, listScrollPane, contentScrollPane);
  87.         splitPane.setDividerLocation(250);
  88.         
  89.         // 添加组件到主窗口
  90.         frame.add(topPanel, BorderLayout.NORTH);
  91.         frame.add(splitPane, BorderLayout.CENTER);
  92.         
  93.         // 显示窗口
  94.         frame.setVisible(true);
  95.     }
  96.    
  97.     // 初始化诗歌集合
  98.     private static void initializePoetryCollection() {
  99.         collection = new com.poetry.collection.PoetryCollection();
  100.         
  101.         // 添加多首诗歌
  102.         String[] lines1 = {"床前明月光,", "疑是地上霜。", "举头望明月,", "低头思故乡。"};
  103.         collection.addPoetry(new Poetry("静夜思", "李白", "唐", lines1));
  104.         
  105.         String[] lines2 = {"白日依山尽,", "黄河入海流。", "欲穷千里目,", "更上一层楼。"};
  106.         collection.addPoetry(new Poetry("登鹳雀楼", "王之涣", "唐", lines2));
  107.         
  108.         String[] lines3 = {"春眠不觉晓,", "处处闻啼鸟。", "夜来风雨声,", "花落知多少。"};
  109.         collection.addPoetry(new Poetry("春晓", "孟浩然", "唐", lines3));
  110.         
  111.         String[] lines4 = {"千山鸟飞绝,", "万径人踪灭。", "孤舟蓑笠翁,", "独钓寒江雪。"};
  112.         collection.addPoetry(new Poetry("江雪", "柳宗元", "唐", lines4));
  113.         
  114.         String[] lines5 = {"日照香炉生紫烟,", "遥看瀑布挂前川。", "飞流直下三千尺,", "疑是银河落九天。"};
  115.         collection.addPoetry(new Poetry("望庐山瀑布", "李白", "唐", lines5));
  116.         
  117.         String[] lines6 = {"锄禾日当午,", "汗滴禾下土。", "谁知盘中餐,", "粒粒皆辛苦。"};
  118.         collection.addPoetry(new Poetry("悯农", "李绅", "唐", lines6));
  119.     }
  120.    
  121.     // 更新诗歌列表
  122.     private static void updatePoetryList(List<Poetry> poems) {
  123.         listModel.clear();
  124.         for (Poetry poetry : poems) {
  125.             listModel.addElement(poetry.getTitle() + " - " + poetry.getAuthor() + " (" + poetry.getDynasty() + ")");
  126.         }
  127.     }
  128.    
  129.     // 搜索诗歌
  130.     private static void searchPoetry(String keyword) {
  131.         if (keyword == null || keyword.trim().isEmpty()) {
  132.             updatePoetryList(collection.getAllPoems());
  133.             return;
  134.         }
  135.         
  136.         List<Poetry> result = collection.findPoemsByAuthor(keyword);
  137.         if (result.isEmpty()) {
  138.             // 如果按作者搜索没有结果,尝试按标题搜索
  139.             Poetry poetry = collection.findPoetryByTitle(keyword);
  140.             if (poetry != null) {
  141.                 result.add(poetry);
  142.             }
  143.         }
  144.         
  145.         updatePoetryList(result);
  146.     }
  147.    
  148.     // 显示诗歌内容
  149.     private static void displayPoetry(Poetry poetry) {
  150.         StringBuilder content = new StringBuilder();
  151.         content.append(poetry.getTitle()).append("\n\n");
  152.         content.append("【").append(poetry.getDynasty()).append("】").append(poetry.getAuthor()).append("\n\n");
  153.         for (String line : poetry.getLines()) {
  154.             content.append(line).append("\n");
  155.         }
  156.         contentArea.setText(content.toString());
  157.     }
  158. }
复制代码

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平台,创建移动诗歌应用。

通过不断扩展和完善这个项目,初学者可以逐步掌握更多的编程技能,同时深入欣赏和理解中国古典诗歌的魅力,实现技术与文化的完美结合。
「七転び八起き(ななころびやおき)」
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则