Search code examples
javaswingjoptionpane

Create an input box controls booleans


I've been attempting for a while now, to use an input box, such where a user enters "activate tv" which then displays the status of the TV on a line for examples the initial line is "tv(no)" turns to "tv(yes)" after user inputs "activate tv" and vice versa when user inputs "deactivate tv" the line should update and say "tv(no)".

I want to use an array like I did for the amount of items the user can input at the start but I don't know how to tackle the problem to create an array for the status of each item the user inputs and could be activated/deactivated by the user, using the input box.

//USING A BOOLEAN FOR (YES) / (NO)
boolean status = false;
String stat;
if (status == false) {
    stat = "(no)";
}else {
    stat = "(yes)";
}

//CREATES AN ARRAY OF SIZE INPUTTED BY THE USER
String[] Item = new String[amount];
for (int i = 0; i < Item.length; i++) {
    Item[i] = showInputDialog("Please enter item?");
}

System.out.print("The available items are: ");
//PRINTS THE INPUT BY THE USER FROM ARRAY TO CONSOLE
String joinedString = String.join(stat+", ", Arrays.asList(Items));
System.out.print(joinedString);
System.out.print(sta);

//I DON'T KNOW HOW I COULD USE THIS INPUT DIALOG TO ACTIVATE AND DEACTIVATE THE ITEMS IN THE ARRAY
String input = showInputDialog("activate / deactivate?");

Any suggestions on how i could solve this problem would be appreciated, as i am a beginner to java.


Solution

  • The way I would approach the problem is as follows:

    1. Create a custom class to keep track of all of the items, ItemManager.
    2. ItemManager should contain a HashMap, allowing <key, value> pairs to be stored. This will allow the item and its status to be stored together. We will use the name of each item as the key (this will be a string), and the status of each item as the value (this will be a Boolean). We therefore define a HashMap<String, Boolean>. Because we have each item's name stored in this HashMap, we no longer need to store them in the array which you mentioned previously (to get a list of all items we could simply use hashMap.keySet().toArray()). The final advantage of a HashMap is that the number of elements can grow indefinitely, you are not confined by the number the user first enters, as with an array.
    3. ItemManager should have queries enabling you to add an item (with a default state of false), add an item with a custom state, check whether an item exists, and update the status of an item.
    4. By querying whether an item is active, you can then determine what the text within the output box should say.
    import java.util.HashMap;
    
    public class ItemManager {
    
        private HashMap<String, Boolean> itemMap;
        private final Boolean DEFAULT_STATUS = false;
    
        ItemManager(){
           itemMap = new HashMap<String, Boolean>();
        }
    
        // Add a new item with a given name and default status (False)
        public void addItem(String name) {
            itemMap.put(name, DEFAULT_STATUS);
        }
    
        // Add a new item with a given name and custom status
        public void addItem(String name, Boolean status) {
           itemMap.put(name, status);
        }
    
        // Check whether an item exists
        public Boolean itemExists(String name) {
            if (getStatus(name) == null) {
                return false;
            } else {
                return true;
            }
        }
    
        // Remove an item with given name
        public void removeItem(String name) {
            itemMap.remove(name);
        }
    
        // Update the status of an existing item. Note this uses the same .put method so we simply call addItem()
        public void setStatus(String forItem, Boolean status) {
            addItem(forItem, status);
        }
    
        // Get the status of a given item
        public Boolean getStatus(String forItem) {
            return itemMap.get(forItem);
        }
    
    }
    

    Obviously when using the ItemManager class, you will have to be careful to check that the item exists before you update the status (otherwise setStatus() will just create the item anyway - note how it calls addItem() - the reason for this is that HashMap.put() adds a new <key, value> pair if the key does not exist within the HashMap already, or updates the value for the key if it does exist). Ideally you would implement error handling, so that updateStatus() throws an error if the item doesn't already exist, however error handling is a more advanced topic, so it may be worth saving for the future.

    To illustrate the above point, my View class does the following:

    ...
    case "activate":
        itemName = activateItemTextField.getText();
        activateItemTextField.setText("");
        if (itemManager.itemExists(itemName)) {
            itemManager.setStatus(itemName, true);
            outputLabel.setText(itemName + "(yes)");
        } else {
            outputLabel.setText("Item doesn't exist!");
        }
        break;
    ...
    

    This leaves me with something as follows. Apologies for the poor looking view - it's been a long time since I used Swing so and I rushed it together.

    enter image description here enter image description here enter image description here