简体   繁体   中英

ActionListener not replacing desired panel with JButton click

I'm creating a To-Do list and I'm attempting to create a button in the FooterPanel called "Add Task" that will disappear and be replaced with a prompt for the user to type in information regarding the task they'd like to add to the list.

I'm just having trouble with the ActionListener since it seems like it's not doing anything. I'm not sure what I'm doing wrong.

The following is the relevant code, any help at all would be appreciated. The main method will contain the main issue, but I've provided the rest of my code for context.

import java.lang.reflect.Array;
import java.util.*;
import java.lang.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;


public class ToDo{

    ArrayList<Item> TodoList = new ArrayList<>();
    static int size=0;

    public void addItem(String item, String category, int priority)
    {
        TodoList.add(new Item(item,category,priority));
        size++;
    }

    //remove item at specified index spot
    private void removeItem(String item )
    {
        TodoList.remove(getIndex(item));
        size--;

    }

    public void getList()
    {
        for (Item item : TodoList)
        {
            System.out.println(item.toString());
        }
    }

    // Return the index of the searched item, accounts for differences in white spaces and cases
    public int getIndex(String item)
    {
        //return -1 if not found  ,  \\s+ => more than one white space
        int index = -1;
        String itemString = item.replaceAll("\\s+", "").toLowerCase();
        for (int i = 0; i < TodoList.size(); i++) {
            String listItem = TodoList.get(i).getItem().replaceAll("\\s+", "").toLowerCase();
            if (listItem.contains(itemString)) {
                index = i;
                break;
            }
        }
        return index;
    }

    public String getItemString(int i)
    {
        return TodoList.get(i).toString();
    }

    public void sortItems()
    {
        TodoList.sort(Item.priorityComparator);
    }


    public void print() {
        System.out.println("To-do List: ");
        System.out.println("-----------");
        getList();
        if (TodoList == null) {
            System.out.println("You're all done for today!");
        }
    }



    public static void main(String[] args) {

        ToDo todo = new ToDo();

        todo.addItem("Get pickles", "Shopping", 2);
        todo.addItem("Read book", "School", 3);
        todo.addItem("Send letter", "Other", 1);
        todo.addItem("Buy planner", "School", 4);
        todo.addItem("Get potatoes", "Shopping", 3);

        //initialize data array to hold items
        String[] data = new String[100];

        for (int i = 0; i < size; i++) {
            //sort items and populate data array with items converted to string
            todo.sortItems();
            data[i] = todo.getItemString(i);
        }

        ///declare components of panels
        JCheckBox[] checkBox;
        JButton resetButton = new JButton("Reset List");
        ;
        JButton addButton = new JButton("Add Task");

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        JPanel headerPanel = new JPanel();
        JPanel contentPane = new JPanel();
        JPanel footerPanel = new JPanel();

        JLabel title = new JLabel("TO-DO");
        headerPanel.add(title);


        contentPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(5, 5));

        checkBox = new JCheckBox[size];
        JPanel centerPanel = new JPanel();
        centerPanel.setLayout(new GridLayout(0, 1, 5, 5));

        for (int i = 0; i < size; i++) {
            checkBox[i] = new JCheckBox(data[i]);
            centerPanel.add(checkBox[i]);
        }

        contentPane.add(headerPanel, BorderLayout.NORTH);
        contentPane.add(centerPanel, BorderLayout.CENTER);


        footerPanel.add(resetButton);
        footerPanel.add(addButton);

        contentPane.add(footerPanel, BorderLayout.SOUTH);



        JButton okButton = new JButton("OK");
        okButton.addActionListener(new ActionListener() {
           public void actionPerformed(ActionEvent e) {
               footerPanel.add(new JTextField("What category is the task?"));
           }
       });


        frame.setContentPane(contentPane);
        frame.setSize(400,500);
        frame.setResizable(false);
        frame.setLocationByPlatform(true);
        frame.setVisible(true);




        todo.print();

        System.out.println("-----------------\n");

        todo.removeItem("Get pickles");

        todo.sortItems();

        
        todo.print();




    }
}

The following is the Item class referenced in the code:

import java.util.Comparator;

public class Item{

    private String item;
    private String category;
    private int priority;



    //default constructor to initialize
    public Item(String item, String category, int priority){
        this.item = item;
        this.category = category;
        this.priority = priority;
    }



    public String getItem() {
        return item;
    }

    public void setItem(String item) {
        this.item = item;
    }

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }

    public void setPriority(int priority) {
        this.priority = priority;
    }

    public int getPriority() {
        return priority;
    }


    public String translatePriority()
    {
        if (priority == 1)
            return "low";
        else if (priority == 2)
            return "medium";
        else if (priority == 3)
            return "high";
        else if (priority == 4)
            return "urgent";
        else
            return "invalid priority";

    }


    @Override
    public String toString() {
        return "PRIORITY: " +
                translatePriority() + " || " + category + ", " + item + " ";
    }

    // override Compare method of Comparator in order to reorder based on priority
    public static Comparator<Item> priorityComparator = new Comparator<Item>() {

        public int compare(Item i1, Item i2) {

            int priority1 = i1.getPriority();
            int priority2 = i2.getPriority();

            /*For ascending order*/
            return priority2-priority1;

        }};



}

First of all:

  1. Variable names should NOT start with an upper case character
  2. There is no need to use a static variable.

with a prompt for the user to type in information regarding the task they'd like to add to the list.

Use a JOptionPane to prompt the user for information.

See: How to Make Dialogs for more information and examples.

footerPanel.add(new JTextField("What category is the task?"));

The text field doesn't show because you need to revalidate() the panel after adding the component so the text field can be given a size and location.

However, even doing that won't help because you create a component without a reference, so you won't be able to get the text typed by the user easily. Also, how would you then remove the component from the panel (easily without a reference)?

The JOptionPane is the simpler solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM