java面板输入年份和月份,将月历表输出到面板上
时间: 2024-04-29 21:23:12 浏览: 85
以下是一个简单的Java程序,可以让用户输入年份和月份,然后在面板上输出相应的月历表:
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CalendarPanel extends JPanel {
private JLabel monthLabel;
private JButton prevButton, nextButton;
private JPanel calendarPanel;
private int month, year;
public CalendarPanel() {
// 初始化月份和年份
month = java.util.Calendar.getInstance().get(java.util.Calendar.MONTH);
year = java.util.Calendar.getInstance().get(java.util.Calendar.YEAR);
// 创建月份标签和按钮
monthLabel = new JLabel();
prevButton = new JButton("<");
nextButton = new JButton(">");
// 创建日历面板
calendarPanel = new JPanel(new GridLayout(0, 7));
// 添加组件
add(monthLabel);
add(prevButton);
add(nextButton);
add(calendarPanel);
// 设置按钮事件处理程序
prevButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (month == 0) {
month = 11;
year--;
} else {
month--;
}
updateCalendar();
}
});
nextButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (month == 11) {
month = 0;
year++;
} else {
month++;
}
updateCalendar();
}
});
// 更新日历表
updateCalendar();
}
private void updateCalendar() {
// 清空日历面板
calendarPanel.removeAll();
// 更新月份标签
monthLabel.setText(new java.text.SimpleDateFormat("MMMM yyyy").format(new java.util.Date(year, month, 1)));
// 获取这个月的第一天和最后一天
java.util.Calendar cal = java.util.Calendar.getInstance();
cal.set(year, month, 1);
int daysInMonth = cal.getActualMaximum(java.util.Calendar.DAY_OF_MONTH);
int dayOfWeek = cal.get(java.util.Calendar.DAY_OF_WEEK);
// 添加空白标签,使日历表开始于星期日
for (int i = 1; i < dayOfWeek; i++) {
calendarPanel.add(new JLabel(""));
}
// 添加日期标签
for (int i = 1; i <= daysInMonth; i++) {
final int day = i;
JButton button = new JButton(Integer.toString(i));
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(CalendarPanel.this, "You clicked on day " + day);
}
});
calendarPanel.add(button);
}
// 重新绘制面板
validate();
repaint();
}
public static void main(String[] args) {
JFrame frame = new JFrame("Calendar");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new CalendarPanel());
frame.pack();
frame.setVisible(true);
}
}
```
该程序使用了Java的Swing库,在面板上绘制了一个月历表。当用户点击某一天时,程序会弹出一个对话框,告诉用户他们点击了哪一天。
阅读全文