【问题标题】:How to properly set time to JSpinner in Java?如何在 Java 中正确设置 JSpinner 的时间?
【发布时间】:2014-11-20 08:35:10
【问题描述】:

我想将我在 Neatbeans swing 中的 JSpinner 设置为当前时间,并允许用户通过单击上下箭头来选择时间。我有这些代码,起初以某种方式工作,但在单击箭头时无法更改时间。这是我的代码:

JSpinner spinner = new JSpinner();
spinner.setModel(new SpinnerDateModel());
mySpinnerControl.setEditor(new JSpinner.DateEditor(spinner, "HH:mm"));

当我单击箭头键时,时间不会改变并收到此错误消息:

java.lang.ClassCastException: javax.swing.SpinnerNumberModel cannot be cast to javax.swing.SpinnerDateModel

我的代码有什么问题?我通过网络进行了研究,它们都有相同的代码。 任何帮助将不胜感激。 先谢谢了。

【问题讨论】:

  • 如需更好的帮助,请告诉我们MCVE。可能有很多问题。
  • 对不起,我是 java 编程新手。你说的抛出异常的代码是什么意思?你的意思是整个错误信息?还是我的代码?
  • 其实,看我编辑的评论。 (刷新页面。)是的,你的代码。抛出异常时,会有一个行号。
  • 但实际上我能想到的有几件事可能是错误的,因此最好提供一个可运行的示例。你所有的代码,如果它很短,如果它更长,你应该尽可能地减少它。

标签: java netbeans time jspinner


【解决方案1】:

mySpinnerControl 是什么?当我将mySpinnerControl 更改为spinner 时,我可以让您的示例生效。我的猜测是您将编辑器设置在另一个组件上,因此 spinner 仍然使用数字编辑器,然后在尝试设置日期/时间值时会产生异常。

以下代码对我有用:

public class Spinner extends JFrame {
    public Spinner() {

        JSpinner spinner = new JSpinner();
        spinner.setModel(new SpinnerDateModel());
        spinner.setEditor(new JSpinner.DateEditor(spinner, "HH:mm"));

        getContentPane().add(spinner, BorderLayout.CENTER);
    }

    public static void main(String[] args) {
        Spinner f = new Spinner();
        f.pack();
        f.setVisible(true);
    }

}

【讨论】:

  • 我不知道如何称呼它,但我在 netbeans 中使用摇摆控件。 mySpinnerControl 是我使用该变量名的挥杆控制。我在 netbeans 的调色板窗格中获得了控制权..
【解决方案2】:

..我终于成功了!我只是使用了以下两行代码:

mySpinnerControl.setModel(new SpinnerDateModel());
mySpinnerControl.setEditor(new JSpinner.DateEditor(mySpinnerControl, "HH:mm"));

但非常感谢@cello 和@Radiodef 的回复。非常感谢你们!

【讨论】:

    【解决方案3】:

    在我为 JSpinner 写之前,让我告诉你使用 Date 函数,如下所示。

      Date d1 = new Date(0);
      Calendar cl = Calendar. getInstance();       
      cl.setTime(d1);      
      System.out.println("today is " + d1.toString());
    

    然后是JSpinner,可以按如下方式使用。将格式更改为仅“dd”可以为您提供日期。要对其进行操作,请使用整数解析器(注释掉的行)对其进行转换。

    SimpleDateFormat formaterD = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); 
    String  spinnerDate=formaterD.format(testSpin.getValue());
    //int z=Integer.parseInt(spinnerValue);
    System.out.println(spinnerDate);
    //System.out.println("Date in integer format:"+z);
    
    //To err is Human!Please comment if I'm wrong.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-26
      相关资源
      最近更新 更多