如何在日历上突出显示日期

时间:2015-06-21 12:34:13

标签: java calendar

所以我有一个程序,它接收用户的某些日期(带有组合框和旋转器的gui)和另一个显示日历的日期。我希望用户在gui中输入的日期在我的日历上突出显示... help !!!

import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

public class CalendarProgram{
    static JLabel lblMonth, lblYear;
    static JButton btnPrev, btnNext;
    static JTable tblCalendar;
    static JComboBox cmbYear;
    static JFrame frmMain;
    static Container pane;
    static DefaultTableModel mtblCalendar; //Table model
    static JScrollPane stblCalendar; //The scrollpane
    static JPanel pnlCalendar;
    static int realYear, realMonth, realDay, currentYear, currentMonth;

    public static void main (String args[]){
        //Look and feel
        try {UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());}
        catch (ClassNotFoundException e) {}
        catch (InstantiationException e) {}
        catch (IllegalAccessException e) {}
        catch (UnsupportedLookAndFeelException e) {}

        //Prepare frame
        frmMain = new JFrame ("Gestionnaire de clients"); //Create frame
        frmMain.setSize(330, 375); //Set size to 400x400 pixels
        pane = frmMain.getContentPane(); //Get content pane
        pane.setLayout(null); //Apply null layout
        frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Close when X is clicked

        //Create controls
        lblMonth = new JLabel ("January");
        lblYear = new JLabel ("Change year:");
        cmbYear = new JComboBox();
        btnPrev = new JButton ("<<");
        btnNext = new JButton (">>");
        mtblCalendar = new DefaultTableModel(){public boolean isCellEditable(int rowIndex, int mColIndex){return false;}};
        tblCalendar = new JTable(mtblCalendar);
        stblCalendar = new JScrollPane(tblCalendar);
        pnlCalendar = new JPanel(null);

        //Set border
        pnlCalendar.setBorder(BorderFactory.createTitledBorder("Calendar"));

        //Register action listeners
        btnPrev.addActionListener(new btnPrev_Action());
        btnNext.addActionListener(new btnNext_Action());
        cmbYear.addActionListener(new cmbYear_Action());

        //Add controls to pane
        pane.add(pnlCalendar);
        pnlCalendar.add(lblMonth);
        pnlCalendar.add(lblYear);
        pnlCalendar.add(cmbYear);
        pnlCalendar.add(btnPrev);
        pnlCalendar.add(btnNext);
        pnlCalendar.add(stblCalendar);

        //Set bounds
        pnlCalendar.setBounds(0, 0, 320, 335);
        lblMonth.setBounds(160-lblMonth.getPreferredSize().width/2, 25, 100, 25);
        lblYear.setBounds(10, 305, 80, 20);
        cmbYear.setBounds(230, 305, 80, 20);
        btnPrev.setBounds(10, 25, 50, 25);
        btnNext.setBounds(260, 25, 50, 25);
        stblCalendar.setBounds(10, 50, 300, 250);

        //Make frame visible
        frmMain.setResizable(false);
        frmMain.setVisible(true);

        //Get real month/year
        GregorianCalendar cal = new GregorianCalendar(); //Create calendar
        realDay = cal.get(GregorianCalendar.DAY_OF_MONTH); //Get day
        realMonth = cal.get(GregorianCalendar.MONTH); //Get month
        realYear = cal.get(GregorianCalendar.YEAR); //Get year
        currentMonth = realMonth; //Match month and year
        currentYear = realYear;

        //Add headers
        String[] headers = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; //All headers
        for (int i=0; i<7; i++){
            mtblCalendar.addColumn(headers[i]);
        }

        tblCalendar.getParent().setBackground(tblCalendar.getBackground()); //Set background

        //No resize/reorder
        tblCalendar.getTableHeader().setResizingAllowed(false);
        tblCalendar.getTableHeader().setReorderingAllowed(false);

        //Single cell selection
        tblCalendar.setColumnSelectionAllowed(true);
        tblCalendar.setRowSelectionAllowed(true);
        tblCalendar.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        //Set row/column count
        tblCalendar.setRowHeight(38);
        mtblCalendar.setColumnCount(7);
        mtblCalendar.setRowCount(6);

        //Populate table
        for (int i=realYear-100; i<=realYear+100; i++){
            cmbYear.addItem(String.valueOf(i));
        }

        //Refresh calendar
        refreshCalendar (realMonth, realYear); //Refresh calendar
    }

    public static void refreshCalendar(int month, int year){
        //Variables
        String[] months =  {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
        int nod, som; //Number Of Days, Start Of Month

        //Allow/disallow buttons
        btnPrev.setEnabled(true);
        btnNext.setEnabled(true);
        if (month == 0 && year <= realYear-10){btnPrev.setEnabled(false);} //Too early
        if (month == 11 && year >= realYear+100){btnNext.setEnabled(false);} //Too late
        lblMonth.setText(months[month]); //Refresh the month label (at the top)
        lblMonth.setBounds(160-lblMonth.getPreferredSize().width/2, 25, 180, 25); //Re-align label with calendar
        cmbYear.setSelectedItem(String.valueOf(year)); //Select the correct year in the combo box

        //Clear table
        for (int i=0; i<6; i++){
            for (int j=0; j<7; j++){
                mtblCalendar.setValueAt(null, i, j);
            }
        }

        //Get first day of month and number of days
        GregorianCalendar cal = new GregorianCalendar(year, month, 1);
        nod = cal.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);
        som = cal.get(GregorianCalendar.DAY_OF_WEEK);

        //Draw calendar
        for (int i=1; i<=nod; i++){
            int row = new Integer((i+som-2)/7);
            int column  =  (i+som-2)%7;
            mtblCalendar.setValueAt(i, row, column);
        }

        //Apply renderers
        tblCalendar.setDefaultRenderer(tblCalendar.getColumnClass(0), new tblCalendarRenderer());
    }

    static class tblCalendarRenderer extends DefaultTableCellRenderer{
        public Component getTableCellRendererComponent (JTable table, Object value, boolean selected, boolean focused, int row, int column){
            super.getTableCellRendererComponent(table, value, selected, focused, row, column);
            if (column == 0 || column == 6){ //Week-end
                setBackground(new Color(255, 220, 220));
            }
            else{ //Week
                setBackground(new Color(255, 255, 255));
            }
            if (value != null){
                if (Integer.parseInt(value.toString()) == realDay && currentMonth == realMonth && currentYear == realYear){ //Today
                    setBackground(new Color(220, 220, 255));
                }
            }
            setBorder(null);
            setForeground(Color.black);
            return this;
        }
    }

    static class btnPrev_Action implements ActionListener{
        public void actionPerformed (ActionEvent e){
            if (currentMonth == 0){ //Back one year
                currentMonth = 11;
                currentYear -= 1;
            }
            else{ //Back one month
                currentMonth -= 1;
            }
            refreshCalendar(currentMonth, currentYear);
        }
    }
    static class btnNext_Action implements ActionListener{
        public void actionPerformed (ActionEvent e){
            if (currentMonth == 11){ //Foward one year
                currentMonth = 0;
                currentYear += 1;
            }
            else{ //Foward one month
                currentMonth += 1;
            }
            refreshCalendar(currentMonth, currentYear);
        }
    }
    static class cmbYear_Action implements ActionListener{
        public void actionPerformed (ActionEvent e){
            if (cmbYear.getSelectedItem() != null){
                String b = cmbYear.getSelectedItem().toString();
                currentYear = Integer.parseInt(b);
                refreshCalendar(currentMonth, currentYear);
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

这是用户输入日期的方式....

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package notifyme;
import java.awt.*;
import java.awt.event.*;
import java.util.Calendar;
import java.text.SimpleDateFormat;

import javax.swing.*;
import javax.swing.event.PopupMenuListener;
import javax.swing.event.PopupMenuEvent;
import javax.swing.plaf.ComboBoxUI;
import javax.swing.plaf.basic.ComboPopup;
import javax.swing.plaf.metal.MetalComboBoxUI;
import javax.swing.border.Border;
import javax.swing.border.EtchedBorder;
import javax.swing.border.EmptyBorder;

import com.sun.java.swing.plaf.motif.MotifComboBoxUI;
import com.sun.java.swing.plaf.windows.WindowsComboBoxUI;

/**
 *
 * @author hermela
 */

public class DateComboBox extends JComboBox {

    protected SimpleDateFormat dateFormat = new SimpleDateFormat("MMM d, yyyy");
    public void setDateFormat(SimpleDateFormat dateFormat) {
    this.dateFormat = dateFormat;
    }
    public void setSelectedItem(Object item) {
    // Could put extra logic here or in renderer when item is instanceof Date, Calendar, or String
    // Dont keep a list ... just the currently selected item
    removeAllItems(); // hides the popup if visible
    addItem(item);
    super.setSelectedItem(item);
    }

    public void updateUI() {
    ComboBoxUI cui = (ComboBoxUI) UIManager.getUI(this);
    if (cui instanceof MetalComboBoxUI) {
        cui = new MetalDateComboBoxUI();
    } else if (cui instanceof MotifComboBoxUI) {
        cui = new MotifDateComboBoxUI();        
    } else if (cui instanceof WindowsComboBoxUI) {
        cui = new WindowsDateComboBoxUI();
    }
        setUI(cui);
    }

    // Inner classes are used purely to keep DateComboBox component in one file
    //////////////////////////////////////////////////////////////
    // UI Inner classes -- one for each supported Look and Feel
    //////////////////////////////////////////////////////////////

    class MetalDateComboBoxUI extends MetalComboBoxUI {
    protected ComboPopup createPopup() {
        return new DatePopup( comboBox );
    }
    }

    class WindowsDateComboBoxUI extends WindowsComboBoxUI {
    protected ComboPopup createPopup() {
        return new DatePopup( comboBox );
    }
    }

    class MotifDateComboBoxUI extends MotifComboBoxUI {
    protected ComboPopup createPopup() {
        return new DatePopup( comboBox );
    }
    }

    //////////////////////////////////////////////////////////////
    // DatePopup inner class
    //////////////////////////////////////////////////////////////

    class DatePopup implements ComboPopup, MouseMotionListener, 
                   MouseListener, KeyListener, PopupMenuListener {

    protected JComboBox comboBox;
    protected Calendar calendar;
    protected JPopupMenu popup;
    protected JLabel monthLabel;
    protected JPanel days = null;
    protected SimpleDateFormat monthFormat = new SimpleDateFormat("MMM yyyy");

    protected Color selectedBackground;
    protected Color selectedForeground;
    protected Color background;
    protected Color foreground;

    public DatePopup(JComboBox comboBox) {
        this.comboBox = comboBox;
        calendar = Calendar.getInstance();
        // check Look and Feel
        background = UIManager.getColor("ComboBox.background");
        foreground = UIManager.getColor("ComboBox.foreground");
        selectedBackground = UIManager.getColor("ComboBox.selectionBackground");
        selectedForeground = UIManager.getColor("ComboBox.selectionForeground");

        initializePopup();
    }

    //========================================
    // begin ComboPopup method implementations
    //
        public void show() {
        try {
        // if setSelectedItem() was called with a valid date, adjust the calendar
        calendar.setTime( dateFormat.parse( comboBox.getSelectedItem().toString() ) );
        } catch (Exception e) {}
        updatePopup(); 
        popup.show(comboBox, 0, comboBox.getHeight());
        }

    public void hide() {
        popup.setVisible(false);
    }

    protected JList list = new JList();
    public JList getList() {
        return list;
    }

    public MouseListener getMouseListener() {
        return this;
    }

    public MouseMotionListener getMouseMotionListener() {
        return this;
    }

    public KeyListener getKeyListener() {
        return this;
    }

    public boolean isVisible() {
        return popup.isVisible();
    }

    public void uninstallingUI() {
        popup.removePopupMenuListener(this);
    }

    //
    // end ComboPopup method implementations
    //======================================



    //===================================================================
    // begin Event Listeners
    //

    // MouseListener

    public void mousePressed( MouseEvent e ) {}
        public void mouseReleased( MouseEvent e ) {}
    // something else registered for MousePressed
    public void mouseClicked(MouseEvent e) {
            if ( !SwingUtilities.isLeftMouseButton(e) )
                return;
            if ( !comboBox.isEnabled() )
                return;
        if ( comboBox.isEditable() ) {
        comboBox.getEditor().getEditorComponent().requestFocus();
        } else {
        comboBox.requestFocus();
        }
        togglePopup();
    }

    protected boolean mouseInside = false;
    public void mouseEntered(MouseEvent e) {
        mouseInside = true;
    }
    public void mouseExited(MouseEvent e) {
        mouseInside = false;
    }

    // MouseMotionListener
    public void mouseDragged(MouseEvent e) {}
    public void mouseMoved(MouseEvent e) {}

    // KeyListener
    public void keyPressed(KeyEvent e) {}
    public void keyTyped(KeyEvent e) {}           
    public void keyReleased( KeyEvent e ) {
        if ( e.getKeyCode() == KeyEvent.VK_SPACE ||
         e.getKeyCode() == KeyEvent.VK_ENTER ) {
        togglePopup();
        }
    }

    /**
     * Variables hideNext and mouseInside are used to 
     * hide the popupMenu by clicking the mouse in the JComboBox
     */
    public void popupMenuCanceled(PopupMenuEvent e) {}
    protected boolean hideNext = false;
    public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
        hideNext = mouseInside;
    }
    public void popupMenuWillBecomeVisible(PopupMenuEvent e) {}

    //
    // end Event Listeners
    //=================================================================

    //===================================================================
    // begin Utility methods
    //

    protected void togglePopup() {
        if ( isVisible() || hideNext ) { 
        hide();
        } else {
        show();
        }
        hideNext = false;
    }

    //
    // end Utility methods
    //=================================================================

    // Note *** did not use JButton because Popup closes when pressed
    protected JLabel createUpdateButton(final int field, final int amount) {
        final JLabel label = new JLabel();
        final Border selectedBorder = new EtchedBorder();
        final Border unselectedBorder = new EmptyBorder(selectedBorder.getBorderInsets(new JLabel()));
        label.setBorder(unselectedBorder);
        label.setForeground(foreground);
        label.addMouseListener(new MouseAdapter() {
            public void mouseReleased(MouseEvent e) {
            calendar.add(field, amount);
            updatePopup();
            }
            public void mouseEntered(MouseEvent e) {
            label.setBorder(selectedBorder);
            }
            public void mouseExited(MouseEvent e) {
            label.setBorder(unselectedBorder);
            }
        });
        return label;
    }


    protected void initializePopup() {
        JPanel header = new JPanel(); // used Box, but it wasn't Opaque
        header.setLayout(new BoxLayout(header, BoxLayout.X_AXIS));
        header.setBackground(background);
        header.setOpaque(true);

        JLabel label;
        label = createUpdateButton(Calendar.YEAR, -1);
        label.setText("<<");
        label.setToolTipText("Previous Year");

        header.add(Box.createHorizontalStrut(12));
        header.add(label);
        header.add(Box.createHorizontalStrut(12));

        label = createUpdateButton(Calendar.MONTH, -1);
        label.setText("<");
        label.setToolTipText("Previous Month");
        header.add(label);

        monthLabel = new JLabel("", JLabel.CENTER);
        monthLabel.setForeground(foreground);
        header.add(Box.createHorizontalGlue());
        header.add(monthLabel);
        header.add(Box.createHorizontalGlue());

        label = createUpdateButton(Calendar.MONTH, 1);
        label.setText(">");
        label.setToolTipText("Next Month");
        header.add(label);

        label = createUpdateButton(Calendar.YEAR, 1);
        label.setText(">>");
        label.setToolTipText("Next Year");

        header.add(Box.createHorizontalStrut(12));
        header.add(label);
        header.add(Box.createHorizontalStrut(12));

        popup = new JPopupMenu();
        popup.setBorder(BorderFactory.createLineBorder(Color.black));
        popup.setLayout(new BorderLayout());
        popup.setBackground(background);
        popup.addPopupMenuListener(this);
        popup.add(BorderLayout.NORTH, header);
    }

    // update the Popup when either the month or the year of the calendar has been changed
    protected void updatePopup() {
        monthLabel.setText( monthFormat.format(calendar.getTime()) );
        if (days != null) {
        popup.remove(days);
        }
        days = new JPanel(new GridLayout(0, 7));
        days.setBackground(background);
        days.setOpaque(true);

        Calendar setupCalendar = (Calendar) calendar.clone();
        setupCalendar.set(Calendar.DAY_OF_WEEK, setupCalendar.getFirstDayOfWeek());
        for (int i = 0; i < 7; i++) {
        int dayInt = setupCalendar.get(Calendar.DAY_OF_WEEK);
        JLabel label = new JLabel();
        label.setHorizontalAlignment(JLabel.CENTER);
        label.setForeground(foreground);
        if (dayInt == Calendar.SUNDAY) {
            label.setText("Sun");
        } else if (dayInt == Calendar.MONDAY) {
            label.setText("Mon");
        } else if (dayInt == Calendar.TUESDAY) {
            label.setText("Tue");
        } else if (dayInt == Calendar.WEDNESDAY) {
            label.setText("Wed");
        } else if (dayInt == Calendar.THURSDAY) {
            label.setText("Thu");
        } else if (dayInt == Calendar.FRIDAY) {
            label.setText("Fri");
        } else if (dayInt == Calendar.SATURDAY){
            label.setText("Sat");
        }
        days.add(label);
        setupCalendar.roll(Calendar.DAY_OF_WEEK, true);
        }

        setupCalendar = (Calendar) calendar.clone();
        setupCalendar.set(Calendar.DAY_OF_MONTH, 1);
        int first = setupCalendar.get(Calendar.DAY_OF_WEEK);
        for (int i = 0; i < (first - 1); i++) {
        days.add(new JLabel(""));       
        }
        for (int i = 1; i <= setupCalendar.getActualMaximum(Calendar.DAY_OF_MONTH); i++) {    
        final int day = i;
        final JLabel label = new JLabel(String.valueOf(day));
        label.setHorizontalAlignment(JLabel.CENTER);
        label.setForeground(foreground);
        label.addMouseListener(new MouseListener() {
            public void mousePressed(MouseEvent e) {}
            public void mouseClicked(MouseEvent e) {}
            public void mouseReleased(MouseEvent e) {
                label.setOpaque(false);
                label.setBackground(background);
                label.setForeground(foreground);
                calendar.set(Calendar.DAY_OF_MONTH, day);
                comboBox.setSelectedItem(dateFormat.format(calendar.getTime()));
                // hide();
                // hide is called with setSelectedItem() ... removeAll()
                comboBox.requestFocus();
            }
            public void mouseEntered(MouseEvent e) {
                label.setOpaque(true);
                label.setBackground(selectedBackground);
                label.setForeground(selectedForeground);
            }
            public void mouseExited(MouseEvent e) {
                label.setOpaque(false);
                label.setBackground(background);
                label.setForeground(foreground);
            }
            });

        days.add(label);
        }

        popup.add(BorderLayout.CENTER, days);
        popup.pack();       
    }
    }

    //////////////////////////////////////////////////////////////
    // This is only included to provide a sample GUI
    //////////////////////////////////////////////////////////////
    public static void main(String args[]) {
    JFrame f = new JFrame();
    Container c = f.getContentPane();
    c.setLayout(new FlowLayout());
    c.add(new JLabel("Date 1:"));
    c.add(new DateComboBox());
    c.add(new JLabel("Date 2:"));
    DateComboBox dcb = new DateComboBox();
    dcb.setEditable(true);
    c.add(dcb);
    f.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
        });
    f.setSize(500, 200);
    f.show();
    }

}