-1

I have a form that the user has 3 buttons to choose. Based on the choice different text and options appear and then there is a second button. The form responds to the first button and to the second button (You will see the separator appears (sep1)) but is not doing the second if Statement. I tried converting the button to a String and use switch but it didn't work and I also tried creating the if statement with both conditions &&. Please see code below.

public class WelcomeNDeposit extends JFrame implements ActionListener {

JLabel userId, message, notePs, personalOpeningMsg, busOpenMsg, 
commOpenMsg, accountMsg, balanceMsg;
JButton personal, business, community, depositButton, mainMenu;
JTextField orgName, depositAmount;
JSeparator sep, sep1;

int min = 10000001;
int max = 99999999;
int accountNo = (int) Math.floor(Math.random() * (max - min + 1) + min);
int overdraft = 1500;  


Connection con = Model.connect();
Statement stmt;
ResultSet rs;
String userTitle, userLName;

public WelcomeNDeposit(User user) {

    this.setSize(600, 600);
    this.setTitle("Welcome");
    this.setLayout(null);

    userId = new JLabel("User ID: " + user.id);
    userId.setSize(250, 30);
    userId.setLocation(350, 15);

    message = new JLabel("<Html>Welcome " + user.title + " " + user.lastName + "<p><br> "
            + "Please select if you are applying as an individual, Business or Community Centre</p></Html?");
    message.setSize(540, 180);
    message.setLocation(10, 20);
    
    personal = new JButton("Personal");
    personal.setText("Individual");
    personal.setSize(120, 40);
    personal.setLocation(80, 135);
    personal.addActionListener(this);
    this.add(personal);

    business = new JButton();
    business.setText("Business");
    business.setSize(120, 40);
    business.setLocation(80, 170);
    business.addActionListener(this);
    this.add(business);

    community = new JButton();
    community.setText("Community");
    community.setSize(120, 40);
    community.setLocation(80, 200);
    community.addActionListener(this);
    this.add(community);

    notePs = new JLabel("Ps. You will be able to add other type of accounts later");
    notePs.setSize(500, 50);
    notePs.setLocation(50, 230);
    this.add(notePs);

    sep = new JSeparator();
    sep.setSize(420, 15);
    sep.setLocation(70, 270);

    personalOpeningMsg = new JLabel("<html>You are qualified to £1,500 overdraft facility, "
            + "with an inital deposit of £1,500<p>                     </p></html?");
    personalOpeningMsg.setSize(540, 50);
    personalOpeningMsg.setLocation(30, 280);
    personalOpeningMsg.setVisible(false);

    busOpenMsg = new JLabel("<html>Your Business qualifies to £2,500 overdraft facility, "
            + "with an inital deposit of £2,500<p><br>What is the name of your Company?</p></html>");
    busOpenMsg.setSize(540, 50);
    busOpenMsg.setLocation(30, 280);
    busOpenMsg.setVisible(false);

    commOpenMsg = new JLabel("<html>Your Community Centre qualifies to £1,000 overdraft facility, "
            + "with an inital deposit of £1,000<p> <br> Please provide the Community Centre name "
            + "below </p></html>");
    commOpenMsg.setSize(540, 50);
    commOpenMsg.setLocation(30, 280);
    commOpenMsg.setVisible(false);

    orgName = new JTextField();
    orgName.setSize(240, 25);
    orgName.setLocation(250, 305);
    orgName.setVisible(false);

    accountMsg = new JLabel("How much would you like to deposit?");
    accountMsg.setSize(210, 50);
    accountMsg.setLocation(30, 330);
    accountMsg.setVisible(false);

    depositAmount = new JTextField("0");
    String text = depositAmount.getText();
    int depositamount = Integer.parseInt(text); 
    int balance = overdraft + depositamount; 
    NumberFormat.getCurrencyInstance(new Locale("en", "UK"))
    .format(overdraft);
    depositAmount.setSize(220, 25);
    depositAmount.setLocation(260, 340);
    depositAmount.setVisible(false);
    depositAmount.addKeyListener(new KeyAdapter() {
        public void keyTyped(KeyEvent e3) {
            char c = e3.getKeyChar();
            if (((c < '0') || (c > '9')) && (c != KeyEvent.VK_BACK_SPACE)) {
                e3.consume(); // if it's not a number, ignore the event
            }
        }
    });
    this.add(depositAmount);
    
    depositButton = new JButton();
    depositButton.setText("Deposit");
    depositButton.setSize(120, 40);
    depositButton.setLocation(200, 370);
    depositButton.addActionListener(this);
    depositButton.setVisible(false);
    this.add(depositButton);

    sep1 = new JSeparator();
    sep1.setSize(420, 20);
    sep1.setLocation(60, 420);
    sep1.setVisible(false);
    
    balanceMsg = new JLabel("<html> Your SortCode is 12-34-56, Account number is"
            + " " + accountNo +"<p><br> Your available balance is £"+ balance );
    balanceMsg.setSize(450, 150); 
    balanceMsg.setLocation(30, 380); 
    balanceMsg.setVisible(false);
    this.add(balanceMsg); 

    this.add(userId);
    this.add(message);
    this.add(personal);
    this.add(business);
    this.add(community);
    this.add(personalOpeningMsg);
    this.add(busOpenMsg);
    this.add(commOpenMsg);
    this.add(orgName);
    this.add(accountMsg);

    this.setVisible(true);

    this.add(sep);
    this.add(sep1);

    try {
        stmt = con.createStatement();
        rs = stmt.executeQuery("select * from registrationAtm");
        while (rs.next()) {
            userTitle = rs.getString("personal_title");
            userLName = rs.getString("personal_lastName");

        }
        rs.close();
        stmt.close();
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }

}

@Override
public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub

    if (e.getSource() == personal) {
        JOptionPane.showMessageDialog(null,
                "You are qualified to £1,500 overdraft " + "facility, with an inital deposit of £1,500");
        personalOpeningMsg.setVisible(true);
        accountMsg.setVisible(true);
        depositAmount.setVisible(true);
        depositButton.setVisible(true);
//          personalOpeningMsg.revalidate(); 
//          radioButtonChoice.setEditable(true);

    } else if (e.getSource() == business) {
        JOptionPane.showMessageDialog(null,
                "Your Business qualifies to £2,500 overdraft " + "facility, with an inital deposit of £2,500");
        busOpenMsg.setVisible(true);
        orgName.setVisible(true);
        accountMsg.setVisible(true);
        depositAmount.setVisible(true);
        depositButton.setVisible(true);

//          busOpenMsg.revalidate();
//          radioButtonChoice.setEditable(true);
    } else if (e.getSource() == community) {
        JOptionPane.showMessageDialog(null, "Your Community Centre qualifies to £1,000 overdraft "
                + "facility, with an inital deposit of £2,500");
        commOpenMsg.setVisible(true);
        orgName.setVisible(true);
        accountMsg.setVisible(true);
        depositAmount.setVisible(true);
        depositButton.setVisible(true);
    }
    if(e.getSource()== depositButton) {
        System.out.print("Deposited");
        sep1.setVisible(true);
        if(e.getSource()==personal) {
            balanceMsg.setVisible(true);
        }else if (e.getSource()==business) {
            overdraft = 2500; 
            balanceMsg.setVisible(true); 
        }else if (e.getSource()== community) {
            overdraft =1000; 
            balanceMsg.setVisible(true);
        }
    }   
}

public static void main(String[] args) {
    // TODO Auto-generated method stub
    new LoginPage();

}

}

  • `depositAmount.addKeyListener(new KeyAdapter() {` isn't going to do what you want it to do - look up `DocumentFilter` instead – MadProgrammer Aug 10 '22 at 23:27
  • 2
    You `if` statement is been executed, I think the issue is with the use of `setLayout(null);` primarily and an lack of understanding into how Swing updates work - Swing is lazy, it won't (always) update the UI on a component change (that would be incredibly laggy), instead, you need to let the API know that you'd like it to refresh. `revalidate` and `repaint` are used in these cases – MadProgrammer Aug 10 '22 at 23:31
  • @MadProgrammer The 'KeyAdopter' works. I tried to type in letters. I changed the 'setLayout' to 'BorderLayout' and separately (after I tried together I change it to 'revalidate; I know that the part of the second button has been executed but not the 'if' statement after – Glen Brook Aug 10 '22 at 23:49
  • 1
    Please, respectively, the `KeyAdapter` does not work properly in this scenario, because of the way key events and the `Document` model works, it's possible for the `Document` model to be notified BEFORE your `KeyListener` AND it's possible for APIs to ignore the `consumed` state. This is why the `DocumentFilter` API exists. It also takes into consideration the use case that the user pastes text into the field. – MadProgrammer Aug 10 '22 at 23:53
  • 2
    For [example](https://stackoverflow.com/questions/35929512/jtexfiledrestrict-user-entry/35929812#35929812), [example](https://stackoverflow.com/questions/17074758/make-a-jformattedtextfield-behave-like-atm-input/17076376#17076376). But of course, if you feel you know better, you are welcome to continue using it – MadProgrammer Aug 10 '22 at 23:54
  • Sorry, still going through your code, `e.getSource` can't be equal to `depositButton` AND `personal` (or `business` or `community`) at the same time. I'd suggest using a flag of some kind or `JToggleButton` or `JRadioButton` instead – MadProgrammer Aug 10 '22 at 23:56
  • @MadProgrammer I respect you and will change it to 'DocumentFileter'. It is a school project and I am still learning. At first I tried 'JradioButton'. I will now try JToggleButton' – Glen Brook Aug 11 '22 at 00:01
  • [mcve] please .. mind the __M__ (you are asking about the actionlistener, no need to show anything else like the wrong key listener)! and __never-ever__ do any manual sizing or locating, that's the exclusive task of a layoutManager – kleopatra Aug 11 '22 at 06:10

1 Answers1

1

So, the core issue is right here...

if(e.getSource()== depositButton) {
    System.out.print("Deposited");
    sep1.setVisible(true);
    if(e.getSource()==personal) {
        balanceMsg.setVisible(true);
    }else if (e.getSource()==business) {
        overdraft = 2500; 
        balanceMsg.setVisible(true); 
    }else if (e.getSource()== community) {
        overdraft =1000; 
        balanceMsg.setVisible(true);
    }
}  

It's not possible for e.getSource() to be equal depositButton AND personal (or business or community) at the same time.

So, what's the solution. Well, you could use some kind of flag, maybe an enum, to indicate which option was selected.

However, a better solution would be to use a ButtonGroup and JToggleButton or JRadioButton. This will, not only, prevent the user from making multiple selections (they can only choose one of the options in the group at a time), it will also provide you with the means to determine what is selected.

Have a look at How to Use Buttons, Check Boxes, and Radio Buttons for more details.

This...

depositAmount.addKeyListener(new KeyAdapter() {
    public void keyTyped(KeyEvent e3) {
        char c = e3.getKeyChar();
        if (((c < '0') || (c > '9')) && (c != KeyEvent.VK_BACK_SPACE)) {
            e3.consume(); // if it's not a number, ignore the event
        }
    }
});

is a bad idea. You should be using a DocumentFilter instead. See Implementing a Document Filter, JTexfiled(restrict user entry) and Make a JFormattedTextField behave like ATM input for more details.

You really should be making use of appropriate layout managers, for example, this is what your UI ends up looking like on my PC...

enter image description here

Remember, you're not stuck to using a single layout. In fact you should endeavour to group UI elements together into small container groups, which allows you to focus on the individual layout requirements.

For example, the following makes use of CardLayout, GridBagLayout, BorderLayout and GridLayout

enter image description here

import java.awt.CardLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import javax.swing.border.EmptyBorder;

public class Main {
    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new WelcomeNDeposit(new User()));
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class User {
        String id = "100";
        String title = "Bob";
        String lastName = "Builder";
    }

    public class UserDetailsPane extends JPanel {
        public UserDetailsPane(User user) {
            setLayout(new GridBagLayout());
            setBorder(new EmptyBorder(4, 4, 4, 4));
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.anchor = gbc.LINE_END;
            gbc.weightx = 1;
            gbc.gridwidth = gbc.REMAINDER;

            add(new JLabel("User ID: " + user.id), gbc);
            gbc.anchor = gbc.CENTER;
            add(new JLabel("<Html>Welcome " + user.title + " " + user.lastName + "<p><br> "
                    + "Please select if you are applying as an individual, Business or Community Centre</p></Html?"), gbc);
        }
    }

    public class AccountPropertiesPane extends JPanel {
        private JTextField organisationName;

        public AccountPropertiesPane(String message, boolean isOrganisation) {
            setLayout(new GridBagLayout());
            setBorder(new EmptyBorder(4, 4, 4, 4));
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(4, 4, 0, 4);
            gbc.gridwidth = gbc.REMAINDER;

            gbc.weightx = 1;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            add(new JSeparator(), gbc);

            add(new JLabel(message), gbc);

            if (isOrganisation) {
                organisationName = new JTextField(10);
                JPanel orgPane = new JPanel(new GridBagLayout());
                gbc = new GridBagConstraints();
                gbc.insets = new Insets(4, 4, 4, 4);
                gbc.gridx = 0;
                gbc.gridy = 0;
                gbc.anchor = gbc.LINE_END;
                orgPane.add(new JLabel("Organisation name:"), gbc);
                gbc.weightx = 1;
                gbc.gridx++;
                gbc.fill = gbc.HORIZONTAL;
                gbc.anchor = gbc.LINE_START;
                orgPane.add(organisationName, gbc);

                gbc = new GridBagConstraints();
                gbc.gridwidth = gbc.REMAINDER;
                gbc.anchor = gbc.LINE_START;
                add(orgPane, gbc);
            }
            gbc.weighty = 1;
            add(new JPanel(), gbc);
        }

        public String getOrganisationName() {
            if (organisationName == null) {
                return null;
            }
            return organisationName.getText();
        }

    }

    public class WelcomeNDeposit extends JPanel {

        int min = 10000001;
        int max = 99999999;
        int accountNo = (int) Math.floor(Math.random() * (max - min + 1) + min);
        int overdraft = 1500;

        String userTitle, userLName;

        private JPanel messagePane;
        private CardLayout messageCardLayout = new CardLayout();

        private ButtonGroup typeButtonGroup;

        private JTextField depositField;
        private JPanel depositPane;

        public WelcomeNDeposit(User user) {
            setBorder(new EmptyBorder(8, 8, 8, 8))  ;
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.weightx = 1;
            gbc.gridwidth = gbc.REMAINDER;

            add(new UserDetailsPane(user), gbc);

            JToggleButton personal = new JToggleButton("Individual");
            personal.setActionCommand("individual");
            personal.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    JOptionPane.showMessageDialog(null,
                            "You are qualified to £1,500 overdraft " + "facility, with an inital deposit of £1,500");
                    messageCardLayout.show(messagePane, "personal");
                    depositPane.setVisible(true);
                }
            });

            JToggleButton business = new JToggleButton("Business");
            business.setActionCommand("business");
            business.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    JOptionPane.showMessageDialog(null,
                            "Your Business qualifies to £2,500 overdraft " + "facility, with an inital deposit of £2,500");
                    messageCardLayout.show(messagePane, "business");
                    depositPane.setVisible(true);
                }
            });

            JToggleButton community = new JToggleButton("Community");
            community.setActionCommand("community");
            community.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    JOptionPane.showMessageDialog(null, "Your Community Centre qualifies to £1,000 overdraft "
                            + "facility, with an inital deposit of £2,500");
                    messageCardLayout.show(messagePane, "community");
                    depositPane.setVisible(true);
                }
            });

            typeButtonGroup = new ButtonGroup();
            typeButtonGroup.add(personal);
            typeButtonGroup.add(business);
            typeButtonGroup.add(community);

            JPanel actionsPane = new JPanel(new GridLayout(3, 1));

            actionsPane.add(personal);
            actionsPane.add(business);
            actionsPane.add(community);

            add(actionsPane, gbc);

            messagePane = new JPanel(messageCardLayout);
            add(messagePane, gbc);

            messagePane.add(new JPanel(), "empty");
            messagePane.add(new AccountPropertiesPane("<html>You are qualified to £1,500 overdraft facility, with an inital deposit of £1,500<p></p></html?", false),
                    "personal");
            messagePane.add(new AccountPropertiesPane("<html>Your Business qualifies to £2,500 overdraft facility, with an inital deposit of £2,500<p><br>What is the name of your Company?</p></html>", true),
                    "business");
            messagePane.add(new AccountPropertiesPane("<html>Your Community Centre qualifies to £1,000 overdraft facility, with an inital deposit of £1,000<p> <br> Please provide the Community Centre name below </p></html>", true),
                    "community");

            messageCardLayout.show(messagePane, "empty");

            depositPane = makeDepositPane();
            add(depositPane, gbc);
            depositPane.setVisible(false);
        }

        protected void deposit(double amount) {
            if (typeButtonGroup.getSelection() == null) {
                return;
            }
            switch (typeButtonGroup.getSelection().getActionCommand()) {
                case "individual":
                    JOptionPane.showMessageDialog(this, "Individual deposit: " + amount);
                    break;
                case "business":
                    JOptionPane.showMessageDialog(this, "Business deposit: " + amount);
                    break;
                case "community":
                    JOptionPane.showMessageDialog(this, "Community deposit: " + amount);
                    break;
            }
        }

        protected JPanel makeDepositPane() {
            JPanel pane = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(4, 4, 4, 4);
            gbc.gridx = 0;
            gbc.gridy = 0;
            gbc.anchor = GridBagConstraints.LINE_END;
            pane.add(new JLabel("How much would you like to deposit?"), gbc);

            gbc.anchor = GridBagConstraints.LINE_START;
            gbc.weightx = 1;
            gbc.gridx++;

            depositField = new JTextField(10);
            pane.add(depositField, gbc);

            JButton depositButton = new JButton("Deposite");
            depositButton.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    System.out.println("Hello");
                    // This is where JFormattedTextField would be helpful
                    try {
                        deposit(Double.parseDouble(depositField.getText()));
                    } catch (NumberFormatException exp) {
                        JOptionPane.showMessageDialog(WelcomeNDeposit.this, "Invalid amount");
                    }
                }
            });
            gbc.anchor = GridBagConstraints.CENTER;
            gbc.gridy++;
            gbc.gridx = 0;
            gbc.gridwidth = gbc.REMAINDER;
            pane.add(depositButton, gbc);

            gbc.gridy++;
            gbc.weightx = 1;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            pane.add(new JSeparator(), gbc);

            return pane;
        }
    }
}

nb: The html text is really screwing with me. I might be tempted to use a JTextArea instead, but that's me

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366