我试图解决一个项目,但遇到了一个问题。
•您的程序应显示一个菜单,允许用户执行以下操作(注意:使用GUI(:
- 添加新客户
- 删除客户
- 修改客户信息//此选项必须将子菜单显示为:
--------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();
}
在我选择"修改客户"选项后,它会立即运行此块。没有显示我在这里创建的个人客户选项/按钮:
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系列:
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.的Scanner代码
最后一件事,请看一下多个JFrame的使用,好/坏做法?