主要监听器java - 数量限制
问题描述:
我在JFrame中有一个应用程序。下面是部分代码:主要监听器java - 数量限制
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String input = text.getText();
int number = Integer.parseInt(text.getText());
if(number>0)
{
for(int i=0; i<liczba; i++)
{
new NewWindow();
}
}
}
});
这个动作在创建新的应用程序窗口,其中取决于我们输入数量的窗口数量。我需要确保它是一个数字(不是字母或其他)。我也知道必须使用关键听众,并且输入的符号必须在代表数字的ASCII值之间。但我不知道如何做到这一点。任何解决方案
答
我也知道密钥听者必须使用
没有一个KeyListener的不需要被使用。这可能是最古老的解决方案,并在AWT中使用。 Swing具有更新,更好的API,您应该使用它。
您可以使用JSpinner
,JFormattedTextField
或DocumentFilter
。
阅读Swing Tutorial。你应该检查出部分上:
How to Use a Spinner
How to use Formatted Text Fields
How to Write a DocumentFilter
上述任何一个比使用KeyListener的一个更好的解决方案。
Surround'int number = Integer.parseInt(input);'带'try {...} catch(Exception e){}'如果它到达'catch'部分,这意味着它不是一个数字 – 3kings