【发布时间】:2014-02-24 14:22:04
【问题描述】:
我想制作一个 JTable,它应该像地址簿一样使用。 所以有一个用于创建新条目的按钮。 我想使用 JOptionPane InpuDialog 创建这些条目,因为我只想要 创建至少具有姓名和年龄的条目。 我也想检查没有重复(同名)。 所以我向你发布了我的添加按钮的代码。 检查年龄是否在 1 到 100 之间有效,但我忘记检查所选名称是否真的不是重复的,如果您单击确定按钮两次,他接受重复。 所以我的问题是是否适用于使用 i while 循环来实现检查(就像我在下面所做的那样)还是有更简单的方法来实现它?
boolean notAllowed=true;
boolean noCreation=false;
DefaultTableModel dtm = (DefaultTableModel) table
.getModel();
String s = JOptionPane.showInputDialog("Select Name");
for (int i = 0; i < dtm.getRowCount(); i++) {
if (s.equals(dtm.getValueAt(i, 0))) {
s = JOptionPane.showInputDialog("Selected Name already in use \n Select an other Name");
i = 0;
}
}
String c = JOptionPane
.showInputDialog("age?",JOptionPane.OK_OPTION);
while(notAllowed){
try{
int teste =Integer.parseInt(c);
if(teste==JOptionPane.CANCEL_OPTION)
{
notAllowed=false;
noCreation=true;
}
if(teste<=100 && teste>0 &¬Allowed)
notAllowed=false;
}
catch( Exception err)
{
notAllowed=false;
noCreation=true;
}
if(notAllowed)
c = JOptionPane.showInputDialog("Only Numbers between 1 and 100 are allowed");
}
if(!noCreation)
{
//create Entry
}
【问题讨论】:
-
当然,您可以使用 while 循环来执行此操作。当你尝试时发生了什么?
-
工作正常,但我认为可能有更好的解决方案
标签: java swing joptionpane