我的 GroceryList 程序中没有输出

There is no output in my GroceryList program

在得到不要像我那样使用静态的建议后,我重写了我的第一个应用程序,我误用了固有性。但是现在我的应用程序不再工作了。

而且我不明白为什么不。我想我实例化了错误的东西,但看不到哪些东西。我在 Whosebug 和其他网站上阅读了有关实例化的信息,但我仍然不完全理解它。

我是 java 的新手,不会编写那么长时间的代码。我在 Netbeans 中构建布局。每次你点击 "Add" 按钮时,一个杂货项目应该显示在文本区域中。我的旧代码(一切都是静态的)工作正常。

我有时会收到 "Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.Boolean cannot be cast to java.awt.Color" 错误。但它不会一直出现。如果我没有收到错误并单击 "Add" 按钮,就会注意到正在发生。

谁能告诉我我做错了什么?

任何关于我做错了什么或如何调试它的建议将不胜感激。

GroceryList2ActionListener.java

    package javaclasses;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import grocerylist2jframe.GroceryList2JFrame;

    // this is the ActionListener for adding a grocery item
    public class GroceryList2ActionListener {
        public void getButtonActionAddGroceryItem() {
        GroceryList2JFrame jFrameAdd = new GroceryList2JFrame();
            jFrameAdd.buttonAddGroceryItem.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    String groceryItem = jFrameAdd.jTextField1GroceryItem.getText();
                    String quantity = jFrameAdd.jTextField2Quantity.getText();
                    String unit = jFrameAdd.jComboBox1Unit.getSelectedItem().toString();
                    jFrameAdd.jTextArea1.append(groceryItem + " " + quantity + " " + unit + "\n" );
                }
            });
        }
        // this is the ActionListener for removing a grocery item
        public void getButtonActionRemoveGroceryItem() {
            GroceryList2JFrame jFrameRemove = new GroceryList2JFrame();
            jFrameRemove.buttonRemoveGroceryItem.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    jFrameRemove.jTextArea1.setText(jFrameRemove.jTextArea1.getText().replaceAll(jFrameRemove.jTextArea1.getSelectedText(),""));
                }
            });
        }

        public static void main(String args[]) {
            /* Set the Nimbus look and feel */
            //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
            /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
             * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
             */
            try {
                for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        javax.swing.UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(GroceryList2JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
            //</editor-fold>
            //</editor-fold>
            /* Create and display the form */
            java.awt.EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    new GroceryList2JFrame().setVisible(true);
                }
            });
            GroceryList2ActionListener action = new GroceryList2ActionListener();
            action.getButtonActionAddGroceryItem(); // I think I call here the "addItem" and "removeItem" on button click.
            action.getButtonActionRemoveGroceryItem();
        }
    }

这是我写的ActionListener。接下来是我在 Netbeans 中制作的应用程序的布局。我不是自己写的,我用的是 JForm。

GroceryList2JFrame.java

package grocerylist2jframe;

public class GroceryList2JFrame extends javax.swing.JFrame {

    /**
     * Creates new form GroceryList2JFrame
     */
    public GroceryList2JFrame() {
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jComboBox1Unit = new javax.swing.JComboBox();
        jTextField2Quantity = new javax.swing.JTextField();
        jTextField1GroceryItem = new javax.swing.JTextField();
        jPanel3 = new javax.swing.JPanel();
        jPanel4 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setSize(new java.awt.Dimension(0, 0));

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Grocerylist2", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Georgia", 3, 18))); // NOI18N
        jPanel1.setFont(new java.awt.Font("Georgia", 1, 11)); // NOI18N

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Grocerylist Input", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Georgia", 3, 14))); // NOI18N

        jLabel2.setFont(new java.awt.Font("Georgia", 1, 11)); // NOI18N
        jLabel2.setText("Choose a Quantity");

        jLabel1.setFont(new java.awt.Font("Georgia", 1, 11)); // NOI18N
        jLabel1.setText("Add a Grocery Item");

        jLabel3.setFont(new java.awt.Font("Georgia", 1, 11)); // NOI18N
        jLabel3.setText("Choose A Unit");

        jComboBox1Unit.setFont(new java.awt.Font("Georgia", 1, 11)); // NOI18N
        jComboBox1Unit.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Kilogram", "Gram", "Liter", "Millilitre", "Piece(s)" }));
        jComboBox1Unit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1UnitActionPerformed(evt);
            }
        });

        jTextField2Quantity.setFont(new java.awt.Font("Georgia", 0, 9)); // NOI18N
        jTextField2Quantity.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField2QuantityActionPerformed(evt);
            }
        });

        jTextField1GroceryItem.setFont(new java.awt.Font("Georgia", 0, 9)); // NOI18N
        jTextField1GroceryItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1GroceryItemActionPerformed(evt);
            }
        });

        buttonAddGroceryItem.setFont(new java.awt.Font("Georgia", 1, 14)); // NOI18N
        buttonAddGroceryItem.setText("Add Grocery Item To Grocerylist");
        buttonAddGroceryItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonAddGroceryItemActionPerformed(evt);
            }
        });

        buttonRemoveGroceryItem.setFont(new java.awt.Font("Georgia", 1, 14)); // NOI18N
        buttonRemoveGroceryItem.setText("Remove Grocery Item From Gocerylist");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 135, Short.MAX_VALUE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jTextField1GroceryItem)
                    .addComponent(jTextField2Quantity)
                    .addComponent(jComboBox1Unit, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
            .addComponent(buttonAddGroceryItem, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(buttonRemoveGroceryItem, javax.swing.GroupLayout.DEFAULT_SIZE, 338, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextField1GroceryItem, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(10, 10, 10)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextField2Quantity, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jComboBox1Unit, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(86, 86, 86)
                .addComponent(buttonAddGroceryItem, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(buttonRemoveGroceryItem, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(217, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );

        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Grocerylist2 View", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Georgia", 1, 14))); // NOI18N

        jTextArea1.setColumns(20);
        jTextArea1.setFont(new java.awt.Font("Georgia", 1, 11)); // NOI18N
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 391, Short.MAX_VALUE)
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1)
        );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(13, 13, 13)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>                        

    private void buttonAddGroceryItemActionPerformed(java.awt.event.ActionEvent evt) {                                                     
        // TODO add your handling code here:
    }                                                    

    private void jTextField1GroceryItemActionPerformed(java.awt.event.ActionEvent evt) {                                                       
        // TODO add your handling code here:
    }                                                      

    private void jTextField2QuantityActionPerformed(java.awt.event.ActionEvent evt) {                                                    
        // TODO add your handling code here:
    }                                                   

    private void jComboBox1UnitActionPerformed(java.awt.event.ActionEvent evt) {                                               
        // TODO add your handling code here:
    }                                              

    /**
     * @param args the command line arguments
     */


    // Variables declaration - do not modify                     
    public final javax.swing.JButton buttonAddGroceryItem = new javax.swing.JButton();
    public final javax.swing.JButton buttonRemoveGroceryItem = new javax.swing.JButton();
    public javax.swing.JComboBox jComboBox1Unit;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    public javax.swing.JTextArea jTextArea1;
    public javax.swing.JTextField jTextField1GroceryItem;
    public javax.swing.JTextField jTextField2Quantity;
    // End of variables declaration                   
} 

我认为你把这个程序复杂化了。其他 SO 用户是正确的,你应该避免对方法和变量使用 static ,除非绝对有道理。您应该阅读一些关于 Java Swing 事件处理的内容,特别是关于如何使用 ActionListener 的内容。

在您的情况下,您不需要单独的 class (GroceryList2ActionListener),因为 NetBeans 正在为您创建事件处理方法(通常)。 GroceryList2JFrame 已经有了处理添加杂货的方法。由于某些原因,当您添加删除按钮时,您在构建表单时没有select添加动作侦听器。

另外,'driver' class 有一个 main 来实例化框架,设置外观等是有意义的

1) 您可以 remove/delete GroceryList2ActionListener class - 它不再需要了。

2) 将此 class 添加到与 GroceryList2JFrame class 相同的包中。这是现在具有 main() 方法的驱动程序 class。

    package grocerylist2jframe;


    public class GroceryList {
        public static void main(String args[]) {
            System.out.println("Running the GroceryList program...");
                /* Set the Nimbus look and feel */
            //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
                /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
                 * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
                 */
            try {
                for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        javax.swing.UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(GroceryList2JFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
            //</editor-fold>
            //</editor-fold>
                /* Create and display the form */
            java.awt.EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    GroceryList2JFrame frame = new GroceryList2JFrame();
                    frame.setVisible(true);
                }
            });
        }
    }

3) 在使用NetBeans 构建表单时,它已经添加了一个事件处理程序方法并为添加按钮注册了它,但是为删除按钮省略了它。如果你查看 GroceryList2JFrame class 的第 70 行,你会看到方法调用 buttonAddGroceryItem.addActionListener()... 我已经添加了一个类似的块来为 buttonRemoveGroceryItem 注册一个新方法。将此代码块放在 `buttonAddGroceryItem.addActionListener() 代码下方:

    buttonRemoveGroceryItem.setFont(new java.awt.Font("Georgia", 1, 14)); // NOI18N
    buttonRemoveGroceryItem.setText("Remove Grocery Item From Gocerylist");
    buttonRemoveGroceryItem.addActionListener(new java.awt.event.ActionListener(){
        public void actionPerformed(java.awt.event.ActionEvent evt){
            buttonRemoveGroceryItemActionPerformed(evt);
        }
    });

最后,您将找到由 NetBeans 创建的现有方法 GroceryList2JFrame.buttonAddGroceryItemActionPerformed()。我已经填写了方法,复制了GroceryList2ActionLIstener的内容,还添加了buttonRemoveGroceryItemActionPerformed()的方法,如下所示:

private void buttonAddGroceryItemActionPerformed(java.awt.event.ActionEvent evt) {
    String groceryItem = jTextField1GroceryItem.getText();
    String quantity = jTextField2Quantity.getText();
    String unit = jComboBox1Unit.getSelectedItem().toString();
    jTextArea1.append(groceryItem + " " + quantity + " " + unit + "\n" );
}

private void buttonRemoveGroceryItemActionPerformed(java.awt.event.ActionEvent evt){
    String choice = jTextArea1.getSelectedText();
    try {
        jTextArea1.setText(jTextArea1.getText().replaceAll(choice, ""));
    }
    catch(Exception ex){
        JOptionPane.showMessageDialog(this, "Please select a valid item from the grocery list before clicking to remove.",
                "Invalid Item selected for removal", JOptionPane.ERROR_MESSAGE);
    }
}

完成这些小改动后,您的程序应该会按预期运行。 祝你好运!