pyuntae
pyuntae

Reputation: 832

How to get ArrayList from another class to show up inside a JComboBox?

I'm trying to build a program and I am having trouble getting my ArrayList from another class to show up in a JComboBox. My program will look something like this but before where "Melissa" is written, I want to have a JComboBox that has a list of users and be able to select from it to get the results:

enter image description here

UPDATE Here is my error:

 ----jGRASP exec: javac -g UserHistory.java

UserHistory.java:20: error: cannot find symbol
        String[] userListItems = users.toArray(new String[0]);
                                 ^
  symbol:   variable users
  location: class UserHistory
Note: UserHistory.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
1 error

 ----jGRASP wedge2: exit code for process is 1.
 ----jGRASP: operation complete.

Here is my incomplete code which gives me an error because it cannot locate my arrayList:

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

public class UserHistory extends JPanel {
    private JLabel jcomp1;
    private JComboBox userList;
    private JLabel jcomp3;
    private JTextField selectedUser;
    private JLabel jcomp5;
    private JTextField pointsEarned;
    private JLabel jcomp7;
    private JList choresCompleted;

    public UserHistory() {
        //construct preComponents
        String[] userListItems = users.toArray(new String[0]);
        String[] choresCompletedItems = {"Item 1", "Item 2", "Item 3"};

        //construct components
        jcomp1 = new JLabel ("User History");
        userList = new JComboBox(userListItems);
        jcomp3 = new JLabel ("Below are the results of : ");
        selectedUser = new JTextField (5);
        jcomp5 = new JLabel ("Total points earned: ");
        pointsEarned = new JTextField (5);
        jcomp7 = new JLabel ("List of chores completed: ");
        choresCompleted = new JList (choresCompletedItems);

        //set components properties
        userList.setToolTipText ("Select a user");

        //adjust size and set layout
        setPreferredSize (new Dimension (465, 343));
        setLayout (null);

        //add components
        add (jcomp1);
        add (userList);
        add (jcomp3);
        add (selectedUser);
        add (jcomp5);
        add (pointsEarned);
        add (jcomp7);
        add (choresCompleted);

        //set component bounds (only needed by Absolute Positioning)
        jcomp1.setBounds (120, 20, 70, 25);
        userList.setBounds (210, 20, 100, 25);
        jcomp3.setBounds (95, 70, 155, 25);
        selectedUser.setBounds (245, 70, 100, 25);
        jcomp5.setBounds (125, 105, 140, 25);
        pointsEarned.setBounds (245, 105, 100, 25);
        jcomp7.setBounds (95, 140, 160, 25);
        choresCompleted.setBounds (245, 145, 100, 75);
    }


    public static void main (String[] args) {
        JFrame frame = new JFrame ("UserHistory");
        frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add (new UserHistory());
        frame.pack();
        frame.setVisible (true);
    }
}

Here's my code for another panel that contains the ArrayList:

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

public class ManageUsersGUI extends JPanel {
    public ArrayList<User> users = new ArrayList<>();

    private JLabel addNewUserLabel;
    private JTextField addNewUserTextField;
    private JLabel deleteUsersLabel;
    private JButton addButton;
    private JButton deleteButton;
    private JPanel namePanel;


    public ManageUsersGUI() {
        //construct components
        addNewUserLabel = new JLabel ("Add new User here:");
        addNewUserTextField = new JTextField (0);
        deleteUsersLabel = new JLabel ("Select which User(s) you would like to delete:");
        addButton = new JButton ("Add");
        deleteButton = new JButton ("Delete");
        namePanel = new JPanel();
        namePanel.setLayout(new BoxLayout(namePanel, BoxLayout.Y_AXIS));

        //set components properties
        addNewUserTextField.setToolTipText ("Enter name and click on Add button.");
        addButton.setToolTipText ("Click here to Add new user.");
        deleteButton.setToolTipText ("Click here to delete User(s) selected.");

        //adjust size and set layout
        setPreferredSize (new Dimension (580, 485));
        setLayout (null);

        //add components
        add (addNewUserLabel);
        add (addNewUserTextField);
        add (deleteUsersLabel);
        add (namePanel);
        add (addButton);
        add (deleteButton);

        //set component bounds (only needed by Absolute Positioning)
        addNewUserLabel.setBounds (85, 130, 120, 25);
        addNewUserTextField.setBounds (235, 130, 125, 25);
        deleteUsersLabel.setBounds (135, 225, 281, 25);
        addButton.setBounds (385, 130, 100, 25);
        namePanel.setBounds(225, 270, 140, 0);
        deleteButton.setBounds (230, 335, 100, 25);

        addButton.addActionListener(new AddButtonListener());

        deleteButton.addActionListener(new DeleteButtonListener());
    }

    public ArrayList<User> getUser() {
               return users;
            }        

    private class AddButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            String text = addNewUserTextField.getText();
            users.add(new User(text));

            // Display the changes.
            JOptionPane.showMessageDialog(null, text + " has been added.");

            JCheckBox nameCheckBox = new JCheckBox();
            nameCheckBox.setText(addNewUserTextField.getText());
            namePanel.add(nameCheckBox);
            namePanel.setBounds(225, 270, 140, namePanel.getHeight() + 25);
            deleteButton.setBounds(230, deleteButton.getY() + 25, 100, 25);
            JFrame frame = (JFrame) getRootPane().getParent();
            frame.setSize(frame.getWidth(), frame.getHeight() + 25);
            frame.pack(); 

        }
    }

    private class DeleteButtonListener implements ActionListener {
         @Override
         public void actionPerformed(ActionEvent e) {
            for(Component component : namePanel.getComponents()) {
               if(component instanceof JCheckBox) {
                  if(((JCheckBox)component).isSelected())
                     namePanel.remove(component);
               }
            }
            namePanel.revalidate();
            namePanel.repaint();
         }   
    }


    public static void main (String[] args) {
        JFrame frame = new JFrame ("AddUsersPanel1");
        frame.setTitle("Manage Users");
        frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add (new ManageUsersGUI());
        frame.pack();
        frame.setVisible (true);
    }
}

Here's my User class that was used to make the ArrayList:

public class User {

   private String userName;
   private int points = 0;

   public User(String userName) {
      this.userName = userName;
   }

   public User() {
      userName = "";
   }   

   public void setUserName(String userName) {
      this.userName = userName;   
   }

   public String getUserName() {
      return userName;
   }

   public void addPoints(int chorePoints) {
      points += chorePoints;
   }

  // public String toString() {
     // return userName + "\n";
 //  }

} 

Upvotes: 0

Views: 1041

Answers (3)

Park JongBum
Park JongBum

Reputation: 1403

Let me upload the whole source code here

  1. User.java -- Source code just follows (I don't know why they came out of box.)

    package userchorelist;

    public class User {

    private String userName; private int points = 0;

    public User(String userName) { this.userName = userName; }

    public User() { userName = ""; }

    public void setUserName(String userName) { this.userName = userName;
    }

    public String getUserName() { return userName; }

    public void addPoints(int chorePoints) { points += chorePoints; } }

  2. ManageUsersGUI.java -- Source code just follows (I don't know why they came out of box, again.)

    package userchorelist;

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

    public class ManageUsersGUI extends JPanel { public static ArrayList users = new ArrayList<>();

    private JLabel addNewUserLabel;
    private JTextField addNewUserTextField;
    private JLabel deleteUsersLabel;
    private JButton addButton;
    private JButton deleteButton;
    private JPanel namePanel;
    
    
    public ManageUsersGUI() {
        //construct components
        addNewUserLabel = new JLabel ("Add new User here:");
        addNewUserTextField = new JTextField (0);
        deleteUsersLabel = new JLabel ("Select which User(s) you would like to delete:");
        addButton = new JButton ("Add");
        deleteButton = new JButton ("Delete");
        namePanel = new JPanel();
        namePanel.setLayout(new BoxLayout(namePanel, BoxLayout.Y_AXIS));
    
        //set components properties
        addNewUserTextField.setToolTipText ("Enter name and click on Add button.");
        addButton.setToolTipText ("Click here to Add new user.");
        deleteButton.setToolTipText ("Click here to delete User(s) selected.");
    
        //adjust size and set layout
        setPreferredSize (new Dimension (580, 485));
        setLayout (null);
    
        //add components
        add (addNewUserLabel);
        add (addNewUserTextField);
        add (deleteUsersLabel);
        add (namePanel);
        add (addButton);
        add (deleteButton);
    
        //set component bounds (only needed by Absolute Positioning)
        addNewUserLabel.setBounds (85, 130, 120, 25);
        addNewUserTextField.setBounds (235, 130, 125, 25);
        deleteUsersLabel.setBounds (135, 225, 281, 25);
        addButton.setBounds (385, 130, 100, 25);
        namePanel.setBounds(225, 270, 140, 0);
        deleteButton.setBounds (230, 335, 100, 25);
    
        addButton.addActionListener(new AddButtonListener());
    
        deleteButton.addActionListener(new DeleteButtonListener());
    }
    
    public ArrayList<User> getUser() {
               return users;
            }        
    
    private class AddButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            String text = addNewUserTextField.getText();
            users.add(new User(text));
    
            // Display the changes.
            JOptionPane.showMessageDialog(null, text + " has been added.");
    
            JCheckBox nameCheckBox = new JCheckBox();
            nameCheckBox.setText(addNewUserTextField.getText());
            namePanel.add(nameCheckBox);
            namePanel.setBounds(225, 270, 140, namePanel.getHeight() + 25);
            deleteButton.setBounds(230, deleteButton.getY() + 25, 100, 25);
            JFrame frame = (JFrame) getRootPane().getParent();
            frame.setSize(frame.getWidth(), frame.getHeight() + 25);
            frame.pack(); 
    
        }
    }
    
    private class DeleteButtonListener implements ActionListener {
         @Override
         public void actionPerformed(ActionEvent e) {
            for(Component component : namePanel.getComponents()) {
               if(component instanceof JCheckBox) {
                  if(((JCheckBox)component).isSelected())
                     namePanel.remove(component);
               }
            }
            namePanel.revalidate();
            namePanel.repaint();
         }   
    }
    
    
    public static void main (String[] args) {
        JFrame frame = new JFrame ("AddUsersPanel1");
        frame.setTitle("Manage Users");
        frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add (new ManageUsersGUI());
        frame.pack();
        frame.setVisible (true);
    }
    
    // in ManageUsersGUI
    public static void manageUsers() {
        JFrame frame = new JFrame ("AddUsersPanel1");
        frame.setTitle("Manage Users");
        frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add (new ManageUsersGUI());
        frame.pack();
        frame.setVisible (true);
    }
    

    }

  3. UserHistory.java -- Source code just follows (I don't know why they came out of box, third and final time.)

    import java.awt.; import javax.swing.; import javax.swing.event.PopupMenuEvent; import javax.swing.event.PopupMenuListener; import userchorelist.ManageUsersGUI; import static userchorelist.ManageUsersGUI.manageUsers; import static userchorelist.ManageUsersGUI.users; import userchorelist.User;

    public class UserHistory extends JPanel { private JLabel jcomp1; private JComboBox userList; private JLabel jcomp3; private JTextField selectedUser; private JLabel jcomp5; private JTextField pointsEarned; private JLabel jcomp7; private JList choresCompleted;

    public UserHistory() {
        //construct preComponents
        String[] userListItems = new String[users.size()];
    
        String[] choresCompletedItems = {"Item 1", "Item 2", "Item 3"};
    
        //construct components
        jcomp1 = new JLabel ("User History");
        userList = new JComboBox(userListItems);
    
        userList.addPopupMenuListener(new PopupMenuListener() {
            @Override
            public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
                userList.removeAllItems();
                for (User user: users) {
                    userList.addItem(user.getUserName());
                }   
            }
    
            @Override
            public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
            }
    
            @Override
            public void popupMenuCanceled(PopupMenuEvent e) {
            }
        });
    
        jcomp3 = new JLabel ("Below are the results of : ");
        selectedUser = new JTextField (5);
        jcomp5 = new JLabel ("Total points earned: ");
        pointsEarned = new JTextField (5);
        jcomp7 = new JLabel ("List of chores completed: ");
        choresCompleted = new JList (choresCompletedItems);
    
        //set components properties
        userList.setToolTipText ("Select a user");
    
        //adjust size and set layout
        setPreferredSize (new Dimension (465, 343));
        setLayout (null);
    
        //add components
        add (jcomp1);
        add (userList);
        add (jcomp3);
        add (selectedUser);
        add (jcomp5);
        add (pointsEarned);
        add (jcomp7);
        add (choresCompleted);
    
        //set component bounds (only needed by Absolute Positioning)
        jcomp1.setBounds (120, 20, 70, 25);
        userList.setBounds (210, 20, 100, 25);
        jcomp3.setBounds (95, 70, 155, 25);
        selectedUser.setBounds (245, 70, 100, 25);
        jcomp5.setBounds (125, 105, 140, 25);
        pointsEarned.setBounds (245, 105, 100, 25);
        jcomp7.setBounds (95, 140, 160, 25);
        choresCompleted.setBounds (245, 145, 100, 75);
    }
    
    
    public static void main (String[] args) {
        JFrame frame = new JFrame ("UserHistory");
        frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add (new UserHistory());
        frame.pack();
        frame.setVisible (true);
    
        manageUsers();
    }
    

    }

Upvotes: 1

Park JongBum
Park JongBum

Reputation: 1403

First of all you would better call user manager module from history main like

    JFrame frame = new JFrame ("UserHistory");
    frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add (new UserHistory());
    frame.pack();
    frame.setVisible (true);

    manageUsers();

Which will start both JPanels so you can manage users and watch history at the same time.

Additionally,

// in ManageUsersGUI
public static void manageUsers() {
    JFrame frame = new JFrame ("AddUsersPanel1");
    frame.setTitle("Manage Users");
    frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add (new ManageUsersGUI());
    frame.pack();
    frame.setVisible (true);
}

And one more thing, as soon as you initialize userlist you need to attach a listener like below:

    userList = new JComboBox(userListItems);

    userList.addPopupMenuListener(new PopupMenuListener() {
        @Override
        public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
            userList.removeAllItems();
            for (User user: users) {
                userList.addItem(user.getUserName());
            }   
        }

        @Override
        public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
        }

        @Override
        public void popupMenuCanceled(PopupMenuEvent e) {
        }
    });

These two corrections would you make be able to list user names on the combo box and the dynamic change of user list would be reflected to the listing in the box.

Cheers.

Upvotes: 1

Little Santi
Little Santi

Reputation: 8783

I suggest you add receive the list of users as an explicit parameter in both classes UserHistory and ManageUsersGUI:

class UserHistory
{
    private final List<User> users;

    public UserHistory(List<User> users)
    {
        super();
        this.users=users;
        ...
    }
}

class ManageUsersGUI
{
    private final List<User> users;

    public UserHistory(List<User> users)
    {
        super();
        this.users=users;
        ...
    }
}

Then, you can create a unique list of users as an external class, let's say UserManagement, and make it a singleton:

public class UserManagement
{
    private static final UserManagement INSTANCE=new UserManagement();

    private final List<User> list=new ArrayList<User>();

    public static UserManagement getInstance()
    {
        return INSTANCE;
    }

    private UserManagement()
    {
    }

    public List<User> getUsers()
    {
        return users;
    }
}

Then, you must provide the list of users when instatiating both classes in the main methods (and further, future instatiations you may have):

public static void main (String[] args) {
    ...
    UserManagement.getInstance().getUsers().add("winkum");
    UserManagement.getInstance().getUsers().add("blinkum");
    UserManagement.getInstance().getUsers().add("nod");
    frame.getContentPane().add (new UserHistory(UserManagement.getInstance().getUsers()));
    ...
}

Upvotes: 0

Related Questions