java万年历图形化界面
时间: 2023-10-14 18:25:13 浏览: 244
要实现Java万年历的图形化界面,你可以使用Swing或JavaFX等GUI工具包。以下是一个简单的Java万年历图形化界面的实现示例:
```java
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class CalendarGUI extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JLabel timeLabel;
private JPanel calendarPanel;
public CalendarGUI() {
super("Java万年历");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
timeLabel = new JLabel();
timeLabel.setHorizontalAlignment(JLabel.CENTER);
timeLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
calendarPanel = new JPanel(new GridLayout(7, 7));
calendarPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
String[] daysOfWeek = {"日", "一", "二", "三", "四", "五", "六"};
for (String day : daysOfWeek) {
calendarPanel.add(new JLabel(day, JLabel.CENTER));
}
refreshCalendar(Calendar.getInstance().getTime());
add(timeLabel, BorderLayout.NORTH);
add(calendarPanel, BorderLayout.CENTER);
setVisible(true);
}
public void refreshCalendar(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.DATE, 1);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月");
timeLabel.setText(sdf.format(date));
calendarPanel.removeAll();
String[] daysOfWeek = {"日", "一", "二", "三", "四", "五", "六"};
for (String day : daysOfWeek) {
calendarPanel.add(new JLabel(day, JLabel.CENTER));
}
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
for (int i = 0; i < dayOfWeek; i++) {
calendarPanel.add(new JLabel(""));
}
int daysOfMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
for (int i = 1; i <= daysOfMonth; i++) {
JButton button = new JButton(String.valueOf(i));
button.addActionListener(this);
calendarPanel.add(button);
}
int remainingDays = 42 - daysOfMonth - dayOfWeek;
for (int i = 0; i < remainingDays; i++) {
calendarPanel.add(new JLabel(""));
}
validate();
}
public static void main(String[] args) {
new CalendarGUI();
}
@Override
public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
int day = Integer.parseInt(button.getText());
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH, day);
refreshCalendar(calendar.getTime());
}
}
```
这个示例程序使用了Swing工具包来实现Java万年历的图形化界面。程序中的`refreshCalendar()`方法负责根据给定的日期更新日历面板的内容。在程序中,我们使用了JButton、JLabel和JPanel等组件来实现日历面板。我们还为每个按钮添加了动作监听器,以便在用户单击某个日期时更新日历面板。
阅读全文