2009-03-17 43 views

Respuesta

62

Para un selector de hora se puede utilizar un JSpinner y establecer un JSpinner.DateEditor que sólo muestra el valor del tiempo

JSpinner timeSpinner = new JSpinner(new SpinnerDateModel()); 
JSpinner.DateEditor timeEditor = new JSpinner.DateEditor(timeSpinner, "HH:mm:ss"); 
timeSpinner.setEditor(timeEditor); 
timeSpinner.setValue(new Date()); // will only show the current time 
+1

wow tan simple y bueno! ¡Gracias, eres genial! – JavaNullPointer

+0

Es posible que también desee utilizar una biblioteca como JDatePicker: http://jdatepicker.org en conjunto para seleccionar la fecha. – juanheyns

+4

La biblioteca [LGoodDatePicker] (https://github.com/LGoodDatePicker/LGoodDatePicker) incluye un buen ** componente DateTimePicker **. (Además de las clases individuales DatePicker y TimePicker). Los tres componentes son simples y fáciles de usar. Aquí hay algunas capturas de pantalla de los componentes y la aplicación de demostración. [Captura de pantalla 1] (http://i.stack.imgur.com/ghDdI.png), [Captura de pantalla 2] (http://i.stack.imgur.com/QXgWE.png). La página principal del proyecto se encuentra en https://github.com/LGoodDatePicker/LGoodDatePicker. – BlakeTNC

1

Como dijo El selector de fecha es fácil, hay muchos por ahí.

En cuanto a un selector de tiempo, consulte cómo Google Calendar lo hace al crear una nueva entrada. Le permite escribir cualquier cosa mientras que al mismo tiempo tiene un menú desplegable en incrementos de 30 minutos. El menú desplegable cambia cuando cambia los minutos.

Si necesita para permitir al usuario elegir segundos, a continuación, lo mejor que puede hacer es un/combo desplegable tipificable

10

Utilice la ambos combinados .. eso es lo que hice:

public static JPanel buildDatePanel(String label, Date value) { 
JPanel datePanel = new JPanel(); 

JDateChooser dateChooser = new JDateChooser(); 
if (value != null) { 
    dateChooser.setDate(value); 
} 
for (Component comp : dateChooser.getComponents()) { 
    if (comp instanceof JTextField) { 
    ((JTextField) comp).setColumns(50); 
    ((JTextField) comp).setEditable(false); 
    } 
} 

datePanel.add(dateChooser); 

SpinnerModel model = new SpinnerDateModel(); 
JSpinner timeSpinner = new JSpinner(model); 
JComponent editor = new JSpinner.DateEditor(timeSpinner, "HH:mm:ss"); 
timeSpinner.setEditor(editor); 
if(value != null) { 
    timeSpinner.setValue(value); 
} 

datePanel.add(timeSpinner); 

return datePanel; 
} 
14

Se puede extender el componente JXDatePicker SwingX:

"JXDatePicker sólo maneja fechas sin tiempo Muy a menudo tenemos que permitir al usuario elegir una fecha y una hora Este es un ejemplo de cómo hacer uso.. JXDatePicker para manejar la fecha y la hora juntas ".

http://wiki.java.net/twiki/bin/view/Javadesktop/JXDateTimePicker

EDIT: En este artículo se desaparecieron de la web, pero como lo descubrió SingleShot, todavía está disponible en un archivo de Internet. Sólo para estar seguro, aquí está el ejemplo de trabajo completo:

import org.jdesktop.swingx.calendar.SingleDaySelectionModel; 
import org.jdesktop.swingx.JXDatePicker; 

import javax.swing.*; 
import javax.swing.text.DefaultFormatterFactory; 
import javax.swing.text.DateFormatter; 
import java.text.DateFormat; 
import java.text.ParseException; 
import java.util.*; 
import java.awt.*; 

/** 
* This is licensed under LGPL. License can be found here: http://www.gnu.org/licenses/lgpl-3.0.txt 
* 
* This is provided as is. If you have questions please direct them to charlie.hubbard at gmail dot you know what. 
*/ 
public class DateTimePicker extends JXDatePicker { 
    private JSpinner timeSpinner; 
    private JPanel timePanel; 
    private DateFormat timeFormat; 

    public DateTimePicker() { 
     super(); 
     getMonthView().setSelectionModel(new SingleDaySelectionModel()); 
    } 

    public DateTimePicker(Date d) { 
     this(); 
     setDate(d); 
    } 

    public void commitEdit() throws ParseException { 
     commitTime(); 
     super.commitEdit(); 
    } 

    public void cancelEdit() { 
     super.cancelEdit(); 
     setTimeSpinners(); 
    } 

    @Override 
    public JPanel getLinkPanel() { 
     super.getLinkPanel(); 
     if(timePanel == null) { 
      timePanel = createTimePanel(); 
     } 
     setTimeSpinners(); 
     return timePanel; 
    } 

    private JPanel createTimePanel() { 
     JPanel newPanel = new JPanel(); 
     newPanel.setLayout(new FlowLayout()); 
     //newPanel.add(panelOriginal); 

     SpinnerDateModel dateModel = new SpinnerDateModel(); 
     timeSpinner = new JSpinner(dateModel); 
     if(timeFormat == null) timeFormat = DateFormat.getTimeInstance(DateFormat.SHORT); 
     updateTextFieldFormat(); 
     newPanel.add(new JLabel("Time:")); 
     newPanel.add(timeSpinner); 
     newPanel.setBackground(Color.WHITE); 
     return newPanel; 
    } 

    private void updateTextFieldFormat() { 
     if(timeSpinner == null) return; 
     JFormattedTextField tf = ((JSpinner.DefaultEditor) timeSpinner.getEditor()).getTextField(); 
     DefaultFormatterFactory factory = (DefaultFormatterFactory) tf.getFormatterFactory(); 
     DateFormatter formatter = (DateFormatter) factory.getDefaultFormatter(); 
     // Change the date format to only show the hours 
     formatter.setFormat(timeFormat); 
    } 

    private void commitTime() { 
     Date date = getDate(); 
     if (date != null) { 
      Date time = (Date) timeSpinner.getValue(); 
      GregorianCalendar timeCalendar = new GregorianCalendar(); 
      timeCalendar.setTime(time); 

      GregorianCalendar calendar = new GregorianCalendar(); 
      calendar.setTime(date); 
      calendar.set(Calendar.HOUR_OF_DAY, timeCalendar.get(Calendar.HOUR_OF_DAY)); 
      calendar.set(Calendar.MINUTE, timeCalendar.get(Calendar.MINUTE)); 
      calendar.set(Calendar.SECOND, 0); 
      calendar.set(Calendar.MILLISECOND, 0); 

      Date newDate = calendar.getTime(); 
      setDate(newDate); 
     } 

    } 

    private void setTimeSpinners() { 
     Date date = getDate(); 
     if (date != null) { 
      timeSpinner.setValue(date); 
     } 
    } 

    public DateFormat getTimeFormat() { 
     return timeFormat; 
    } 

    public void setTimeFormat(DateFormat timeFormat) { 
     this.timeFormat = timeFormat; 
     updateTextFieldFormat(); 
    } 

    public static void main(String[] args) { 
     Date date = new Date(); 
     JFrame frame = new JFrame(); 
     frame.setTitle("Date Time Picker"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     DateTimePicker dateTimePicker = new DateTimePicker(); 
     dateTimePicker.setFormats(DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM)); 
     dateTimePicker.setTimeFormat(DateFormat.getTimeInstance(DateFormat.MEDIUM)); 

     dateTimePicker.setDate(date); 

     frame.getContentPane().add(dateTimePicker); 
     frame.pack(); 
     frame.setVisible(true); 
    } 
} 
+1

Este enlace ya no está, sin embargo, el [Wayback Machine] (http://archive.org/web/web.php) lo tiene [aquí] (http://web.archive.org/web/20111118105909/http: //wiki.java.net/twiki/bin/view/Javadesktop/JXDateTimePicker?TWIKISID=cc05dea1611ad043796cd67ed476d711;skin=print). – SingleShot

+0

Incluí ahora aquí el código completo de esta pequeña gema :) – lbalazscs

+1

¿Hay un editor de celda, para ponerlo en la celda de la tabla? – whatswrong

Cuestiones relacionadas