2013-04-19 6 views
5

저는 SwingX JXDatePicker를 사용하고 있으며 다음/이전 연도 버튼을 제공하는 방법을 알 수 없습니다. 기본적으로 다음/이전 달 버튼 만 제공합니다.Java Swing JXDatePicker

또한 SwingX가 더 이상 유지되지 않는 것 같습니다. 날짜 선택기로 최신 구성 요소를 사용해야합니까?

도움/의견을 보내 주시면 대단히 감사하겠습니다. 감사합니다, 토마스

는 UPDATE :

질문을 명확히하기 위해, 나는 JXDatePicker 스크린 샷을 추가하고 빨간색 이전/다음 달 버튼에 강조했다. 질문은 다음과 같습니다 : 달력을 다음/이전 연도로 가져 오는 단추를 추가하는 방법은 무엇입니까? 새로운 단추는 특정 Look & 느낌 관리자 (이 경우 Insusbtantial)에서 렌더링해야하므로 표준 구성 요소 여야합니다.

많은 감사

enter image description here

+0

체크 아웃까지의 목록은 [이] (http://stackoverflow.com/questions/1339354/what-are-good-java-date-chooser-swing-gui-widgets) 질문 최신 대안. 나는 그 중 일부를 시도하는 것이 좋습니다거야. – Kezz101

+0

it is maintain - 현재 버전 1.6.5-1,하지만 당신이 뭘하는지 이해하지 못한다. 정확히 무엇을 원하니? 그리고 왜 왜 swingx 데모 (프로젝트 페이지의 웹 스타트 가능 링크)에 설명 된대로 사용자 정의가 도움이되지 않습니까? – kleopatra

+0

@MrD 관련없는 링크를 확산시키는 이유는 무엇입니까? 그 하나는 완전히 관련이없는 문제에 관한 것입니다 ... – kleopatra

답변

2

내가 Microba DatePicker에서 사용을 권장합니다. 그것은 고도로 사용자 정의 할 수 있으며 정확하게 당신이 원하는 것을 수행합니다.

http://microba.sourceforge.net/

enter image description here enter image description here

편집 :

내가보고 좋아. 글쎄, 나는 약간의 조사를했고 당신이 찾고있는 함수가 실제로 JXDatePicker에 존재하지 않는 것 같다.

발견 된 다른 대안은 다음과 같습니다. JDatePicker at http://sourceforge.net/projects/jdatepicker/.

홈페이지 웹 사이트 : https://jdatepicker.org/

이 계속 지원하고 원하는 기능을 갖고있는 것 같아요된다.

+0

불행히도이 구성 요소는 더 이상 유지 관리되지 않습니다 (지난 5 년 동안 출시되지 않음). Java/Swing의 이후 버전이 중단 될 수 있고 수정되지 않았기 때문에 위험합니다. – Tom

+0

@Omid can 어떻게 스윙 컴포넌트에 이것을 추가하고 jframe에서 드래그하는지 말해 주시고 JPallete Manager를 사용하여 추가했지만이 컴포넌트는 jframe으로 드래그하지 않습니다. –

+0

Net Beans 7.1을 노래하며 NeBeans 7.1 및 Swing 프레임 작업과 호환됩니다. –

1

이것은 몇 년 전에 내가 조립 한 것입니다. 필요에 맞게 수정할 수 있습니다. calendar icon :

enter image description here

당신은 주요 테스트를 실행하려면이 이미지가 필요합니다. datepicker.gif라는 이름으로 소스와 동일한 디렉토리에 넣기 만하면됩니다.

import java.awt.Color; 
import java.awt.Container; 
import java.awt.Dimension; 
import java.awt.FlowLayout; 
import java.awt.Font; 
import java.awt.GridBagConstraints; 
import java.awt.GridBagLayout; 
import java.awt.Insets; 
import java.awt.Point; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.net.URL; 
import java.text.SimpleDateFormat; 
import java.util.ArrayList; 
import java.util.Calendar; 
import java.util.Date; 
import java.util.List; 

import javax.swing.BorderFactory; 
import javax.swing.BoxLayout; 
import javax.swing.ImageIcon; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 
import javax.swing.JTextField; 
import javax.swing.Popup; 
import javax.swing.PopupFactory; 

public class DatePicker extends JPanel { 

    private static final long serialVersionUID = 1L; 

    protected boolean controlsOnTop; 
    protected boolean removeOnDaySelection; 

    protected Calendar currentDisplayDate; 

    protected JButton prevMonth; 
    protected JButton nextMonth; 
    protected JButton prevYear; 
    protected JButton nextYear; 

    protected JTextField textField; 

    protected List<ActionListener> popupListeners = 
     new ArrayList<ActionListener>(); 

    protected Popup popup; 

    protected SimpleDateFormat dayName = new SimpleDateFormat("d"); 
    protected SimpleDateFormat monthName = new SimpleDateFormat("MMMM"); 

    protected String iconFile = "datepicker.gif"; 
    protected String[] weekdayNames = 
     {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; 

    public DatePicker() { 
     super(); 
     currentDisplayDate = Calendar.getInstance(); 
     controlsOnTop  = true; 
     removeOnDaySelection = true; 
     createPanel(); 
    } 

    public DatePicker(Calendar date) { 
     super(); 
     setDate(date); 
     controlsOnTop  = true; 
     removeOnDaySelection = true; 
     createPanel(); 
    } 

    public DatePicker(int month, int day, int year) { 
     super(); 
     setDate(month, day, year); 
     controlsOnTop  = true; 
     removeOnDaySelection = true; 
     createPanel(); 
    } 

    public void setDate(String date) { 
     currentDisplayDate = Calendar.getInstance(); 
     editDate(date); 
    } 

    public void setDate(Calendar date) { 
     currentDisplayDate = date; 
     createPanel(); 
     validate(); 
     repaint(); 
    } 

    public void setDate(int month, int day, int year) { 
     currentDisplayDate = Calendar.getInstance(); 
     currentDisplayDate.set(expandYear(year), month - 1, day); 
     createPanel(); 
     validate(); 
     repaint(); 
    } 

    protected int expandYear(int year) { 
     if (year < 100) {     // 2 digit year 
      int currentYear = Calendar.getInstance().get(Calendar.YEAR); 
      int current2DigitYear = currentYear % 100; 
      int currentCentury = currentYear/100 * 100; 
      // set 2 digit year range +20/-80 from current year 
      int high2DigitYear = (current2DigitYear + 20) % 100; 
      if (year <= high2DigitYear) { 
       year += currentCentury; 
      } 
      else { 
       year += (currentCentury - 100); 
      } 
     } 
     return year; 
    } 

    public void setControlsOnTop(boolean flag) { 
     controlsOnTop = flag; 
     createPanel(); 
     validate(); 
     repaint(); 
    } 

    public void setRemoveOnDaySelection(boolean flag) { 
     removeOnDaySelection = flag; 
    } 

    public Popup getPopup(Container c) { 
     if (popup == null) { 
      Point p = c.getLocation(); 
      PopupFactory factory = PopupFactory.getSharedInstance(); 
      popup = factory.getPopup(c, this, p.x, p.y); 
     } 
     return popup; 
    } 

    public void popupShow(Container c) { 
     getPopup(c); 
     popup.show(); 
    } 

    public void popupHide() { 
     popup.hide(); 
    } 

    public Calendar getCalendarDate() { 
     return currentDisplayDate; 
    } 

    public Date getDate() { 
     return currentDisplayDate.getTime(); 
    } 

    public String getFormattedDate() { 
     return Integer.toString(getMonth()) + "/" + 
      Integer.toString(getDay()) + "/" + 
      Integer.toString(getYear()); 
    } 

    public int getMonth() { 
     return currentDisplayDate.get(Calendar.MONTH) + 1; 
    } 

    public int getDay() { 
     return currentDisplayDate.get(Calendar.DAY_OF_MONTH); 
    } 

    public int getYear() { 
     return currentDisplayDate.get(Calendar.YEAR); 
    } 

    public ImageIcon getImage() { 
     return createImageIcon(iconFile, "Calendar date picker"); 
    } 

    /* 
    * Returns an ImageIcon, or null if the path was invalid. 
    */ 
    protected ImageIcon createImageIcon(String path, String description) { 
     URL imgURL = getClass().getResource(path); 
     String fileName = imgURL.getFile().replace("bin/", "src/"); 
     fileName = fileName.replace("%20", " ").substring(1); 
     ImageIcon icon = new ImageIcon(fileName, description); 
     return icon; 
    } 

    protected void createPanel() { 
     removeAll(); 
     setBorder(BorderFactory.createLineBorder(Color.black, 3)); 
     setFocusable(true); 
     setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); 
     if (controlsOnTop) { 
      add(createControls()); 
      add(createCalendar()); 
     } else { 
      add(createCalendar()); 
      add(createControls()); 
     } 
     Dimension d = getPreferredSize(); 
     setPreferredSize(new Dimension(d.width, d.height + 8)); 
    } 

    protected JPanel createControls() {   
     JPanel c = new JPanel(); 
     c.setBorder(BorderFactory.createRaisedBevelBorder()); 
     c.setFocusable(true); 
     c.setLayout(new FlowLayout(FlowLayout.CENTER)); 

     prevYear = new JButton("<<"); 
     c.add(prevYear); 
     prevYear.setMargin(new Insets(0,0,0,0)); 
     prevYear.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent arg0) { 
       addYear(-1);   
      } 
     }); 

     prevMonth = new JButton("<"); 
     c.add(prevMonth); 
     prevMonth.setMargin(new Insets(0,0,0,0)); 
     prevMonth.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent arg0) { 
       addMonth(-1);  
      } 
     }); 


     textField = new JTextField(getFormattedDate(), 10); 
     c.add(textField); 
     textField.setEditable(true); 
     textField.setEnabled(true); 
     textField.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent e) { 
       editDate(textField.getText()); 
      } 
     }); 

     nextMonth = new JButton(">"); 
     c.add(nextMonth); 
     nextMonth.setMargin(new Insets(0,0,0,0)); 
     nextMonth.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent arg0) { 
       addMonth(+1); 
      } 
     }); 

     nextYear = new JButton(">>"); 
     c.add(nextYear); 
     nextYear.setMargin(new Insets(0,0,0,0)); 
     nextYear.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent arg0) { 
       addYear(+1);  
      } 
     }); 

     return c; 
    } 

    protected JPanel createCalendar() { 
     JPanel x = new JPanel(); 
     GridBagLayout gridbag = new GridBagLayout(); 
     GridBagConstraints c = new GridBagConstraints(); 

     x.setFocusable(true); 
     x.setLayout(gridbag); 

     String month = monthName.format(currentDisplayDate.getTime()); 
     String year = Integer.toString(getYear()); 

     c.gridx  = 0; 
     c.gridy  = 0; 
     c.gridwidth = 7; 
     c.gridheight = 1; 
     JLabel title = new JLabel(month + " " + year); 
     x.add(title, c); 
     Font font  = title.getFont(); 
//  Font titleFont = new Font(font.getName(), font.getStyle(), 
//    font.getSize() + 2); 
     Font weekFont = new Font(font.getName(), font.getStyle(), 
       font.getSize() - 2); 
     title.setFont(font); 

     c.gridy  = 1; 
     c.gridwidth = 1; 
     c.gridheight = 1; 
     for (c.gridx = 0; c.gridx < 7; c.gridx++) { 
      JLabel label = new JLabel(weekdayNames[c.gridx]); 
      x.add(label, c); 
      label.setFont(weekFont); 
     } 

     Calendar draw = (Calendar) currentDisplayDate.clone(); 
     draw.set(Calendar.DATE, 1); 
     draw.add(Calendar.DATE, -draw.get(Calendar.DAY_OF_WEEK) + 1); 
     int monthInt = currentDisplayDate.get(Calendar.MONTH); 
//  monthInt = 0; 
//  System.out.println("Current month: " + monthInt); 

     c.gridwidth = 1; 
     c.gridheight = 1; 
     int width = getFontMetrics(weekFont).stringWidth(" Wed "); 
     int width1 = getFontMetrics(weekFont).stringWidth("Wed"); 
     int height = getFontMetrics(weekFont).getHeight() + 
       (width - width1); 

     for (c.gridy = 2; c.gridy < 8; c.gridy++) { 
      for (c.gridx = 0; c.gridx < 7; c.gridx++) { 
       JButton dayButton; 
//    System.out.print("Draw month: " + draw.get(Calendar.MONTH)); 
       if (draw.get(Calendar.MONTH) == monthInt) { 
        String dayString = dayName.format(draw.getTime()); 
        if (draw.get(Calendar.DAY_OF_MONTH) < 10) 
         dayString = " " + dayString; 
        dayButton = new JButton(dayString); 
       } else { 
        dayButton = new JButton(); 
        dayButton.setEnabled(false); 
       } 
//    System.out.println(", day: " + dayName.format(draw.getTime())); 
       x.add(dayButton, c); 
       Color color = dayButton.getBackground(); 
       if ((draw.get(Calendar.DAY_OF_MONTH) == getDay()) && 
         (draw.get(Calendar.MONTH) == monthInt)) { 
        dayButton.setBackground(Color.yellow); 
//     dayButton.setFocusPainted(true); 
//     dayButton.setSelected(true); 
       } else 
        dayButton.setBackground(color); 
       dayButton.setFont(weekFont); 
       dayButton.setFocusable(true); 
       dayButton.setPreferredSize(new Dimension(width, height)); 
       dayButton.setMargin(new Insets(0,0,0,0)); 
       dayButton.addActionListener(new ActionListener() { 
        public void actionPerformed(ActionEvent e) { 
         changeDay(e.getActionCommand()); 
        } 

       }); 
       draw.add(Calendar.DATE, +1); 
      } 
//   if (draw.get(Calendar.MONTH) != monthInt) break; 
     } 
     return x; 
    } 

    public void addMonth(int month) { 
     currentDisplayDate.add(Calendar.MONTH, month); 
     createPanel(); 
     validate(); 
     repaint(); 
    } 

    public void addYear(int year) { 
     currentDisplayDate.add(Calendar.YEAR, year); 
     createPanel(); 
     validate(); 
     repaint(); 
    } 

    public void editDate(String date) { 
     parseDate(date); 
     createPanel(); 
     validate(); 
     repaint(); 
    } 

    protected void parseDate(String date) { 
     String[] parts = date.split("/"); 
     if (parts.length == 3) { 
      currentDisplayDate.set(Calendar.MONTH, 
        Integer.valueOf(parts[0]) - 1); 
      currentDisplayDate.set(Calendar.DAY_OF_MONTH, 
        Integer.valueOf(parts[1])); 
      currentDisplayDate.set(Calendar.YEAR, 
        expandYear(Integer.valueOf(parts[2]))); 
     } else if (parts.length == 2) { 
      currentDisplayDate = Calendar.getInstance(); 
      currentDisplayDate.set(Calendar.MONTH, 
        Integer.valueOf(parts[0]) - 1); 
      currentDisplayDate.set(Calendar.DAY_OF_MONTH, 
        Integer.valueOf(parts[1])); 
     } else { 
      // invalid date 
      currentDisplayDate = Calendar.getInstance(); 
     } 
    } 

    public void changeDay(String day) { 
     currentDisplayDate.set(Calendar.DAY_OF_MONTH, 
       Integer.valueOf(day.trim())); 
     if (removeOnDaySelection) { 
      firePopupEvent(new ActionEvent(this, 1, "hide")); 
      popup = null; 
     } else { 
      createPanel(); 
      validate(); 
      repaint(); 
     } 
    } 

    public void addPopupListener(ActionListener l) { 
     popupListeners.add(l); 
    } 

    public void removePopupListener(ActionListener l) { 
     popupListeners.remove(l); 
    } 

    public void firePopupEvent(ActionEvent e) { 
     for (int i = popupListeners.size() - 1; i >= 0; i--) { 
      ActionListener l = popupListeners.get(i); 
      l.actionPerformed(e); 
     } 
    } 

    public static void main(String[] args) { 
     final JFrame frame = new JFrame("Date Picker"); 
     Container pane = frame.getContentPane(); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setPreferredSize(new Dimension(450, 250)); 
     pane.setLayout(new FlowLayout(FlowLayout.LEFT)); 
     pane.add(new JLabel("Birthdate: ")); 
     final JTextField testDate = new JTextField(10); 
     pane.add(testDate); 
     final DatePicker dp = new DatePicker(); 
     ImageIcon ii = dp.getImage(); 
//  System.out.println(ii.getIconWidth()); 
//  System.out.println(ii.getIconHeight()); 
     final JButton datePicker = new JButton(ii); 
     pane.add(datePicker); 
     datePicker.setPreferredSize(new Dimension(30, 24)); 
     datePicker.setMargin(new Insets(0,0,0,0)); 
     datePicker.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent e) { 
       dp.setDate(testDate.getText()); 
       dp.popupShow(datePicker); 
      } 
     }); 
     dp.addPopupListener(new ActionListener() { 
      public void actionPerformed(ActionEvent e) { 
       testDate.setText(dp.getFormattedDate()); 
       dp.popupHide(); 
      } 
     }); 
     frame.pack(); 
     frame.setFocusable(true); 
     frame.setResizable(true); 
     frame.setVisible(true); 
    } 
} 
5

나는이 오래된 질문이다 알지만, 결국 SwingsLab 데모에 대한 클레오 파트라의 의견에서, 여기에 답을 발견했다.

는 SwingsLab 데모는 구성 요소별로에 사용자 지정 일정 헤더를 설정하는 방법의 예를 제공하지만, 이것은 내가 실제로 사용되는 코드 (이 세계이며, 응용 프로그램 별)입니다 :

UIManager.put(CalendarHeaderHandler.uiControllerID, SpinningCalendarHeaderHandler.class.getName()); 
datePicker = new JXDatePicker(); 
datePicker.getMonthView().setZoomable(true); //this is needed for custom header 

이것은 실험 코드 (아직 완전히 공개되지 않은 것 같습니다)이므로 위험을 감수하십시오. 희망이 도움이됩니다.

SwingsLab Demo

+0

nice, someone _really_ 데모를 보았습니다 :-) – kleopatra

+0

@Radiace Wei Q Ong 게시물 주셔서 감사하지만 코드를 사용하면 이미지에 표시되는대로 연도가 표시되지 않습니다. 나는 같은 요구 사항을 가지고있다. –

+0

@Syed Muhammad Mubashir 그것은 나를 위해 일한다. SwingsLab 데모에서 코드를 사용해보십시오. 사진은 데모에서 가져온 것입니다. –

0

개선 :

을 DateTimePicker 너무 멀리 버튼으로부터 그래서 라인 139

:

public Popup getPopup(Container c) { 

    if (popup == null) { 

     Point p = c.getLocation(); 

     PopupFactory factory = PopupFactory.getSharedInstance(); 


// FramePrinc.Location.x ==> public static Point Location ; in class FramePrinc 

    popup = factory.getPopup(c, this, FramePrinc.Location.x,FramePrinc.Location.y); 

    } 

    return popup; 

} 

과 행동 안에 당신의 위치를 ​​얻을 구성 요소

그래서 :

  • 내가 버튼 액션
  • 내부 말했다 라인을 넣어 패널 내부에 당신에게 dateTimePiker를 추가 예를 들어 FramePrinc
  • 만들 공공 정적 포인트 위치 :

    • 다른 클래스를 생성

    행운 행운

    Grine_Amine 개선 :

  • 0

    JXDatePicker에 내장/이전 버튼이 없기 때문에 소프트웨어 패키지를 사용하지 않은 주된 이유가 있습니다. 그렇지 않으면 더 나은 날짜 선택기 중 하나입니다.

    대신 LGoodDatePicker을 권하고 싶습니다. 여기에는 연중 계속되는 버튼과 원하는 연도를 선택하기위한 메뉴가 있습니다. 공정한 공개 : 저는이 프로젝트의 주요 개발자입니다. 그것이 귀하의 필요에 부합하는지 알려주십시오.

    LGoodDatePicker 홈 페이지 : https://github.com/LGoodDatePicker/LGoodDatePicker

    릴리스 섹션에서 작업 데모 (실행 jar 파일) 및 gitub 페이지에 핵심 기능의 목록이 있습니다.

    스크린 샷은 아래에 있습니다.

    enter image description here