2

I deleted my other post because I was told it wasn't specific and to come back with a more specific question, here goes....

The program is supposed to take in contact info (First & Last name, phone, email) then you click an add button a Contact object will be created and go to an ArrayList. Then when a view button is clicked you will see all of the contacts that were added to it.

I have been watching tutorials and reading in books on how to use GUI and have been able to create a window with all the necessary stuff to add the contact info.

My issues: Where I'm struggling is how to then add this info to an array list

After I figure out how to add the info I will work on how to view it when the view button is clicked.

Any help or tips on moving me forward would be greatly appreciated!

public class InputForm extends JFrame {
    private static JPanel panel;
    private static JLabel firstNameLabel;
    private static JLabel lastNameLabel;
    private static JLabel phoneNumLabel;
    private static JLabel emailLabel;
    private static JLabel contactMessage;
    private static JTextField  firstNameInput;
    private static JTextField  lastNameInput;
    private static JTextField  phoneInput;
    private static JTextField  emailInput;
    private static JButton addButton;
    private static JButton viewButton;
    private String fn;
    private String ln;
    private String ph;
    private String em;
    private List<String> list = new ArrayList<String>();

public InputForm() {
    int windowWidth = 650;
    int windowHeight = 550;

    //Window title
    setTitle("CONTACT FORM");
    //Set window size.
    setSize(windowWidth, windowHeight);
    //Exit on close 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Buld the panel and add it the the JFrame.
    buildPanel();
    //Add the panel to the frames content pane
    add(panel);
    //Display the window.
    setVisible(true);   
}

private void buildPanel() {

    panel = new JPanel();

    addButton = new JButton("Add Contact");
    viewButton = new JButton("View Contacts");

    firstNameLabel = new JLabel("First Name");
    firstNameInput = new JTextField(10);
    lastNameLabel = new JLabel("Last Name: ");
    lastNameInput = new JTextField(10);
    phoneNumLabel = new JLabel("Phone Number: ");
    phoneInput = new JTextField(10);
    emailLabel = new JLabel("Email: ");
    emailInput = new JTextField(10);


    /*Add labels, text fields and buttons to the panel*/
    panel.add(firstNameLabel);
    panel.add(firstNameInput);
    panel.add(lastNameLabel);
    panel.add(lastNameInput);
    panel.add(phoneNumLabel);
    panel.add(phoneInput);
    panel.add(emailLabel);
    panel.add(emailInput);
    panel.add(addButton);
    panel.add(viewButton);

    theHandler handler = new theHandler();
    addButton.addActionListener(handler);
    viewButton.addActionListener(handler);

}


private class theHandler implements ActionListener {

public void actionPerformed(ActionEvent event) {
    fn = firstNameInput.getText();
    ln = lastNameInput.getText();
    ph = phoneInput.getText();
    em = emailInput.getText();
    Contact con = new Contact(fn, ln, ph, em);  

    if(event.getSource() == addButton) {
        list.add(con);  
    }
    else if(event.getSource() == viewButton) {
        JOptionPane.showMessageDialog(null,"Contact Info:\n" + con);        
    }
    else if(event.getSource() == viewButton) {
        JOptionPane.showMessageDialog(null, con);       
    }

}

}

public static void main(String[] args) {
    new InputForm();

}

}

Ok here is a contact class I created based on the advice from "Hovercraft Full of Eels".

public class Contact {
    private String fn;
    private String ln;
    private String ph;
    private String em;

private List<Contact> list = new ArrayList<Contact>();

public Contact(String fn, String ln, String ph, String em) { 
    this.fn = fn;
    this.ln = ln;
    this.ph = ph;
    this.em = em;
}
    public String getFirstName() {
        return fn;
    }
    public void setFirstName(String fn) {
        this.fn = fn;
    }

    public String getLastName() {
        return ln;
    }
    public void setLastName(String ln) {
        this.ln = ln;
    }

    public String getPhone() {
        return ph;
    }
    public void setPhone(String ph) {
        this.ph = ph;
    }

    public String getEmail() {
        return fn;
    }   
    public void setEmail(String em) {
        this.em = em;
    }

    public String toString() {
        return "First Name: " + getFirstName() + "\n" +
                "Last Name: " + getLastName() + "\n" +
                "Phone Number: " + getPhone() + "\n" +
                "Email: " + getEmail() + "\n";
    }

public static void main(String[] args) {
    new InputForm();

}
}
1
  • What problem are you having now? Does this compile? Do you have some other problem? Commented Sep 19, 2015 at 23:49

2 Answers 2

4

Suggestions:

  1. First and foremost, create a non-GUI Contact class, one that has fields for first name, last name, phone number and email address, one with a decent constructor that takes Strings for the four fields as a parameter, one with getter and setter methods.
  2. Also give Contact a decent public String toString() override method. This can be very helpful when you want to debug your code.
  3. Make your List a List<Contact> and same for the ArrayList -- it should be an ArrayList<Contact>.
  4. In your handler ActionListener, extract the Strings from the JTextFields, and create a Contact object.
  5. Then add the Contact object to your List.
  6. There's no need to use an iterator like you're doing when adding data to the List. You simply create a Contact instance and call the List's add(...) method, and that's it.
  7. You're done.

Side recommendations (unrelated to your main question):

  1. Read up on and play with the layout managers as their use can make your GUI look much more pleasing and be much more functional.
  2. For data entry of this type, I like to use a GridBagLayout, and also I usually give my class a helper method for creating GridBagConstraints to simplify its use.
  3. I try to avoid extending JFrame since this forces you to create and display JFrames, when often more flexibility is called for. In fact, I would venture that most of the Swing GUI code that I've created and that I've seen does not extend JFrame, and in fact it is rare that you'll ever want to do this. More commonly your GUI classes will be geared towards creating JPanels, which can then be placed into JFrames or JDialogs, or JTabbedPanes, or swapped via CardLayouts, wherever needed. This will greatly increase the flexibility of your GUI coding.
  4. A decent toString method would display the state of the class's fields. For instance for a Contact class, it would create and return a String that held the first name, last name, phone number and email address of that contact. Then if you need to debug your program and iterate through the List to see what it holds, you could simply call System.out.println(myContact); on each Contact item in the List, and useful information would be printed. Also if you display the List in a JList, the toString is used by default to display each item in the JList's model.
  5. Your code grossly over-uses the static modifier, something that makes it non-object oriented and thus somewhat inflexible code. I would suggest that most all of your fields should be non-static instance fields.

For example, something like:

import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;

import javax.swing.*;

@SuppressWarnings("serial")
public class InputForm2 extends JPanel {
    private static final int COLS = 10;
    private List<ShoppingItem> shoppingList = new ArrayList<>();
    private JTextField nameField = new JTextField(COLS);
    private JTextField skuField = new JTextField(COLS);
    private JTextField priceField = new JTextField(COLS);    

    public InputForm2() {
        JPanel formPanel = new JPanel(new GridBagLayout());
        formPanel.add(new JLabel("Item Name:"), createGbc(0, 0));
        formPanel.add(nameField, createGbc(1, 0));
        formPanel.add(new JLabel("Item SKU:"), createGbc(0, 1));
        formPanel.add(skuField, createGbc(1, 1));
        formPanel.add(new JLabel("Price:"), createGbc(0, 2));
        formPanel.add(priceField, createGbc(1, 2));

        JPanel btnPanel = new JPanel(new GridLayout(1, 0, 4, 4));
        btnPanel.add(new JButton(new AddItemAction("Add Item")));
        btnPanel.add(new JButton(new DisplayItemsAction("Display Items")));

        setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
        setLayout(new BorderLayout());
        add(formPanel, BorderLayout.CENTER);
        add(btnPanel, BorderLayout.PAGE_END);
    }

    private static GridBagConstraints createGbc(int x, int y) {
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = x;
        gbc.gridy = y;
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        gbc.anchor = x == 0 ? GridBagConstraints.WEST : GridBagConstraints.EAST;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        int inset = 4;
        int leftInset = x == 0 ? inset : 3 * inset;
        gbc.insets = new Insets(inset, leftInset, inset, inset);
        return gbc;
    }

    private class AddItemAction extends AbstractAction {
        public AddItemAction(String name) {
            super(name);
            int mnemonic = (int) name.charAt(0); // mnemonic keystroke
            putValue(MNEMONIC_KEY, mnemonic);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            // TODO finish this
            // get Strings from fields
            // create ShoppingItem object
            // add to shoppingList

        }
    }

    private class DisplayItemsAction extends AbstractAction {
        public DisplayItemsAction(String name) {
            super(name);
            int mnemonic = (int) name.charAt(0); // mnemonic keystroke
            putValue(MNEMONIC_KEY, mnemonic);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            // TODO finish this

        }
    }

    private static void createAndShowGui() {
        InputForm2 mainPanel = new InputForm2();

        JFrame frame = new JFrame("InputForm2");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGui();
            }
        });
    }
}

class ShoppingItem {
    private String name;
    private String skuNumber;
    private double price;
    public ShoppingItem(String name, String skuNumber, double price) {
        this.name = name;
        this.skuNumber = skuNumber;
        this.price = price;
    }
    public String getName() {
        return name;
    }
    public String getSkuNumber() {
        return skuNumber;
    }
    public double getPrice() {
        return price;
    }

    @Override
    public String toString() {
        return String.format("name: %s, sku: %s, price: $%0.df", name, skuNumber, price);        
    }
}

Note that this uses a different non-GUI class and JTextFields, but I want you to get and borrow the ideas, not the code. :)


Edit

Regarding your updated question, your error message is telling you exactly what is wrong. This code:

    if(event.getSource() == addButton) {
    fn = firstNameInput.getText();
    ln = lastNameInput.getText();
    ph = phoneInput.getText();
    em = emailInput.getText();
    list.add(fn + "\n" + ln + "\n" + ph + "\n" + em + "\n");   

does not add a Contact object to the list, but rather tries to add a concatenated String (one with new line characters as separators???) to the list, but a String is not allowed nor wanted here. Again as per my suggestions above, you should use the Strings held in your text fields, create a Contact object, and then add that object to your list.

Sign up to request clarification or add additional context in comments.

16 Comments

Yeah after I got this actually working correctly my next step was to mess with the Layout manager to make it look nice.
@user3862586: see what I mean in the example code above.
Lol I would never borrow your code but I greatly appreciate the ideas! I updated my code but I'm still getting errors in list.add since I changed it too a List<Contact>, error says String parameters are not applicable for List<Contact>
@user3862586: I just noticed that your code grossly over-uses the static modifier. Most all of your fields should not be static. Please change this.
@user3862586: and the error message is telling you exactly what you're doing wrong. You're trying to add a String to the List when you need to add a new Contact(...) object.
|
1

You dont need an iterator to add elements to the list. and you probably want to add all the data as 1 String. Using multiple add(); will create multiple entries... a better approach will be to create a Contact object that contains all the parameters as fields and use a List<Contact> instead of List<String>.

public void actionPerformed(ActionEvent event) {

    if(event.getSource() == addButton) {
        fn = firstNameInput.getText();
        ln = lastNameInput.getText();
        ph = phoneInput.getText();
        em = emailInput.getText();
        list.add(fn + ", " + ln + ", " + ph + ", " + em + ".");
        }
    }
    else if(event.getSource() == viewButton) {
        JOptionPane.showMessageDialog();        
    }

2 Comments

Thanks for the info but I'm getting an error on list.add saying the arguments of type string are not applicable for List<Contact> and also showMessageDialog() needs two parameters
If you want to change the List<String> to List<Contact> - You need to create a Contact class. objects of that class will fit in List<Contact>. if you want to stay with List<String> , You can add 1 String for each contact (seperated by commas for example).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.