如何从另一个类中获取ArrayList以显示在JComboBox中?

时间:2015-12-13 09:45:53

标签: java arraylist jpanel jcombobox

我正在尝试构建一个程序而且我无法从另一个类中获取我的ArrayList以显示在JComboBox中。我的程序将看起来像这样,但在“Melissa”之前写的,我想有一个JComboBox,它有一个用户列表,并能从中选择以获得结果:

enter image description here

更新 这是我的错误:

 ----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.

这是我的不完整代码,它给我一个错误,因为它找不到我的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);
    }
}

这是我的另一个包含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);
    }
}

这是用于制作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";
 //  }

} 

3 个答案:

答案 0 :(得分:1)

首先,您最好从历史记录中调用用户管理器模块,如

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

    manageUsers();

这将启动两个JPanel,以便您可以同时管理用户和观看历史记录。

此外,

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

还有一件事,一旦初始化用户列表,你需要附加一个如下所示的监听器:

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

这两个更正将使您能够在组合框中列出用户名,并且用户列表的动态更改将反映到框中的列表中。

干杯。

答案 1 :(得分:1)

让我在这里上传整个源代码

  1. User.java - 源代码如下(我不知道它们开箱即用的原因。)

    package userchorelist;

    公共类用户{

    private String userName;    private int points = 0;

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

    public User(){       userName =&#34;&#34 ;;    }

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

    public String getUserName(){       return userName;    }

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

  2. ManageUsersGUI.java - 源代码如下(我不知道他们为什么再次开箱了。)

    package userchorelist;

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

    公共类ManageUsersGUI扩展JPanel {     public static ArrayList users = new ArrayList&lt;&gt;();

    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 - 源代码如下(我不知道为什么它们开箱即用,第三次也是最后一次。)

    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;

    公共类UserHistory扩展JPanel {     私人JLabel jcomp1;     private JComboBox userList;     私人JLabel jcomp3;     private JTextField selectedUser;     私人JLabel jcomp5;     私有JTextField pointsEarned;     私人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();
    }
    

    }

答案 2 :(得分:0)

我建议您在<nav class="ui borderless menu"> </nav> <div class="desc"> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </div> <div class="ui container"> </div> <div class="ui container"> </div> <footer class="footer"> some footer at the bottom </footer>UserHistory两个类中添加接收用户列表作为显式参数

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; ... } } ,并将其设为 singleton

UserManagement

然后,您必须在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; } } 方法中进行两个类的实例化时提供用户列表(以及您可能拥有的未来实例):

main