单击按钮创建不同的jLabel

时间:2016-03-27 20:35:48

标签: java swing jbutton jlabel

我为我的第一个Java应用程序写了一个杂货店。我的第一个版本效果很好。如果您填写两个文本字段并从下拉列表中选择一个项目并按下添加按钮。具有金额和单位的项目显示在文本区域的第二个jPanel中。 但现在我不想在文本区域中显示它,而是希望jLabel中显示的项目。因此,每次单击“添加”按钮时,第二个jPanel中都会出现一个新标签。但我似乎无法让它发挥作用。我在stackoverflow和google上的不同网站上阅读了很多不同的方法,我也阅读了oracle网站。但我一定是做错了。你能看看我的代码并告诉我我做错了什么吗?

CODE

GroceryList2ActionListener.java

package javaclasses;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import grocerylist2jframe.GroceryList2JFrame;
import java.awt.Dimension;
import javax.swing.Box;
import javax.swing.JLabel;

public class GroceryList2ActionListener {

    public static class GroceryListActionListenerHandler extends GroceryList2JFrame   {
        protected static String groceryItem, unit, quantity;
        protected static JButton buttonAddGroceryItemToGrocerylist = buttonAddGroceryItem, buttonRemoveGroceryItemFromGrocerylist = buttonRemoveGroceryItem;
        protected static JLabel label;

        public static void getButtonActionAddGroceryItem() {
            buttonAddGroceryItemToGrocerylist.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    groceryItem = jTextField1GroceryItem.getText();
                    quantity = jTextField2Quantity.getText();
                    unit = jComboBox1Unit.getSelectedItem().toString();
                    label  =  new JLabel(groceryItem + " " + quantity + " " + unit + "\n");
                    label.setOpaque(true);
                    jPanel2.add(label);
                    jPanel2.add(Box.createRigidArea(new Dimension(0,5)));
                    jPanel2.revalidate();
                } 
            });
        }

        public static void main(String args[]) {

        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);
        }

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new GroceryList2JFrame().setVisible(true);
            }
        });
        getButtonActionAddGroceryItem();

        }
    }
}

GroceryList2JFrame.java

package grocerylist2jframe;


public class GroceryList2JFrame extends javax.swing.JFrame {

    public GroceryList2JFrame() {
        initComponents();
    }

    @SuppressWarnings("unchecked")                         
    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();

        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)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(buttonRemoveGroceryItem)
                .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

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 391, Short.MAX_VALUE)
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 455, Short.MAX_VALUE)
        );

        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:
    } 

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

我添加了我的JFrame.java。问题是什么都没发生。没有添加jLabel。我知道如何更改令人兴奋的jLabel的文本,但不知道如何使用相同的按钮添加多个标签。

1 个答案:

答案 0 :(得分:4)

你的主要问题是你

  • 你试图将组件添加到1)错误的JPanel,而不是jPanel2而不是jPanel4
  • 布局:您的JPanel正在使用GroupLayout,这种布局不喜欢以您正在使用的方式添加组件
  • 严重过度使用和误用静电。
  • 滥用继承:您的GroceryListActionListenerHandler绝对应该扩展GroceryList2JFrame。

建议:

  • 摆脱主要方法以外的所有静态
  • 为您的jPanel4提供更好的布局管理器,例如BoxLayout。
  • 或者更好的是,使用JList

例如:

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;

import javax.swing.*;

@SuppressWarnings("serial")
public class SimpleGroceryList extends JPanel {
    private static final int JLIST_VISIBLE_ROWS = 25;
    private JTextField itemField = new JTextField(10);
    private JSpinner itemNumberSpinner = new JSpinner(new SpinnerNumberModel(1, 0, 10, 1));
    private JButton addItemButton = new JButton(new AddItemAction(this, "Add Item", KeyEvent.VK_A));
    private JPanel itemPanel = new JPanel();
    private DefaultListModel<String> listModel = new DefaultListModel<>();
    private JList<String> itemJList = new JList<>(listModel);

    public SimpleGroceryList() {
        JPanel addItemPanel = new JPanel();
        addItemPanel.add(new JLabel("Item:"));
        addItemPanel.add(itemField);
        addItemPanel.add(new JLabel("Count:"));
        addItemPanel.add(itemNumberSpinner);
        addItemPanel.add(addItemButton);

        // give jpanel a border and a decent layout that will accept jlabels well
        itemPanel.setBorder(BorderFactory.createTitledBorder("Item Panel"));
        itemPanel.setLayout(new BoxLayout(itemPanel, BoxLayout.PAGE_AXIS));

        // make the JList large
        itemJList.setVisibleRowCount(JLIST_VISIBLE_ROWS);

        setLayout(new GridLayout(1, 0));
        add(addItemPanel);
        add(new JScrollPane(itemPanel));
        add(new JScrollPane(itemJList));
    }

    // public methods that our Action can use
    public String getNewItemText() {
        return itemField.getText();
    }

    public int getNewItemCount() {
        return (int) itemNumberSpinner.getValue();
    }

    public void addNewItem(String newItem) {
        // add to jpanel
        itemPanel.add(new JLabel(newItem));
        itemPanel.revalidate();
        itemPanel.repaint();

        // add to jlist
        listModel.addElement(newItem);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            createAndShowGui();
        });
    }

    private static void createAndShowGui() {
        SimpleGroceryList mainPanel = new SimpleGroceryList();
        JFrame frame = new JFrame("SimpleGroceryList");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }
}

@SuppressWarnings("serial")
class AddItemAction extends AbstractAction {
    private SimpleGroceryList simpleGroceryList;

    // pass the GUI into this class
    public AddItemAction(SimpleGroceryList simpleGroceryList, String name, int mnemonic) {
        super(name);  // the button's text
        putValue(MNEMONIC_KEY, mnemonic);  // the button's alt-key hot-key
        this.simpleGroceryList = simpleGroceryList; // set a field with the parameter
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        // create our new item string
        String item = simpleGroceryList.getNewItemText();
        int count = simpleGroceryList.getNewItemCount();
        String newItem = item + ": " + count;

        // and pass it into gui
        simpleGroceryList.addNewItem(newItem);
    }
}