Java 试图使用GUI解决问题,但如果语句让我困惑

Java 试图使用GUI解决问题,但如果语句让我困惑,java,Java,我正试图解决一个项目,但我陷入了一个问题 •您的程序应显示一个菜单,允许用户执行以下操作: 以下操作说明:使用GUI: 1.添加新客户 2.删除客户 3.修改客户信息//此选项必须将子菜单显示为: ----1. 个人客户//修改基本信息:电话。。。 代码: 我的第一个问题是:为什么下面的if语句是假的 if (actionEvent.getSource().equals(individualCustomer)) { 我的第二个问题是:如果if语句为真。。例如,如果我键入 if(true){

我正试图解决一个项目,但我陷入了一个问题

•您的程序应显示一个菜单,允许用户执行以下操作: 以下操作说明:使用GUI: 1.添加新客户 2.删除客户 3.修改客户信息//此选项必须将子菜单显示为: ----1. 个人客户//修改基本信息:电话。。。 代码:

我的第一个问题是:为什么下面的if语句是假的

if (actionEvent.getSource().equals(individualCustomer)) {
我的第二个问题是:如果if语句为真。。例如,如果我键入

if(true){
         frame.dispose();
         System.out.println("Enter the new phone number: ");
         int updatedPhoneNumber = input.nextInt();
     }
它在我选择ModifyCustomer选项后立即运行此块。不显示我在此处创建的单个客户选项/按钮:

        individualCustomer = new JButton("Individual customer");
        individualCustomer.addActionListener(this);
如果你不知道答案,并且对这个项目问题有更好的逻辑答案,请分享它们,我将从那里开始工作。

你有一个巨大的ActionListener,一个试图同时做太多事情的人。由于代码的连接方式,第二个if语句永远不会为真。您嵌套了if,因此如果外部if为true,允许访问内部if,则内部if将始终为false:

if (actionEvent.getSource().equals(modifyCustomer)) {
    // if we're here, then source will **never** be individualCustomer

    //..... code here

    // the if-test below will **always** be false
    if (actionEvent.getSource().equals(individualCustomer)) {
         // .... code here
    }
}
如果是串联的,您可以制作这些:

if (actionEvent.getSource().equals(modifyCustomer)) {

    //.....

} else if (actionEvent.getSource().equals(individualCustomer)) {

    //.....

}
那就行了

最好给每个JButton提供自己的匿名内部ActionListener,以分离关注点

individualCustomer = new JButton("Individual customer");
individualCustomer.addActionListener(() -> {
    // button-specific listener code goes here
});
关于本守则:

if(true){
     frame.dispose();
     System.out.println("Enter the new phone number: ");
     int updatedPhoneNumber = input.nextInt();
}
看起来您正试图将线性控制台编程与Scanner和println与事件驱动的GUI混合在一起,但这几乎总是会失败,因为这两种模式不能很好地混合。在这里,坚持一个范例,坚持以事件驱动的方式通过GUI获取所有输入,并删除基于System.in的所有扫描仪代码


最后一件事,请务必查看

您有actionEvent.getSource.equalsmodifyCustomer,只有当这是真的时,才检查actionEvent.getSource.equalsindividualCustomer。如果第一个是真的,那么第二个就不可能是真的。我总是使用单独的听众,所以我很少需要做出这样复杂的选择。
if(true){
     frame.dispose();
     System.out.println("Enter the new phone number: ");
     int updatedPhoneNumber = input.nextInt();
}