有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

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

 //Modify Customer
    if (actionEvent.getSource().equals(modifyCustomer)) {
        frame.dispose();
        frame = new JFrame();
        panel = new JPanel();

        individualCustomer = new JButton("Individual customer");
        individualCustomer.addActionListener(this);

        panel.setBorder(BorderFactory.createEmptyBorder(100, 100, 100, 100));
        panel.setLayout(new GridLayout(0, 1));
        panel.add(individualCustomer);

        frame.setTitle("General Distribution Center");
        frame.add(panel, BorderLayout.CENTER);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);

        //Individual Customer
        if (actionEvent.getSource().equals(individualCustomer)) {
            frame.dispose();
            System.out.println("Enter the new phone number: ");
            int updatedPhoneNumber = input.nextInt();
        }

我的第一个问题是:为什么下面的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);

请如果你不知道答案,并有更好的回答这个项目的问题,分享他们的逻辑,我会从那里工作


共 (1) 个答案

  1. # 1 楼答案

    你有一个巨大的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获取所有输入,并根据系统删除所有扫描仪代码。在


    最后一件事,请看一下The Use of Multiple JFrames, Good/Bad Practice?