IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

 Java Discussion :

[Swing] Calendrier en Java


Sujet :

Java

  1. #41
    Membre confirmé
    Profil pro
    Inscrit en
    Mars 2005
    Messages
    429
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mars 2005
    Messages : 429
    Points : 475
    Points
    475
    Par défaut
    JDateChooser de JCalendar se ferme lors de la sélection du jour, il faut choisir mois et année avant. Tout calendrier popup fonctionne d'ailleurs sur ce principe.
    Pas nécessairement. Voir d'ailleurs le code quelques messages plus haut, qui utilise bien JCalendar. Il est un fait que la fenêtre ne se ferme pas après avoir cliqué sur un jour, permettant à l'utilisateur de "tester" plusieurs jours avant de fermer.

    Néanmoins, ce code peut sûrement être adapté pour obtenir l'effet voulu. Par un Listener ?

  2. #42
    Membre confirmé
    Profil pro
    Inscrit en
    Mars 2005
    Messages
    429
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mars 2005
    Messages : 429
    Points : 475
    Points
    475
    Par défaut
    Le code ci-dessous (basé sur le tien) me semble avoir l'effet voulu : la fenêtre se ferme dès qu'un jour est choisi.

    Pour cela PropertyChangeListener a été ajouté au JDateChooser du JCalendar.

    Nicolas

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
     
    import com.toedter.calendar.*;
    import java.awt.*;
    import java.awt.Dialog.*;
    import java.awt.event.*;
    import java.beans.*;
    import java.text.*;
    import java.util.*;
    import javax.swing.*;
     
    public class TestFrame {
     
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
     
                @Override
                public void run() {
                    JFrame frame = new JFrame("Test");
     
                    final JTextField jTextField18 = new JTextField("Waiting...");
                    jTextField18.setColumns(15);
     
                    JButton jButton10 = new JButton("Push!");
                    jButton10.addActionListener(new ActionListener() {
     
                        @Override
                        public void actionPerformed(ActionEvent e) {
     
                            final JDialog d = new JDialog(); // fenêtre
     
                            JCalendar c = new JCalendar();
     
                            JDayChooser dayChooser = c.getDayChooser();
                            dayChooser.addPropertyChangeListener(new PropertyChangeListener() {
     
                                @Override
                                public void propertyChange(PropertyChangeEvent evt) {
                                    if ("day".equals(evt.getPropertyName())) {
                                        d.dispose();
                                    }
                                }
                            });
     
                            jTextField18.setText("");
     
                            d.setTitle("Date choose");
                            d.setModalityType(ModalityType.APPLICATION_MODAL);
                            d.add(c);
                            d.pack();
                            d.setLocationRelativeTo(null); // UIMonitor.this
     
                            d.setVisible(true);
                            Date date = c.getCalendar().getTime(); // on récupère la date
     
                            //System.out.println(date.toString());
                            //   d.setVisible(false);
                            //	 d.dispose();
                            //   d.Hide();
    		/* on affiche la date dans le JTextfield */
                            Locale locale = Locale.getDefault();
                            DateFormat dateFormat = DateFormat.getDateInstance(
                                    DateFormat.SHORT, Locale.FRANCE);
                            jTextField18.setText(new SimpleDateFormat("dd/MM/yyyy", Locale.FRANCE).format(date));
     
     
                        }
                    });
     
                    frame.add(jTextField18, BorderLayout.WEST);
                    frame.add(jButton10, BorderLayout.EAST);
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                }
            });
        }
    }

  3. #43
    Membre du Club
    Profil pro
    Inscrit en
    Avril 2009
    Messages
    89
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2009
    Messages : 89
    Points : 45
    Points
    45
    Par défaut
    Bonjour

    Je suis desolé de rouvrir ce post mais dans mon cas cela ne marche pas...

    J'ai voulu utilisé
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
     
    import com.toedter.calendar.*;
    import java.awt.*;
    import java.awt.Dialog.*;
    import java.awt.event.*;
    import java.beans.*;
    import java.text.*;
    import java.util.*;
    import javax.swing.*;
     
    public class TestFrame {
     
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
     
                @Override
                public void run() {
                    JFrame frame = new JFrame("Test");
     
                    final JTextField jTextField18 = new JTextField("Waiting...");
                    jTextField18.setColumns(15);
     
                    JButton jButton10 = new JButton("Push!");
                    jButton10.addActionListener(new ActionListener() {
     
                        @Override
                        public void actionPerformed(ActionEvent e) {
     
                            final JDialog d = new JDialog(); // fenêtre
     
                            JCalendar c = new JCalendar();
     
                            JDayChooser dayChooser = c.getDayChooser();
                            dayChooser.addPropertyChangeListener(new PropertyChangeListener() {
     
                                @Override
                                public void propertyChange(PropertyChangeEvent evt) {
                                    if ("day".equals(evt.getPropertyName())) {
                                        d.dispose();
                                    }
                                }
                            });
     
                            jTextField18.setText("");
     
                            d.setTitle("Date choose");
                            d.setModalityType(ModalityType.APPLICATION_MODAL);
                            d.add(c);
                            d.pack();
                            d.setLocationRelativeTo(null); // UIMonitor.this
     
                            d.setVisible(true);
                            Date date = c.getCalendar().getTime(); // on récupère la date
     
                            //System.out.println(date.toString());
                            //   d.setVisible(false);
                            //	 d.dispose();
                            //   d.Hide();
    		/* on affiche la date dans le JTextfield */
                            Locale locale = Locale.getDefault();
                            DateFormat dateFormat = DateFormat.getDateInstance(
                                    DateFormat.SHORT, Locale.FRANCE);
                            jTextField18.setText(new SimpleDateFormat("dd/MM/yyyy", Locale.FRANCE).format(date));
     
     
                        }
                    });
     
                    frame.add(jTextField18, BorderLayout.WEST);
                    frame.add(jButton10, BorderLayout.EAST);
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                }
            });
        }
    }
    et ai pour JDateChooser avec PropertyChangeListener ajouté
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    532
    533
    534
    535
    536
    537
    538
    539
    540
    541
    542
    543
    544
    545
    546
    547
    548
    549
    550
    551
    552
    553
    554
    555
    556
    557
    558
    559
    560
    561
    562
    563
    564
    565
    566
    567
    568
    569
    570
    571
    572
    573
    574
    575
    576
    577
    /*
     *  JDateChooser.java  - A bean for choosing a date
     *  Copyright (C) 2004 Kai Toedter
     *  kai@toedter.com
     *  www.toedter.com
     *
     *  This program is free software; you can redistribute it and/or
     *  modify it under the terms of the GNU Lesser General Public License
     *  as published by the Free Software Foundation; either version 2
     *  of the License, or (at your option) any later version.
     *
     *  This program is distributed in the hope that it will be useful,
     *  but WITHOUT ANY WARRANTY; without even the implied warranty of
     *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     *  GNU Lesser General Public License for more details.
     *
     *  You should have received a copy of the GNU Lesser General Public License
     *  along with this program; if not, write to the Free Software
     *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
     */
    package com.toedter.calendar;
     
    import java.awt.BorderLayout;
    import java.awt.Font;
    import java.awt.Insets;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import java.net.URL;
    import java.util.Calendar;
    import java.util.Date;
    import java.util.Locale;
     
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JPopupMenu;
    import javax.swing.MenuElement;
    import javax.swing.MenuSelectionManager;
    import javax.swing.SwingUtilities;
    import javax.swing.event.ChangeEvent;
    import javax.swing.event.ChangeListener;
     
    /**
     * A date chooser containig a date editor and a button, that makes a JCalendar
     * visible for choosing a date. If no date editor is specified, a
     * JTextFieldDateEditor is used as default.
     * 
     * @author Kai Toedter
     * @version $LastChangedRevision: 101 $
     * @version $LastChangedDate: 2006-06-04 14:42:29 +0200 (So, 04 Jun 2006) $
     */
    public class JDateChooser extends JPanel implements ActionListener,
    		PropertyChangeListener {
     
    	private static final long serialVersionUID = -4306412745720670722L;
     
    	protected IDateEditor dateEditor;
     
    	protected JButton calendarButton;
     
    	protected JCalendar jcalendar;
     
    	protected JPopupMenu popup;
     
    	protected boolean isInitialized;
     
    	protected boolean dateSelected;
     
    	protected Date lastSelectedDate;
     
    	private ChangeListener changeListener;
     
    	/**
             * Creates a new JDateChooser. By default, no date is set and the textfield
             * is empty.
             */
    	public JDateChooser() {
    		this(null, null, null, null);
    	}
     
    	/**
             * Creates a new JDateChooser with given IDateEditor.
             * 
             * @param dateEditor
             *            the dateEditor to be used used to display the date. if null, a
             *            JTextFieldDateEditor is used.
             */
    	public JDateChooser(IDateEditor dateEditor) {
    		this(null, null, null, dateEditor);
    	}
     
    	/**
             * Creates a new JDateChooser.
             * 
             * @param date
             *            the date or null
             */
    	public JDateChooser(Date date) {
    		this(date, null);
    	}
     
    	/**
             * Creates a new JDateChooser.
             * 
             * @param date
             *            the date or null
             * @param dateFormatString
             *            the date format string or null (then MEDIUM SimpleDateFormat
             *            format is used)
             */
    	public JDateChooser(Date date, String dateFormatString) {
    		this(date, dateFormatString, null);
    	}
     
    	/**
             * Creates a new JDateChooser.
             * 
             * @param date
             *            the date or null
             * @param dateFormatString
             *            the date format string or null (then MEDIUM SimpleDateFormat
             *            format is used)
             * @param dateEditor
             *            the dateEditor to be used used to display the date. if null, a
             *            JTextFieldDateEditor is used.
             */
    	public JDateChooser(Date date, String dateFormatString,
    			IDateEditor dateEditor) {
    		this(null, date, dateFormatString, dateEditor);
    	}
     
    	/**
             * Creates a new JDateChooser. If the JDateChooser is created with this
             * constructor, the mask will be always visible in the date editor. Please
             * note that the date pattern and the mask will not be changed if the locale
             * of the JDateChooser is changed.
             * 
             * @param datePattern
             *            the date pattern, e.g. "MM/dd/yy"
             * @param maskPattern
             *            the mask pattern, e.g. "##/##/##"
             * @param placeholder
             *            the placeholer charachter, e.g. '_'
             */
    	public JDateChooser(String datePattern, String maskPattern, char placeholder) {
    		this(null, null, datePattern, new JTextFieldDateEditor(datePattern,
    				maskPattern, placeholder));
    	}
     
    	/**
             * Creates a new JDateChooser.
             * 
             * @param jcal
             *            the JCalendar to be used
             * @param date
             *            the date or null
             * @param dateFormatString
             *            the date format string or null (then MEDIUM Date format is
             *            used)
             * @param dateEditor
             *            the dateEditor to be used used to display the date. if null, a
             *            JTextFieldDateEditor is used.
             */
    	public JDateChooser(JCalendar jcal, Date date, String dateFormatString,
    			IDateEditor dateEditor) {
    		setName("JDateChooser");
     
    		this.dateEditor = dateEditor;
    		if (this.dateEditor == null) {
    			this.dateEditor = new JTextFieldDateEditor();
    		}
    		this.dateEditor.addPropertyChangeListener("date", this);
     
    		if (jcal == null) {
    			jcalendar = new JCalendar(date);
    		} else {
    			jcalendar = jcal;
    			if (date != null) {
    				jcalendar.setDate(date);
    			}
    		}
     
    		setLayout(new BorderLayout());
     
    		jcalendar.getDayChooser().addPropertyChangeListener("day", this);
    		// always fire"day" property even if the user selects
    		// the already selected day again
    		jcalendar.getDayChooser().setAlwaysFireDayProperty(true);
     
    		setDateFormatString(dateFormatString);
    		setDate(date);
     
    		// Display a calendar button with an icon
    		URL iconURL = getClass().getResource(
    				"/com/toedter/calendar/images/JDateChooserIcon.gif");
    		ImageIcon icon = new ImageIcon(iconURL);
     
    		calendarButton = new JButton(icon) {
    			private static final long serialVersionUID = -1913767779079949668L;
     
    			public boolean isFocusable() {
    				return false;
    			}
    		};
    		calendarButton.setMargin(new Insets(0, 0, 0, 0));
    		calendarButton.addActionListener(this);
     
    		// Alt + 'C' selects the calendar.
    		calendarButton.setMnemonic(KeyEvent.VK_C);
     
    		add(calendarButton, BorderLayout.EAST);
    		add(this.dateEditor.getUiComponent(), BorderLayout.CENTER);
     
    		calendarButton.setMargin(new Insets(0, 0, 0, 0));
    		// calendarButton.addFocusListener(this);
     
    		popup = new JPopupMenu() {
    			private static final long serialVersionUID = -6078272560337577761L;
     
    			public void setVisible(boolean b) {
    				Boolean isCanceled = (Boolean) getClientProperty("JPopupMenu.firePopupMenuCanceled");
    				if (b
    						|| (!b && dateSelected)
    						|| ((isCanceled != null) && !b && isCanceled
    								.booleanValue())) {
    					super.setVisible(b);
    				}
    			}
    		};
     
    		popup.setLightWeightPopupEnabled(true);
     
    		popup.add(jcalendar);
     
    		lastSelectedDate = date;
     
    		// Corrects a problem that occured when the JMonthChooser's combobox is
    		// displayed, and a click outside the popup does not close it.
     
    		// The following idea was originally provided by forum user
    		// podiatanapraia:
    		changeListener = new ChangeListener() {
    			boolean hasListened = false;
     
    			public void stateChanged(ChangeEvent e) {
    				if (hasListened) {
    					hasListened = false;
    					return;
    				}
    				if (popup.isVisible()
    						&& JDateChooser.this.jcalendar.monthChooser
    								.getComboBox().hasFocus()) {
    					MenuElement[] me = MenuSelectionManager.defaultManager()
    							.getSelectedPath();
    					MenuElement[] newMe = new MenuElement[me.length + 1];
    					newMe[0] = popup;
    					for (int i = 0; i < me.length; i++) {
    						newMe[i + 1] = me[i];
    					}
    					hasListened = true;
    					MenuSelectionManager.defaultManager()
    							.setSelectedPath(newMe);
    				}
    			}
    		};
    		MenuSelectionManager.defaultManager().addChangeListener(changeListener);
    		// end of code provided by forum user podiatanapraia
     
    		isInitialized = true;
    	}
     
    	/**
             * Called when the jalendar button was pressed.
             * 
             * @param e
             *            the action event
             */
    	public void actionPerformed(ActionEvent e) {
    		int x = calendarButton.getWidth()
    				- (int) popup.getPreferredSize().getWidth();
    		int y = calendarButton.getY() + calendarButton.getHeight();
     
    		Calendar calendar = Calendar.getInstance();
    		Date date = dateEditor.getDate();
    		if (date != null) {
    			calendar.setTime(date);
    		}
    		jcalendar.setCalendar(calendar);
    		popup.show(calendarButton, x, y);
    		dateSelected = false;
    	}
     
    	/**
             * Listens for a "date" property change or a "day" property change event
             * from the JCalendar. Updates the date editor and closes the popup.
             * 
             * @param evt
             *            the event
             */
    	public void propertyChange(PropertyChangeEvent evt) {
    		if (evt.getPropertyName().equals("day")) {
    			if (popup.isVisible()) {
    				dateSelected = true;
    				popup.setVisible(false);
    				setDate(jcalendar.getCalendar().getTime());
    			}
    		} else if (evt.getPropertyName().equals("date")) {
    			if (evt.getSource() == dateEditor) {
    				firePropertyChange("date", evt.getOldValue(), evt.getNewValue());
    			} else {
    				setDate((Date) evt.getNewValue());
    			}
    		}
    	}
     
    	/**
             * Updates the UI of itself and the popup.
             */
    	public void updateUI() {
    		super.updateUI();
    		setEnabled(isEnabled());
     
    		if (jcalendar != null) {
    			SwingUtilities.updateComponentTreeUI(popup);
    		}
    	}
     
    	/**
             * Sets the locale.
             * 
             * @param l
             *            The new locale value
             */
    	public void setLocale(Locale l) {
    		super.setLocale(l);
    		dateEditor.setLocale(l);
    		jcalendar.setLocale(l);
    	}
     
    	/**
             * Gets the date format string.
             * 
             * @return Returns the dateFormatString.
             */
    	public String getDateFormatString() {
    		return dateEditor.getDateFormatString();
    	}
     
    	/**
             * Sets the date format string. E.g "MMMMM d, yyyy" will result in "July 21,
             * 2004" if this is the selected date and locale is English.
             * 
             * @param dfString
             *            The dateFormatString to set.
             */
    	public void setDateFormatString(String dfString) {
    		dateEditor.setDateFormatString(dfString);
    		invalidate();
    	}
     
    	/**
             * Returns the date. If the JDateChooser is started with a null date and no
             * date was set by the user, null is returned.
             * 
             * @return the current date
             */
    	public Date getDate() {
    		return dateEditor.getDate();
    	}
     
    	/**
             * Sets the date. Fires the property change "date" if date != null.
             * 
             * @param date
             *            the new date.
             */
    	public void setDate(Date date) {
    		dateEditor.setDate(date);
    		if (getParent() != null) {
    			getParent().invalidate();
    		}
    	}
     
    	/**
             * Returns the calendar. If the JDateChooser is started with a null date (or
             * null calendar) and no date was set by the user, null is returned.
             * 
             * @return the current calendar
             */
    	public Calendar getCalendar() {
    		Date date = getDate();
    		if (date == null) {
    			return null;
    		}
    		Calendar calendar = Calendar.getInstance();
    		calendar.setTime(date);
    		return calendar;
    	}
     
    	/**
             * Sets the calendar. Value null will set the null date on the date editor.
             * 
             * @param calendar
             *            the calendar.
             */
    	public void setCalendar(Calendar calendar) {
    		if (calendar == null) {
    			dateEditor.setDate(null);
    		} else {
    			dateEditor.setDate(calendar.getTime());
    		}
    	}
     
    	/**
             * Enable or disable the JDateChooser.
             * 
             * @param enabled
             *            the new enabled value
             */
    	public void setEnabled(boolean enabled) {
    		super.setEnabled(enabled);
    		if (dateEditor != null) {
    			dateEditor.setEnabled(enabled);
    			calendarButton.setEnabled(enabled);
    		}
    	}
     
    	/**
             * Returns true, if enabled.
             * 
             * @return true, if enabled.
             */
    	public boolean isEnabled() {
    		return super.isEnabled();
    	}
     
    	/**
             * Sets the icon of the buuton.
             * 
             * @param icon
             *            The new icon
             */
    	public void setIcon(ImageIcon icon) {
    		calendarButton.setIcon(icon);
    	}
     
    	/**
             * Sets the font of all subcomponents.
             * 
             * @param font
             *            the new font
             */
    	public void setFont(Font font) {
    		if (isInitialized) {
    			dateEditor.getUiComponent().setFont(font);
    			jcalendar.setFont(font);
    		}
    		super.setFont(font);
    	}
     
    	/**
             * Returns the JCalendar component. THis is usefull if you want to set some
             * properties.
             * 
             * @return the JCalendar
             */
    	public JCalendar getJCalendar() {
    		return jcalendar;
    	}
     
    	/**
             * Returns the calendar button.
             * 
             * @return the calendar button
             */
    	public JButton getCalendarButton() {
    		return calendarButton;
    	}
     
    	/**
             * Returns the date editor.
             * 
             * @return the date editor
             */
    	public IDateEditor getDateEditor() {
    		return dateEditor;
    	}
     
    	/**
             * Sets a valid date range for selectable dates. If max is before min, the
             * default range with no limitation is set.
             * 
             * @param min
             *            the minimum selectable date or null (then the minimum date is
             *            set to 01\01\0001)
             * @param max
             *            the maximum selectable date or null (then the maximum date is
             *            set to 01\01\9999)
             */
    	public void setSelectableDateRange(Date min, Date max) {
    		jcalendar.setSelectableDateRange(min, max);
    		dateEditor.setSelectableDateRange(jcalendar.getMinSelectableDate(),
    				jcalendar.getMaxSelectableDate());
    	}
     
    	public void setMaxSelectableDate(Date max) {
    		jcalendar.setMaxSelectableDate(max);
    		dateEditor.setMaxSelectableDate(max);
    	}
     
    	public void setMinSelectableDate(Date min) {
    		jcalendar.setMinSelectableDate(min);
    		dateEditor.setMinSelectableDate(min);
    	}
     
    	/**
             * Gets the maximum selectable date.
             * 
             * @return the maximum selectable date
             */
    	public Date getMaxSelectableDate() {
    		return jcalendar.getMaxSelectableDate();
    	}
     
    	/**
             * Gets the minimum selectable date.
             * 
             * @return the minimum selectable date
             */
    	public Date getMinSelectableDate() {
    		return jcalendar.getMinSelectableDate();
    	}
     
    	/**
             * Should only be invoked if the JDateChooser is not used anymore. Due to popup
             * handling it had to register a change listener to the default menu
             * selection manager which will be unregistered here. Use this method to
             * cleanup possible memory leaks.
             */
    	public void cleanup() {
    		MenuSelectionManager.defaultManager().removeChangeListener(changeListener);
    		changeListener = null;
    	}
     
    	/**
             * Creates a JFrame with a JDateChooser inside and can be used for testing.
             * 
             * @param s
             *            The command line arguments
             */
    	public static void main(String[] s) {
    		JFrame frame = new JFrame("JDateChooser");
    		JDateChooser dateChooser = new JDateChooser();
    		// JDateChooser dateChooser = new JDateChooser(null, new Date(), null,
    		// null);
    		// dateChooser.setLocale(new Locale("de"));
    		// dateChooser.setDateFormatString("dd. MMMM yyyy");
     
    		// dateChooser.setPreferredSize(new Dimension(130, 20));
    		// dateChooser.setFont(new Font("Verdana", Font.PLAIN, 10));
    		// dateChooser.setDateFormatString("yyyy-MM-dd HH:mm");
     
    		// URL iconURL = dateChooser.getClass().getResource(
    		// "/com/toedter/calendar/images/JMonthChooserColor32.gif");
    		// ImageIcon icon = new ImageIcon(iconURL);
    		// dateChooser.setIcon(icon);
     
    		frame.getContentPane().add(dateChooser);
    		frame.pack();
    		frame.setVisible(true);
    	}
     
    }
    Mais pour autant losrsque je selectionne une date elle ne s'affiche pas dans le jtext... C'est a la place celle du jour d'aujourd'hui.

    Merci de m'eclairer pour me donner la bonne date

  4. #44
    Membre du Club
    Profil pro
    Inscrit en
    Avril 2009
    Messages
    89
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2009
    Messages : 89
    Points : 45
    Points
    45
    Par défaut
    Bonjour,

    Je revien apres quelque temps.

    Mon calendrier fonctionne tres bien, mais j'ai les meme prérogative que la personne qui ouvert ce poste. Soit la fermeture du calendrier apres selection du jour, avec en plus le non affichage de la date en cour lors de l'ouvertur de la fenetre calendar.

    Le prob avec le code precedant c'est que celui ci ne prend pas en compte la date d'aujourd'hui, on peut cliquer dessus comme un fou il ne se passera rien, et ne prendra pas non plus la date.

    Je me suis tres largement inspiré du code mais ca ne marche pas.

    j'ai tenté un mousseListener sur le dayChooser en effectuant l'action sur le mousseClick mais il n'est pas effectué

    Auriez vous une petite idée

    Code actuel

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    final JDialog calendar = new JDialog(); // fenêtre
     
            final JCalendar dateChooser = new JCalendar();
            dateChooser.setLocale(Locale.ENGLISH);
     
            JDayChooser dayChooser = dateChooser.getDayChooser();
            dayChooser.addPropertyChangeListener(new PropertyChangeListener() {
     
                public void propertyChange(PropertyChangeEvent evt) {
     
                    int year = dateChooser.getYearChooser().getYear();
                    int month = dateChooser.getMonthChooser().getMonth() + 1;
                    int day = dateChooser.getDayChooser().getDay();
                    String sDate = new Integer(year).toString() + "/" + new Integer(month).toString() + "/" + new Integer(day).toString();
                    Date newDate = new Date(sDate);
     
                    if ("day".equals(evt.getPropertyName())) {
                        requExeDate.setText(new SimpleDateFormat("yyMMdd", Locale.ENGLISH).format(newDate));
                        calendar.setVisible(false);
                    }else if (requExeDate.getText().equals("")){
                        requExeDate.setText(new SimpleDateFormat("yyMMdd", Locale.ENGLISH).format(newDate));
                        calendar.setVisible(false);
                    }
                }
            });
     
     
     
            calendar.setTitle("Calendar");
            //d.setModalityType(true);
            calendar.add(dateChooser);
            calendar.pack();
            calendar.setLocationRelativeTo(null); // UIMonitor.this
            calendar.setModal(true);
            calendar.setVisible(true);
     
            if (!calendar.isVisible())
                calendar.dispose();
    et avec le mousseListener
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    final JDialog calendar = new JDialog(); // fenêtre
     
            final JCalendar dateChooser = new JCalendar();
            dateChooser.setLocale(Locale.ENGLISH);
     
            JDayChooser dayChooser = dateChooser.getDayChooser();
     
            dayChooser.addMouseListener(new MouseAdapter() {
     
                @Override
                public void mouseClicked(MouseEvent e) {
                    int year = dateChooser.getYearChooser().getYear();
                    int month = dateChooser.getMonthChooser().getMonth() + 1;
                    int day = dateChooser.getDayChooser().getDay();
                    String sDate = new Integer(year).toString() + "/" + new Integer(month).toString() + "/" + new Integer(day).toString();
                    Date newDate = new Date(sDate);
                    requExeDate.setText(new SimpleDateFormat("yyMMdd", Locale.ENGLISH).format(newDate));
                    calendar.setVisible(false);
                }
     
            });
    calendar.setTitle("Calendar");
            //d.setModalityType(true);
            calendar.add(dateChooser);
            calendar.pack();
            calendar.setLocationRelativeTo(null); // UIMonitor.this
            calendar.setModal(true);
            calendar.setVisible(true);
     
            if (!calendar.isVisible())
                calendar.dispose();
    MERCI

  5. #45
    Membre éprouvé
    Avatar de michel.di
    Homme Profil pro
    Freelance
    Inscrit en
    Juin 2009
    Messages
    782
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 37
    Localisation : France, Nord (Nord Pas de Calais)

    Informations professionnelles :
    Activité : Freelance
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juin 2009
    Messages : 782
    Points : 1 042
    Points
    1 042
    Par défaut
    JCalendar ne permet que de sélectionner des jours, mois... non?
    Vous connaissez des lib pour éditer les jours?
    en fait je voulais développer un agenda il y a quelques temps et je voulais pouvoir mettre des petits sticks sur des jours avec événements. Je ne sais pas si c'est possible, j'avais essayé JCalendar mais je n'avais rien trouvé pour éditer
    Docteur en informatique
    Freelance R&D, Web
    Activité freelance : https://redinnov.fr
    Page perso : https://michel-dirix.com/

  6. #46
    Membre du Club
    Profil pro
    Inscrit en
    Avril 2009
    Messages
    89
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2009
    Messages : 89
    Points : 45
    Points
    45
    Par défaut
    Salut,

    Je tourne en rond la, et ne voit pas le bout du tunel. personne ne saurai comment resoudre ce petit probleme?

    Je rappel :

    Choisir une date avec une fermeture automatique du calendrier. la fonction proposé ici ne permet pas de choisir la date d'aujourd'hui ce qui est genant

    Comme montrer precedement j'ai tenté un mousseListener sur le DateChooser mais il ne se passe rien.

    A defaut pourrait on au moins ou il réinitialise la date lorsque l'on choisi un jour. j'ai effectué un debugg mais ca ne ma mené null part pour l'instant.

    Merci

  7. #47
    Membre régulier

    Inscrit en
    Septembre 2005
    Messages
    99
    Détails du profil
    Informations personnelles :
    Âge : 41

    Informations forums :
    Inscription : Septembre 2005
    Messages : 99
    Points : 118
    Points
    118
    Par défaut swingx
    Bonjour,

    Pourquoi ne pas utilisé le magnifique projet Swingx.

    il y a un composant JXdatePicker qui repond à tous tes critères.

    Example

    Cdt, Jérôme

  8. #48
    Membre du Club
    Profil pro
    Inscrit en
    Avril 2009
    Messages
    89
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2009
    Messages : 89
    Points : 45
    Points
    45
    Par défaut
    oui mais la c'est reporter le probleme car il faut que maintenant je comprenne ce module.

    Ca me serait tres util si tu pouvai transmettre directement la methode pour recupere la date parce que la je n ai plus trop le temps

    J'ai reussi a le lance mais le probleme c'est aue ca ouvre un Jcomponent. Ce que je recherche c'est que l'orsque je clique sur un chanmp (JtextFormat) il m'ouvre un calendrier de choix.

    J'utilise netbean donc ca bloque un peu.

    Merci

  9. #49
    Membre régulier

    Inscrit en
    Septembre 2005
    Messages
    99
    Détails du profil
    Informations personnelles :
    Âge : 41

    Informations forums :
    Inscription : Septembre 2005
    Messages : 99
    Points : 118
    Points
    118
    Par défaut
    Citation Envoyé par totonin Voir le message
    oui mais la c'est reporter le probleme car il faut que maintenant je comprenne ce module.

    Ca me serait tres util si tu pouvai transmettre directement la methode pour recupere la date parce que la je n ai plus trop le temps

    J'ai reussi a le lance mais le probleme c'est aue ca ouvre un Jcomponent. Ce que je recherche c'est que l'orsque je clique sur un chanmp (JtextFormat) il m'ouvre un calendrier de choix.

    J'utilise netbean donc ca bloque un peu.

    Merci
    pour utiliser swingx c'est pas compliqué tu download les jar.
    tu ajoute le composant Jxdatepicker soit avec netbean soit à l'ancienne ...

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
     
     private JXDatePicker datePickerEnd;
    datePickerEnd = new JXDatePicker(new Date());
    datePickerStart.getMonthView().setZoomable(true);
    // selection de la langue
    datePickerStart.setLocale(Locale.FRENCH);
     
    // return the date selected
    datePickerEnd.getDate()
    Pour information tu peux ajouter swingx a Netbean.
    tutorial

  10. #50
    Membre du Club
    Profil pro
    Inscrit en
    Avril 2009
    Messages
    89
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2009
    Messages : 89
    Points : 45
    Points
    45
    Par défaut
    j'ai utilisé un l'exemple sité plus haut

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    final JDialog calendar = new JDialog(); // fenêtre
     
     
            final JXDatePicker datePicker = new JXDatePicker();
            datePicker.setLocale(Locale.ENGLISH);
            datePicker.addActionListener(new ActionListener() {
     
                public void actionPerformed(ActionEvent e) {
                    requExeDate.setText(new SimpleDateFormat("yyMMdd", Locale.ENGLISH).format(datePicker.getDate()));
                }
            });
     
            //calendar.getContentPane().add(label, BorderLayout.NORTH);
            calendar.getContentPane().add(datePicker, BorderLayout.CENTER);
            calendar.setTitle("Calendar");
            calendar.setLocationRelativeTo(null); // UIMonitor.this
            calendar.setModal(true);
            calendar.pack();
            calendar.setVisible(true);
    Losrque tu clique sur requExeDate, qui est de type JTextField dans mon cas, un nouvelle frame s'ouvre calendar, et la j'ai un petit onglet qui me permet de selectionner la date.

    Mais comment mettre cette onglet directement dans mon interface. la il y a une frame intermediare qui ne me sert a rien.

    peux tu me donner plus d'indication s'il te plait. car JXDatePicker comme tu le disai correspond exactement a ce que je cherché.

    Merci

  11. #51
    Membre régulier

    Inscrit en
    Septembre 2005
    Messages
    99
    Détails du profil
    Informations personnelles :
    Âge : 41

    Informations forums :
    Inscription : Septembre 2005
    Messages : 99
    Points : 118
    Points
    118
    Par défaut
    Je ne comprends pas bien ta problamétique pourrais tu m'expliquer le fonctionnement que tu souhaite avoir en terme d'interface ?

  12. #52
    Membre du Club
    Profil pro
    Inscrit en
    Avril 2009
    Messages
    89
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2009
    Messages : 89
    Points : 45
    Points
    45
    Par défaut
    l'objectif est d'avoir un champ dans le quel je saisirai la date atravers un calendrier.

    JXDatePicker me le permet mais j'arrive pas a le mettre dans l'interface que j'ai deja faite.

    A l'origine j'avai un JTextField dans le quelle je saisissé la date. lorsque l'on cliqué sur le champ cela ouvrait un Jcalendar (qui ne correspond pas a ce que je cherche).

    Ce qu'il faudrait c'est remplacer le JTextField par JXDatePicker, mais je n'y arrive pas....

    en gros je ne sais pas implementé JXDatePicker ou que ce soit en dehors d'une frame (et cela grace a un exemple)

  13. #53
    Membre régulier

    Inscrit en
    Septembre 2005
    Messages
    99
    Détails du profil
    Informations personnelles :
    Âge : 41

    Informations forums :
    Inscription : Septembre 2005
    Messages : 99
    Points : 118
    Points
    118
    Par défaut
    tu as la réponse dans ta phrase.remplace ton jtextfield par le datepicker.

  14. #54
    Membre du Club
    Profil pro
    Inscrit en
    Avril 2009
    Messages
    89
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2009
    Messages : 89
    Points : 45
    Points
    45
    Par défaut
    C'est bon c'est regler.

    Le probleme etait que j'utilisé netbean pour me facilité la vie => echec.

    Il fallait juste rajouté la class dans la palette. chose qui ne m etait pas venu a l'esprit.

    Petite question pour cloturer. j'ai mit le calendrier en anglais mais la phrase du bas "aujourd'hui nous somme le" est en francais ou puis je changer cela???

    Merci infiniment

  15. #55
    Membre régulier

    Inscrit en
    Septembre 2005
    Messages
    99
    Détails du profil
    Informations personnelles :
    Âge : 41

    Informations forums :
    Inscription : Septembre 2005
    Messages : 99
    Points : 118
    Points
    118

  16. #56
    Membre du Club
    Profil pro
    Inscrit en
    Avril 2009
    Messages
    89
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2009
    Messages : 89
    Points : 45
    Points
    45
    Par défaut
    Je vai voir mais je pense que ca ne modifie que la langue du calendrier (days, month, year)

    par contre en fesant cela
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    requExeDate.setLinkDay(new Date(),"Today");
    je met un vide a la place d'aujourd'hui et peu remplacer le message.

    Saurai tu comment rendre non saisissable le champ text... que le seul moyen de le remplir c'est de selectionner su le calendrier?

    Merci

  17. #57
    Membre régulier

    Inscrit en
    Septembre 2005
    Messages
    99
    Détails du profil
    Informations personnelles :
    Âge : 41

    Informations forums :
    Inscription : Septembre 2005
    Messages : 99
    Points : 118
    Points
    118
    Par défaut
    non (regarde la ajvadoc de Jxdatepicker)

    Je pense que ton problème est résolu et qu'il faut ouvrir un autre poste sinon les autres utilisateurs seront un peu perdu lors de la consultation de ce post sur ton problème initial.

  18. #58
    Expert éminent sénior
    Avatar de sinok
    Profil pro
    Inscrit en
    Août 2004
    Messages
    8 765
    Détails du profil
    Informations personnelles :
    Âge : 43
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Août 2004
    Messages : 8 765
    Points : 12 977
    Points
    12 977
    Par défaut
    Il te faut aussi spécifier la Locale par défaut pour java dès le démarrage du programme. En effet cette mention se trouve dans un RessourceBundle fournit par SwingX en différents langages. Ce bundle est chargé en fonction de la locale par défaut.

    Pour la changer: Soit switcher l'OS en Anglais, soit faire un Locale.setDefaultLocale (Locale.EN) dans le main du programme, avant d'intancier ton interface.
    Hey, this is mine. That's mine. All this is mine. I'm claiming all this as mine. Except that bit. I don't want that bit. But all the rest of this is mine. Hey, this has been a really good day. I've eaten five times, I've slept six times, and I've made a lot of things mine. Tomorrow, I'm gonna see if I can't have sex with something.

  19. #59
    Membre du Club
    Profil pro
    Inscrit en
    Avril 2009
    Messages
    89
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2009
    Messages : 89
    Points : 45
    Points
    45
    Par défaut
    Merci pour votre aide

    Si non c'etait

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    JXDatePicker textF = nex JXDatePicker();
    textF.getEditor().setEditable(false);

    fallait juste chercher 2 mn de plus

Discussions similaires

  1. [Jcalendar] construire un agenda /calendrier avec java.
    Par Battant dans le forum Composants
    Réponses: 3
    Dernier message: 08/06/2010, 11h57
  2. Calendrier graphique java
    Par projet16 dans le forum AWT/Swing
    Réponses: 1
    Dernier message: 22/11/2007, 11h27
  3. calendrier en java
    Par le_tigre_est_en_toi dans le forum Collection et Stream
    Réponses: 1
    Dernier message: 29/12/2006, 19h38
  4. Calendrier en Java
    Par r-o-m-z dans le forum Collection et Stream
    Réponses: 5
    Dernier message: 21/10/2006, 15h51

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo