ActionListener无法正常工作

时间:2013-02-27 23:55:58

标签: java swing user-interface awt actionlistener

我对编程很陌生,我需要为pethouse程序创建一个GUI,允许用户添加,删除和排序记录。

问题在于,无论出于何种原因,ActionListeners都无效。 GUI打开得足够好,但如果我点击菜单项,则没有任何反应。 Quit MenuItem不做任何事情,添加动物也不做任何事情。删除也不起作用(虽然这也可能是我的编程错误。)

以下是代码:

import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.border.Border;
import javax.swing.table.DefaultTableModel;
import scrap.knockoff;

public class knockoff extends JFrame {

    private ButtonHandler handler;
    static int animals;
    static Color Backgroundcolor = Color.red;
    private JTable thelist;
    private JTextField search, breed, category, buyprice, sellprice;
    private JMenuBar menuBar;
    private JMenu menu;
    private JMenuItem menuAdd, menuDelete, menuQuit;
    private JLabel maintitle, breedquery, categoryquery, buypricequery, sellpricequery;
    private JButton sortbreed, sortcat, sortdog, sortratios, searchButton, add, delete, modify;
    private JPanel animalPane, sortPane, titlePane, searchPane, tablePane, optionPane;
    static Container container;
    static int recnumber;
    static String control[] = new String[100];
    static double buyprices, sellprices, profitratios;
    static String BreedName, CategoryName;
    static String Pets[][] = new String[50][5];

    public knockoff() {
        super("The Peel Pet House Program"); //This just changes the name at the top there.
        setSize(700, 600);
        Border paneEdge = BorderFactory.createEmptyBorder(0, 10, 10, 10);
        JTabbedPane tabbedPane = new JTabbedPane();
        tabbedPane.setLocation(0, 30);
        tabbedPane.setSize(200, 100);
        //These are our panels. The sortPane just keeps the buttons responsible for sorting the animals where they are. The animalPane is for the other functions (add, delete, whatnot) and the title pane
        //just holds the title. The AnimalPane is just a constant, it's there just so that the Animals menu process has a place to be. The Table Pane holds the table.
        tablePane = new JPanel();
        tablePane.setLocation(200, 35);
        tablePane.setSize(500, 500);
        titlePane = new JPanel();
        titlePane.setSize(700, 30);
        animalPane = new JPanel();
        Border greenline = BorderFactory.createLineBorder((Color.green).darker());
        animalPane.setBorder(greenline);
        animalPane.setLocation(0, 135);
        animalPane.setSize(200, 400);
        sortPane = new JPanel();
        sortPane.setBorder(paneEdge);
        search = new JTextField();
        searchButton = new JButton("Search");
        searchPane = new JPanel();
        FlowLayout searchLayout = new FlowLayout();
        searchPane.setLayout(searchLayout);
        searchPane.setBorder(paneEdge);
        search.setPreferredSize(new Dimension(190, 30));
        searchPane.add(search);
        searchPane.add(searchButton);
        optionPane = new JPanel();
        optionPane.setSize(100, 30);
        //This establishes our table
        String[] columns = {"Breed", "Category", "Buying Price", "Selling Price", "Profit Ratio"};
        thelist = new JTable(Pets, columns);
        JScrollPane listbrowser = new JScrollPane(thelist);
        tablePane.add(listbrowser);
        //These establish the buttons for our various sorting sprees.
        sortbreed = new JButton("Breed");
        sortcat = new JButton("Cat");
        sortdog = new JButton("Dog");
        sortratios = new JButton("Profit Ratio");
        sortPane.add(sortbreed);
        sortPane.add(sortcat);
        sortPane.add(sortdog);
        sortPane.add(sortratios);
        //Our ever reliable menu bar maker.
        menuBar = new JMenuBar();
        setJMenuBar(menuBar);
        menu = new JMenu("File");
        menuBar.add(menu);
        //The items of the file menu.
        menuQuit = new JMenuItem("Quit");
        menuQuit.addActionListener(handler);
        menu.add(menuQuit);
        //Animal Menu Creation
        menu = new JMenu("Animals");
        menuBar.add(menu);
        menuAdd = new JMenuItem("Add an Animal");
        menuAdd.addActionListener(handler);
        menu.add(menuAdd);
        menuDelete = new JMenuItem("Delete Animal");
        menuDelete.addActionListener(handler);
        menu.add(menuDelete);
        //Adding everything to the container now.
        Container container = getContentPane();
        container.setLayout(null);
        maintitle = new JLabel("The Piddly Penultimate Peel Pet House Program");
        titlePane.add(maintitle);
        container.setBackground(Backgroundcolor.darker()); //This just makes a darker version of red to set as the background on the Content Pane. Grey is boring.
        container.add(tablePane);
        container.add(titlePane);
        container.add(tabbedPane);
        container.add(animalPane);
        container.add(optionPane);
        tabbedPane.addTab("Sort By:", null, sortPane, "Sorts the Table");
        tabbedPane.addTab("Search", null, searchPane, "The Search Function");
    }

    public static void main(String args[]) {
        knockoff application = new knockoff();
        application.setVisible(true);
    }

    private class ButtonHandler implements ActionListener {

        public void actionPerformed(ActionEvent event) {
            if (event.equals("Add an Animal")) {
                addananimal();
            } else if (event.equals("Delete Animal")) {
                deleteanimal();
            } else if (event.getSource().equals(add)) //getsource relates to the button, it just makes it so that anybody programming can freely change the text of the button without worrying about this.
            {
                addanimal();
            } else if (event.getSource().equals(delete)) {
                deleteanimal();
            } else if (event.getSource().equals(sortbreed)) {
                breedsort();
            } else if (event.getSource().equals(sortcat)) {
            } else if (event.getSource().equals(sortdog)) {
            } else if (event.getSource().equals(sortratios)) {
            } else if (event.equals("Quit")) {
                hide();
                System.exit(0);
            }
        }
        //Add new Record Method

        public void addananimal() {
            container = getContentPane();
            //Plate cleaner. Or dishwasher.
            if (animalPane != null) {
                container.remove(animalPane);
            }
            animalPane = new JPanel();
            Border greenline = BorderFactory.createLineBorder((Color.green).darker());
            animalPane.setBorder(greenline);
            animalPane.setLocation(0, 135);
            animalPane.setSize(200, 400);
            FlowLayout animalLayout = new FlowLayout();
            animalPane.setLayout(animalLayout);
            breedquery = new JLabel("Add Animal Name:");
            categoryquery = new JLabel("Cat or Dog?");
            buypricequery = new JLabel("Buying Price:");
            sellpricequery = new JLabel("Selling Price:");
            animalPane.add(breedquery);
            breed = new JTextField(18);
            animalPane.add(breed);
            animalPane.add(categoryquery);
            category = new JTextField(18);
            animalPane.add(category);
            animalPane.add(buypricequery);
            buyprice = new JTextField(18);
            animalPane.add(buyprice);
            animalPane.add(sellpricequery);
            sellprice = new JTextField(18);
            add = new JButton("Add Animal");
            //The above list of .add and JComponent things were just to establish the
//            contents of our new animalPane.
            profitratios = Double.parseDouble(sellprice.getText()) / Double.parseDouble(buyprice.getText());
            //This just makes finding the profit ratio an autonomous action.
            add.addActionListener(handler);
            animalPane.add(add);
            container.add(animalPane);
            setVisible(true);
        }

        public void addanimal() {
            animals = animals + 1;
            Pets[animals][0] = breed.getText();
            Pets[animals][1] = category.getText();
            Pets[animals][2] = buyprice.getText();
            Pets[animals][3] = sellprice.getText();
            Pets[animals][4] = profitratios + "";
            breed.setText(" ");
            category.setText(" ");
            buyprice.setText(" ");
            sellprice.setText(" ");
            thelist.repaint(); //This is supposed to update the JTable in real time.
        }

        public void deleteanimal() {
            removeSelectedRows(thelist);
        }

        public void removeSelectedRows(JTable table) {
            DefaultTableModel model = (DefaultTableModel) table.getModel();
            int[] rows = table.getSelectedRows();
            for (int x = 0; x < rows.length; ++x) {
                model.removeRow(rows[x] - x);
            }
            for (int x = 0; x < animals; ++x) {
                if (Pets[x][0].equalsIgnoreCase(table.getValueAt(table.getSelectedRow(), 0) + "")) {
                    Pets[x][0] = null;
                    Pets[x][1] = null;
                    Pets[x][2] = null;
                    Pets[x][3] = null;
                    Pets[x][4] = null;
                }
            }
        }

        public void breedsort() {
            for (int x = 0; x < animals; ++x) {
            }
        }
    }
}

2 个答案:

答案 0 :(得分:3)

您永远不会初始化ButtonHandler,这意味着每次拨打addActionListener(handler)时,您实际上都在呼叫addActionListener(null)

尝试在将构建函数添加到任何内容之前初始化构造函数中的处理程序...

public knockoff() {
    super("The Peel Pet House Program"); //This just changes the name at the top there.
    handler = new ButtonHandler();

<强>更新

更好的是,请查看Action API而不是

答案 1 :(得分:1)

你没有在任何地方实例化和注册ButtonHandler ......