i'm having a few problem with my phone book program:
1. If the any of the buttons have empty fields, I need to display an error message. How would I do that? Some sort of try/catch statement or if/else statement?

2. I'm a bit clueless as how I would go about doing the update statement.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
/**
 * This program creates a phone book with contacts using swing components.
 *
 */
public class PhoneBook extends JFrame implements ActionListener
{
		ArrayList<String> nameList = new ArrayList<String>();
		ArrayList<String> phoneList = new ArrayList<String>();
        String name;
        String phone;
        double phoneNum;
        int index;

        JPanel northPanel  = new JPanel();
        JPanel centerPanel = new JPanel();
        JPanel southPanel  = new JPanel();

        JLabel nameLabel         = new JLabel("Name");
        JTextField nameField = new JTextField(20);

        JLabel phoneLabel        = new JLabel("Phone");
        JTextField phoneField = new JTextField(20);

        JButton addBtn = new JButton("Add");
        JButton deleteBtn = new JButton("Delete");
        JButton updateBtn = new JButton("Update");
        JButton findBtn   = new JButton("Find");

/**
 * This method creates the instance of phone book and sets the layout. 
 */
        public PhoneBook()
        {
                super ("Phone Book");

                Container c = getContentPane();
                c.setLayout(new BorderLayout());

                northPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
                centerPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
                southPanel.setLayout(new FlowLayout());

                northPanel.add(nameLabel);
                northPanel.add(nameField);

                centerPanel.add(phoneLabel);
                centerPanel.add(phoneField);

                southPanel.add(addBtn);
                southPanel.add(deleteBtn);
                southPanel.add(updateBtn);
                southPanel.add(findBtn);

                c.add(northPanel,BorderLayout.NORTH);
                c.add(centerPanel,BorderLayout.CENTER);
                c.add(southPanel,BorderLayout.SOUTH);

                addBtn.addActionListener(this);
                deleteBtn.addActionListener(this);
                updateBtn.addActionListener(this);
                findBtn.addActionListener(this);
        }
/**
 * This method sets the look and feel and frame for the application.
 * @param args This parameter is the one that takes the arguments.
 */
        public static void main(String[] args)
        {
                try
                {
                        UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
                }

                catch(Exception ex)
                {
                        JOptionPane.showMessageDialog(null,"The UIManager couldn't setthe motif look and feel","Error",JOptionPane.ERROR_MESSAGE);
                }

                PhoneBook f = new PhoneBook();
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                f.setSize(300,140);
                f.setLocation(350,350);
                f.setVisible(true);
        }
/**
 * This method is triggered when names and phone numbers are added to the list.
 */
        public void actionPerformed(ActionEvent e)
        {
                index = 0;
                @SuppressWarnings("unused")
               boolean nameAdded;
                @SuppressWarnings("unused")
               boolean phoneAdded;
                name = new String (nameField.getText());
                phone = new String (phoneField.getText());

                if(e.getSource() == addBtn)
                {
                        nameAdded = nameList.add(name);
                        phoneAdded = phoneList.add(phone);
                        if(nameList.contains(name))
                        {
                                JOptionPane.showMessageDialog(null,"The name "+name+" & phone number "+phone+"  were successfully added","Info",JOptionPane.INFORMATION_MESSAGE);
                                clear();
                        }
                }

                if(e.getSource() == deleteBtn)
                {
                        if(validName())
                        {
                                int phoneIndex = getIndex();
                                nameList.remove(phoneIndex);
                                phoneList.remove(phoneIndex);
                        }

                        {
                                JOptionPane.showMessageDialog(null,"Name "+nameField.getText()+" was successfully removed ","Info",JOptionPane.INFORMATION_MESSAGE);
                                clear();
                        }
                }

                if(e.getSource() == updateBtn)
                {
                }

                if(e.getSource() == findBtn)
                {
                        int findIndex = getIndex();

                        if(findIndex < 0){
                           //no such name..
                           JOptionPane.showMessageDialog(null,"Name not found","Info",JOptionPane.INFORMATION_MESSAGE);
                           clear();
                         }
                         else {
                           //tha name was found - means a legal index
                           //perform that action:
                            phoneField.setText((String)phoneList.get(findIndex));
                         }
                }
        }
/**
 * This method clears the fields.
 */
        public void clear()
        {
                nameField.setText("");
                nameField.requestFocus();
                phoneField.setText("");
        }
/**
 * This method gets the index.
 * @return Returns the name if it is in the list.
 */
		public int getIndex()
		{
			 for(int i = 0;i<nameList.size();i++)
			 {
				   if(nameField.getText().equals(nameList.get(i)))
						 return i;
			 }

			 JOptionPane.showMessageDialog(null,"List does not contain the name "+nameField.getText(),"Info",JOptionPane.INFORMATION_MESSAGE);

			 return -1;
		}

/**
 * This method checks to see if it is a valid name.
 * @return Returns the validName (true) if the name list contains the text entered.
 */
        public boolean validName()
        {
                boolean validName = false;
                if(nameList.contains(nameField.getText()))

                validName = true;
                return validName;
        }
}

Recommended Answers

All 7 Replies

When do you want to check to make sure none of the fields are empty? When the 'add' button is clicked? You need to give more information. Regardless, you'd use an if statement.

if (buttonName.getText().equals("") || otherButton.getText().equals("")) //do something, your button's text was empty!

for the first question your need some code that looks lik:

name = new String(nameField.getText());
        phone = new String(phoneField.getText());
        
        name = name.trim();
        phone = phone.trim();

        if (name.isEmpty() || phone.isEmpty()) {
            JOptionPane.showMessageDialog(null, "Empty values noot allwed", "Warning", JOptionPane.WARNING_MESSAGE);
            return;
        }

Hope it helps.

for the first question your need some code that looks lik:

name = new String(nameField.getText());
        phone = new String(phoneField.getText());
        
        name = name.trim();
        phone = phone.trim();

        if (name.isEmpty() || phone.isEmpty()) {
            JOptionPane.showMessageDialog(null, "Empty values noot allwed", "Warning", JOptionPane.WARNING_MESSAGE);
            return;
        }

Hope it helps.

that helped, thanks!!!

for the update part, i want a previously added name to have the phone number updated. any idea how to go about that?

also i probably shouldn't have suppressed the phoneAdded, nameAdded but it's saying the variable is not read. But i though I was using it with:

nameAdded = nameList.add(name);
                        phoneAdded = phoneList.add(phone);

the code I'v posted before did not resolve the problem here I made some code that support all functinalities: add, remove,find and delete by making some change to your code

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

/**
 * This program creates a phone book with contacts using swing components.
 *
 */
public class PhoneBook extends JFrame implements ActionListener {

    ArrayList<String> nameList = new ArrayList<String>();
    ArrayList<String> phoneList = new ArrayList<String>();
    String name;
    String phone;
    double phoneNum;
    int index;
    JPanel northPanel = new JPanel();
    JPanel centerPanel = new JPanel();
    JPanel southPanel = new JPanel();
    JLabel nameLabel = new JLabel("Name");
    JTextField nameField = new JTextField(20);
    JLabel phoneLabel = new JLabel("Phone");
    JTextField phoneField = new JTextField(20);
    JButton addBtn = new JButton("Add");
    JButton deleteBtn = new JButton("Delete");
    JButton updateBtn = new JButton("Update");
    JButton findBtn = new JButton("Find");

    /**
     * This method creates the instance of phone book and sets the layout.
     */
    public PhoneBook() {
        super("Phone Book");

        Container c = getContentPane();
        c.setLayout(new BorderLayout());

        northPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
        centerPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
        southPanel.setLayout(new FlowLayout());

        northPanel.add(nameLabel);
        northPanel.add(nameField);

        centerPanel.add(phoneLabel);
        centerPanel.add(phoneField);

        southPanel.add(addBtn);
        southPanel.add(deleteBtn);
        southPanel.add(updateBtn);
        southPanel.add(findBtn);

        c.add(northPanel, BorderLayout.NORTH);
        c.add(centerPanel, BorderLayout.CENTER);
        c.add(southPanel, BorderLayout.SOUTH);

        addBtn.addActionListener(this);
        deleteBtn.addActionListener(this);
        updateBtn.addActionListener(this);
        updateBtn.setEnabled(false);
        findBtn.addActionListener(this);
    }

    /**
     * This method sets the look and feel and frame for the application.
     * @param args This parameter is the one that takes the arguments.
     */
    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "The UIManager couldn't setthe motif look and feel", "Error", JOptionPane.ERROR_MESSAGE);
        }

        PhoneBook f = new PhoneBook();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(300, 140);
        f.setLocation(350, 350);
        f.setVisible(true);
    }

    /**
     * This method is triggered when names and phone numbers are added to the list.
     */
    public void actionPerformed(ActionEvent e) {

        String tmpName = new String(nameField.getText());
        String tmpPhone = new String(phoneField.getText());

        tmpName = tmpName.trim();
        tmpPhone = tmpPhone.trim();



        if (e.getSource() == addBtn) {
            if (tmpName.isEmpty() || tmpPhone.isEmpty()) {
                JOptionPane.showMessageDialog(null, "Empty values noot allwed", "Warning", JOptionPane.WARNING_MESSAGE);

            } else {
                add(tmpName, tmpPhone);
            }
        }

        if (e.getSource() == deleteBtn) {
            if (tmpName.isEmpty()) {
                JOptionPane.showMessageDialog(null, "Empty values not allwed", "Warning", JOptionPane.WARNING_MESSAGE);

            } else {
                this.delete(tmpName);
            }
        }

        if (e.getSource() == updateBtn) {
            if (tmpName.isEmpty() || tmpPhone.isEmpty()) {
                JOptionPane.showMessageDialog(null, "Empty values noot allwed", "Warning", JOptionPane.WARNING_MESSAGE);
            } else {
                this.update(this.name, tmpName, tmpPhone);
            }
        }

        if (e.getSource() == findBtn) {
            if (tmpName.isEmpty()) {
                JOptionPane.showMessageDialog(null, "Empty values not allwed", "Warning", JOptionPane.WARNING_MESSAGE);

            } else {
                this.find(tmpName);
            }

        }
    }

    /**
     * This method clears the fields.
     */
    public void clear() {
        nameField.setText("");
        nameField.requestFocus();
        phoneField.setText("");
    }

    private void add(String name, String phone) {
        this.name=name;
        this.phone=phone;
        nameList.add(name);
        phoneList.add(phone);
        if (nameList.contains(name)) {
            JOptionPane.showMessageDialog(null, "The name " + name + " & phone number " + phone + "  were successfully added", "Info", JOptionPane.INFORMATION_MESSAGE);
            clear();
        }
    }

    private void delete(String name) {
        int ind = nameList.indexOf(name);
        if (ind > -1) {
            nameList.remove(ind);
            phoneList.remove(ind);
            this.name = "";
            this.phone = "";
            updateFields();
        } else {
            JOptionPane.showMessageDialog(null, "Name not found", "Info", JOptionPane.INFORMATION_MESSAGE);
        }
    }

    private void find(String name) {
        int ind = nameList.indexOf(name);
        if (ind > -1) {
            this.name = name;
            this.phone = phoneList.get(index);
            updateBtn.setEnabled(true);
            updateFields();
        } else {
            JOptionPane.showMessageDialog(null, "Name not found", "Info", JOptionPane.INFORMATION_MESSAGE);
        }
    }

    private void update(String oldName, String newName, String newPhone) {
        int ind = nameList.indexOf(oldName);
        if (ind > -1) {
            nameList.set(index, newName);
            phoneList.set(index, newPhone);
            updateBtn.setEnabled(false);
        } else {
            JOptionPane.showMessageDialog(null, "Name not found", "Info", JOptionPane.INFORMATION_MESSAGE);
        }
    }

    private void updateFields() {
        this.nameField.setText(name);
        this.phoneField.setText(phone);
    }
}

Don't worry if you see the update button disabled at the firt time it will be anabled as soon as you the update functionality is needed.

Just copy paste and run.
Hope it helps.

Avoid giving people fully working code. Give them tips that will help them learn and occasionally bits of code.

The guy shows effort, he wrote a good structure and i'm just trying to give help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.