我有一个简单的微调器应用程序。使用SpinnerNumberModel创建微调器,使用格式字符串“###”创建JSpinner.NumberEditor:
spinner_ = new JSpinner( new SpinnerNumberModel( 0, 0, 500, 1 ) );
spinner_.setEditor( new JSpinner.NumberEditor( spinner_, "###" ) );
我有一个如下所示的提交程序:
try
{
spinner_.commitEdit();
System.out.println( "success" );
}
catch ( ParseException exc )
{
System.out.println( exc );
}
但是,无论我在编辑器中键入什么值(例如,“nuts”),我都不会得到ParseException;提交将使值恢复为先前提交的值,但不会引发异常。我做错了什么?
示例程序如下。
public class TestSpinner
implements Runnable
{
private final JFrame frame_;
private final JSpinner spinner_;
public static void main(String[] args)
{
new Thread( new TestSpinner() ).start();
}
public TestSpinner()
{
frame_ = new JFrame( "Spinner Test" );
spinner_ = new JSpinner( new SpinnerNumberModel( 0, 0, 500, 1 ) );
spinner_.setEditor( new JSpinner.NumberEditor( spinner_, "###" ) );
}
public void run()
{
JPanel panel = new JPanel( new GridLayout( 2, 1 ) );
frame_.getContentPane().add( panel );
JButton okButton = new JButton( "OK" );
okButton.addActionListener( x -> commit() );
panel.add( spinner_ );
panel.add( okButton );
frame_.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame_.pack();
frame_.setVisible( true );
}
public void commit()
{
try
{
spinner_.commitEdit();
System.out.println( "success" );
}
catch ( ParseException exc )
{
System.out.println( exc );
}
}
}