【问题标题】:There is no output in my GroceryList program我的 GroceryList 程序中没有输出
【发布时间】:2016-03-28 12:29:51
【问题描述】:

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

我不知道为什么不这样做。我想我实例化了错误的事情,但看不到哪些事情。我在 stackoverflow 和其他网站上阅读了有关实例化的信息,但我仍然不完全理解它。

我是 java 新手,不会写这么久的代码。我在 Netbeans 中构建了一个布局。每次您单击“添加”按钮时,都会在文本区域中显示一个杂货项目。我的旧代码(一切都是静态的)运行良好。

我有时会收到“线程中的异常“AWT-EventQueue-0”java.lang.ClassCastException:java.lang.Boolean 无法转换为 java.awt.Color”错误。但它不会一直出现。如果我没有收到错误消息,然后单击“添加”按钮,就会注意到正在发生的事情。

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

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

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                   
} 

【问题讨论】:

    标签: java actionlistener jform


    【解决方案1】:

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

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

    此外,有一个带有 main 的“驱动程序”类来实例化框架、设置外观等是有意义的。

    1) 您可以移除/删除 GroceryList2ActionListener 类 - 它不再需要。

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

        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 类的第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);
            }
        });
    

    最后,您将找到现有的方法GroceryList2JFrame.buttonAddGroceryItemActionPerformed(),它是由 NetBeans 创建的。方法我填好了,把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);
        }
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-27
      • 2018-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多