我创建了一个程序,用于将项目添加到连接到MySQL数据库的库存中。当用户点击"添加"一个JOptionPane会询问他们是否希望将该项添加到数据库中。编码似乎是正确的,但当我点击"否"它仍然将项添加到数据库中。这是代码:
int dialogButton = JOptionPane.YES_NO_OPTION;
JOptionPane.showConfirmDialog (null, "Are you sure you want to add this item?",null, dialogButton);
if(dialogButton == JOptionPane.YES_OPTION)
{
Statement stmt=conn.createStatement();
stmt.executeUpdate(query);
if(dialogButton == JOptionPane.NO_OPTION)
{
remove(dialogButton);
}
}
答案 0 :(得分:1)
首先,if(dialogButton == JOptionPane.NO_OPTION)
位于if(dialogButton == JOptionPane.YES_OPTION)
块内。它应该永远不会执行。尝试将其移到该区域之外。
if(dialogButton == JOptionPane.YES_OPTION)
{
Statement stmt=conn.createStatement();
stmt.executeUpdate(query);
}
else if(dialogButton == JOptionPane.NO_OPTION)
{
remove(dialogButton);
}
其次,JOptionPane.showConfirmDialog
返回一个整数,表示按下的按钮。您需要检查此结果是JOptionPane.YES_OPTION
还是JOptionPane.NO_OPTION
。你应该:
int dialogButton = JOptionPane.showConfirmDialog (null, "Are you sure you want to add this item?",null, 0);