简体   繁体   English

ActionListener 没有用 JButton 单击替换所需的面板

[英]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.我正在创建待办事项列表,并尝试在 FooterPanel 中创建一个名为“添加任务”的按钮,该按钮将消失并替换为提示用户输入有关他们想要的任务的信息添加到列表中。

I'm just having trouble with the ActionListener since it seems like it's not doing anything.我只是在使用 ActionListener 时遇到了麻烦,因为它似乎什么也没做。 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.主要方法将包含主要问题,但我已经提供了我的代码的 rest 作为上下文。

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:以下是代码中引用的Item class:

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.无需使用 static 变量。

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.使用JOptionPane提示用户输入信息。

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.文本字段未显示,因为您需要在添加组件后revalidate()面板,以便可以为文本字段指定大小和位置。

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. JOptionPane 是更简单的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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