我对java编程很陌生,我创建了一个java程序,使用户可以在JFrame上使用JSpinner输入时间(HH:mm:ss格式)。它是通过自定义JSPinner的代码(如下所示)制作的。我想要做的是获取用户输入的值(Time)并将其转换为JLabel上显示的字符串。我尝试过使用状态更改事件,但仅限于整数模型。
JSPinner的自定义代码
Date date = new Date();
SpinnerDateModel sm = new SpinnerDateModel(date, null, null, Calendar.HOUR_OF_DAY);
time_spinner = new javax.swing.JSpinner(sm);
JSpinner.DateEditor te = new JSpinner.DateEditor(time_spinner, "HH:mm:ss");
time_spinner.setEditor(te);
getContentPane().add(time_spinner, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 50, 120, 30));
答案 0 :(得分:3)
在您的问题的上下文中,JSpinner#getValue
将返回Date
个对象。您需要获取Date
对象并以您需要的方式对其进行格式化(例如HH:mm:ss
)
这是How to use Spinners的演示,值得您花时间阅读
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerDateModel;
import javax.swing.SwingUtilities;
public class Test1 {
public static void main(String[] args) {
new Test1();
}
public Test1() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JSpinner time_spinner;
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
Date date = new Date();
SpinnerDateModel sm = new SpinnerDateModel(date, null, null, Calendar.HOUR_OF_DAY);
time_spinner = new javax.swing.JSpinner(sm);
JSpinner.DateEditor te = new JSpinner.DateEditor(time_spinner, "HH:mm:ss");
time_spinner.setEditor(te);
add(time_spinner, gbc);
JButton btn = new JButton("Show me the time");
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Object value = time_spinner.getValue();
if (value instanceof Date) {
Date date = (Date)value;
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
String time = format.format(date);
JOptionPane.showMessageDialog(TestPane.this, "The time is " + time);
}
}
});
add(btn, gbc);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
}