2016-03-27 12 views
1

Ich schrieb meine erste Java-Anwendung eine Einkaufsliste. Meine erste Version hat gut funktioniert. Wenn Sie die beiden Textfelder ausfüllen und ein Element aus der Dropdown-Liste auswählen, klicken Sie auf die Schaltfläche HINZUFÜGEN. Die Artikel mit den Mengen und Einheiten wurden im 2. jPanel in einem Textbereich angezeigt. Aber jetzt, anstatt es in einem Textbereich anzuzeigen, möchte ich die Elemente in jLabels angezeigt. Jedes Mal, wenn Sie auf die Schaltfläche HINZUFÜGEN klicken, sollte ein neues Label im zweiten jPanel erscheinen. Aber ich kann es nicht zur Arbeit bringen. Ich lese hier auf Stackoverflow und verschiedenen Seiten auf google viele verschiedene Wege und lese auch die Orakelseite. Aber ich muss etwas falsch machen. Könntest du dir meinen Code ansehen und mir sagen, was ich falsch mache?Erstellen Sie verschiedene jLabels auf Knopfdruck

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     
} 

Ich habe meine JFrame.java. Das Problem ist, dass nichts passiert. Es wurde kein jLabel hinzugefügt. Ich weiß, wie man den Text eines aufregenden jLabel ändert, aber nicht wie man mehrere Labels mit der gleichen Schaltfläche hinzufügt.

+0

Sieht ein XY-Problem zu sein: Nicht JLabels verwenden, sondern sie einfach in einem JList setzen. Es ist wie mit JLabels, aber besser, einfacher, vollständiger. –

+1

Unabhängig davon, ohne eine gültige [MCVE], wird dies eine harte Nuss zu knacken sein. Bitte überlegen Sie einen mit Ihrer Frage zu posten. –

+1

Ihre Verwendung von statischen macht mir Sorgen, und schlägt vor, dass der Rest Ihres Programms sie auch verwendet und sie möglicherweise übermäßig verwendet. Der statische Modifikator ist nicht dein Freund und sollte sparsam verwendet werden. Ihre Frage hört sich möglicherweise als eine missbrauchte Referenz an, aber das ist schwer zu sagen, und wieder wird Ihre mcve uns sehr helfen. –

Antwort

4

Ihre Hauptprobleme areyou

  • Sie versuchen, Komponenten zu 1) die falschen JPanel hinzuzufügen, zu jPanel2 anstelle des approprate jPanel4
  • Layouts: Ihre JPanels Grouplayout verwenden, ein Layout, das doesn Es ist nicht so, als hätten Sie Komponenten hinzugefügt, so wie Sie es tun.
  • Grobe Überbeanspruchung und falsche Verwendung von Statik.
  • Missbrauch der Vererbung: Ihr GroceryListActionListenerHandler sollte auf jeden Fall nicht verlängern GroceryList2JFrame.

Vorschläge:

  • Lassen Sie sich andere alle Statik befreien als die wichtigste Methode
  • Ihre jPanel4 einen besseren Layout-Manager geben, wie BoxLayout.
  • Oder noch besser, eine JList verwenden

Zum Beispiel:

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

Vielen Dank für den Hinweis, ich werde meinen Code umschreiben –