Reputation: 11
I'm creating a vending machine for a school project, and I have to update the numbers when user clicks A1, A2, B1, B2 etc. Everything after the decimal changes, but anything before that does not. So if I click A1 which is set to 4 dollars 50 cents, and I then choose D4 which is 1 dollar 5 cents, my JTextField
shows as 4 dollars 5 cents.
This is the buttons on the GUI:
public void cost() {
C_button.addActionListener (new ActionListener () {
public void actionPerformed (ActionEvent e) {
button_1.addActionListener (new ActionListener () {
public void actionPerformed (ActionEvent e) {
total_order = 2 + 0.5;
cost_total.setText(String.valueOf(total_order));
}
});
button_2.addActionListener (new ActionListener () {
public void actionPerformed (ActionEvent e) {
total_order = 2 + 0.25;
cost_total.setText(String.valueOf(total_order));
}
});
button_3.addActionListener (new ActionListener () {
public void actionPerformed (ActionEvent e) {
total_order = 2 + 0.10;
cost_total.setText(String.valueOf(total_order));
}
});
button_4.addActionListener (new ActionListener () {
public void actionPerformed (ActionEvent e) {
total_order = 2 + 0.05;
cost_total.setText(String.valueOf(total_order));
}
});
}
});
D_button.addActionListener (new ActionListener () {
public void actionPerformed (ActionEvent e) {
button_1.addActionListener (new ActionListener () {
public void actionPerformed (ActionEvent e) {
total_order = 1 + 0.5;
cost_total.setText(String.valueOf(total_order));
}
});
button_2.addActionListener (new ActionListener () {
public void actionPerformed (ActionEvent e) {
total_order = 1 + 0.25;
cost_total.setText(String.valueOf(total_order));
}
});
button_3.addActionListener (new ActionListener () {
public void actionPerformed (ActionEvent e) {
total_order = 1 + 0.10;
cost_total.setText(String.valueOf(total_order));
}
});
button_4.addActionListener (new ActionListener () {
public void actionPerformed (ActionEvent e) {
total_order = 1 + 0.05;
cost_total.setText(String.valueOf(total_order));
}
});
}
});
Upvotes: 0
Views: 60
Reputation: 1760
You're make this WAY more difficult than it should be. First, I'd create a map of all the value combinations and their costs, something like:
Map<String, Double> costMap = new HashMap<>();
costMap.put("A1", 4.5);
costMap.put("A2", 4.25);
Then I'd create a String somewhere to track user input:
String register = "";
Then create a Action to handle the basic key pressed for the bulk of your keys:
public class VendingAction extends AbstractAction {
@Override
public void actionPerformed(ActionEvent arg0) {
register += getValue(Action.NAME);
if (costMap.containsKey(register)) {
costLabel.setText(costMap.get(register).toString());
register = "";
} else if (register.length() == 2) {
//handle bad choice
register = "";
}
}
}
Then when you create your buttons it would be something like:
JButton buttonA = new JButton(new VendingAction("A"));
JButton buttonB = new JButton(new VendingAction("B"));
//so on and so forth.
Upvotes: 2