본문 바로가기
2023/PROJECT

[JAVA] 달력 추가할 것

by Or0i쿠 2023. 6. 27.
달력의 날짜를 클릭하면 클릭한 날짜를 받아오는 변수를 추가 하기
// ...
JLabel dayLabel = new JLabel(String.valueOf(day));
dayLabel.addMouseListener(new MouseAdapter() {
    @Override
    public void mouseClicked(MouseEvent e) {
        int clickedDay = Integer.parseInt(dayLabel.getText());
        Calendar clickedDate = (Calendar) calendar.clone();
        clickedDate.set(Calendar.DAY_OF_MONTH, clickedDay);
        System.out.println(clickedDate.getTime());
        
        // 클릭한 날짜를 저장하는 변수에 값을 할당
        // 변수의 타입은 Calendar 혹은 Date
    }
});
styleLabel(dayLabel, new Font("NEXON Lv1 Gothic", Font.PLAIN, 12));
daysPanel.add(dayLabel);
// ...
package UiTest;

import java.awt.*;
import java.awt.event.ActionListener;
import java.text.*;
import java.util.*;
import javax.swing.*;

public class CalPanel extends JPanel {
    private JLabel dateLabel;

    public CalPanel() {
        setLayout(new BorderLayout());
        setOpaque(false);
        setBounds(21, 76, 425, 358);

        // 날짜 라벨을 포함하는 헤더 패널 생성
        JPanel headerPanel = new JPanel(new BorderLayout());
        headerPanel.setOpaque(false);
        add(headerPanel, BorderLayout.NORTH);

        // 현재 날짜를 출력하는 라벨 생성
        dateLabel = new JLabel(getDateString(new Date()));
        styleLabel(dateLabel, new Font("NEXON Lv1 Gothic", Font.BOLD, 25));
        headerPanel.add(dateLabel, BorderLayout.CENTER);

        headerPanel.setBorder(BorderFactory.createEmptyBorder(20, 0, 0, 0));

        // 캘린더 패널 생성
        JPanel calendarPanel = new JPanel(new BorderLayout());
        calendarPanel.setOpaque(false);
        add(calendarPanel, BorderLayout.CENTER);

        // 요일 라벨이 위치한 패널 생성
        JPanel weekPanel = new JPanel(new GridLayout(0, 7));
        weekPanel.setOpaque(false);
        calendarPanel.add(weekPanel, BorderLayout.NORTH);
        weekPanel.setBorder(BorderFactory.createEmptyBorder(20, 0, 0, 0));

        // 요일 라벨을 생성하고 패널에 추가
        String[] weekdays = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
        for (String weekday : weekdays) {
            JLabel label = new JLabel(weekday);
            styleLabel(label, new Font("NEXON Lv1 Gothic", Font.BOLD, 12));
            label.setHorizontalAlignment(SwingConstants.CENTER);
            weekPanel.add(label);
        }

        // 날짜 라벨(1~31)이 위치한 패널 생성
        JPanel daysPanel = new JPanel(new GridLayout(0, 7));
        daysPanel.setOpaque(false);
        calendarPanel.add(daysPanel, BorderLayout.CENTER);

        // 현재 월의 날짜 라벨을 생성하고 패널에 추가
        Calendar calendar = Calendar.getInstance();
        renderMonth(daysPanel, calendar);

        // 이전 달, 다음 달 버튼이 위치한 패널 생성
        add(createButtonPanel(daysPanel, calendar), BorderLayout.SOUTH);
    }

    // 현재 날짜를 yyyy MMMM 형식의 문자열로 반환
    private String getDateString(Date date) {
        DateFormat dateFormat = new SimpleDateFormat("yyyy MMMM");
        return dateFormat.format(date);
    }

    // 라벨의 스타일을 설정
    private void styleLabel(JLabel label, Font font) {
        label.setHorizontalAlignment(SwingConstants.CENTER);
        label.setVerticalAlignment(SwingConstants.CENTER);
        label.setFont(font);
    }

    // 현재 월의 날짜 라벨을 생성하고 패널에 추가
    private void renderMonth(JPanel daysPanel, Calendar calendar) {
        clearPanel(daysPanel);
        calendar.set(Calendar.DAY_OF_MONTH, 1); // 현재 월의 1일로 설정

        int startingDayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); // 현재 월의 1일의 요일
        int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH); // 현재 월의 일수

        // 1일 부터 시작하는 요일까지 빈 라벨 추가
        for (int i = 1; i < startingDayOfWeek; i++) {
            daysPanel.add(new JLabel(""));
        }

        // 현재 월의 모든 날짜 라벨 추가
        for (int day = 1; day <= daysInMonth; day++) {
            JLabel dayLabel = new JLabel(String.valueOf(day));
            styleLabel(dayLabel, new Font("NEXON Lv1 Gothic", Font.PLAIN, 12));
            daysPanel.add(dayLabel);
        }
    }

    // 패널의 컴포넌트 모두 삭제
    private void clearPanel(JPanel panel) {
        panel.removeAll();
        panel.revalidate();
        panel.repaint();
    }

    // 버튼 생성
    private JButton createButton(Font font, String text, ActionListener listener) {
        JButton button = new JButton(text);
        button.setFont(font);
        button.addActionListener(listener);
        button.setOpaque(false);
        button.setContentAreaFilled(false);
        button.setBorderPainted(false);
        return button;
    }

    // 이전 달, 다음 달 버튼이 위치한 패널 생성
    private JPanel createButtonPanel(final JPanel daysPanel, final Calendar calendar) {
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        buttonPanel.setOpaque(false);

        // 이전 달 버튼
        JButton prevMonthButton = createButton(new Font("NEXON Lv1 Gothic", Font.BOLD, 12), "<", e -> {
            calendar.add(Calendar.MONTH, -1); // 이전 달로 변경
            renderMonth(daysPanel, calendar); // 날짜 라벨 업데이트
            dateLabel.setText(getDateString(calendar.getTime())); // 날짜 라벨 업데이트
        });
        buttonPanel.add(prevMonthButton);

        // 다음 달 버튼
        JButton nextMonthButton = createButton(new Font("NEXON Lv1 Gothic", Font.BOLD, 12), ">", e -> {
            calendar.add(Calendar.MONTH, 1); // 다음 달로 변경
            renderMonth(daysPanel, calendar); //// 날짜 라벨 업데이트
            dateLabel.setText(getDateString(calendar.getTime())); // 날짜 라벨 업데이트
        });
        buttonPanel.add(nextMonthButton);

        return buttonPanel;
    }
}

'2023 > PROJECT' 카테고리의 다른 글

html - search  (0) 2023.08.28
[JAVA] 유저 값 가져오기  (0) 2023.06.27
[SPL] 관계형 데이터베이스  (0) 2023.06.27
[JAVA]SWING  (0) 2023.06.23
[JAVA] 캘린더 UI (클래스 정리)  (0) 2023.06.22