设计GUI界面的日历记事本,系统将日历和记事本结合在一起,可以方便地保存、查看日志,即可以记录与任何日期有关的内容并可以随时查看与某个日期相对应的日志内容。要求能够运用合适的数据结构及算法存储和处理数据,达到相应的时间和空间效率要求。请用Java语言完成并给出源代码
时间: 2024-02-23 21:02:39 浏览: 17
好的,这是一个Java语言实现的日历记事本,它基于Java Swing库构建GUI界面,使用了合适的数据结构和算法来存储和处理数据,以达到相应的时间和空间效率要求:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class CalendarNotebook extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JTextArea textArea;
private JCalendar calendar;
private JButton saveButton;
private JButton loadButton;
private Map<String, String> notes = new HashMap<String, String>();
public CalendarNotebook() {
super("Calendar Notebook");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(1, 2));
calendar = new JCalendar();
panel.add(calendar);
textArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(textArea);
panel.add(scrollPane);
add(panel, BorderLayout.CENTER);
JPanel buttonPanel = new JPanel();
saveButton = new JButton("Save");
saveButton.addActionListener(this);
buttonPanel.add(saveButton);
loadButton = new JButton("Load");
loadButton.addActionListener(this);
buttonPanel.add(loadButton);
add(buttonPanel, BorderLayout.SOUTH);
setVisible(true);
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() == saveButton) {
String date = getDateStr(calendar.getDate());
String note = textArea.getText();
notes.put(date, note);
JOptionPane.showMessageDialog(this, "Note saved successfully!");
} else if (event.getSource() == loadButton) {
String date = getDateStr(calendar.getDate());
String note = notes.get(date);
if (note != null) {
textArea.setText(note);
JOptionPane.showMessageDialog(this, "Note loaded successfully!");
} else {
textArea.setText("");
JOptionPane.showMessageDialog(this, "No note found for this date.");
}
}
}
private String getDateStr(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH) + 1;
int day = cal.get(Calendar.DAY_OF_MONTH);
return year + "-" + month + "-" + day;
}
public static void main(String[] args) {
new CalendarNotebook();
}
}
```
这个程序可以保存和加载任意日期的日志内容,每个日志内容可以包含任意长度的文本。它使用了HashMap来存储日志信息,键是日期字符串(格式为“年-月-日”),值是对应的日志内容。当用户单击“保存”按钮时,程序会将当前日期和文本框内容保存到HashMap中;当用户单击“加载”按钮时,程序会从HashMap中取出对应日期的日志内容,并显示在文本框中。如果没有找到对应日期的日志内容,程序会提示用户。
在这个程序中,存储和处理数据的时间和空间效率都很高。HashMap可以实现O(1)的常数时间复杂度的插入、查找和删除操作,因此可以快速地存储和查找任意日期的日志内容。同时,HashMap也可以动态调整大小,以适应数据的增长或减少,因此空间占用也比较合理。