【问题标题】:How to get ArrayList from another class to show up inside a JComboBox?如何从另一个类中获取 ArrayList 以显示在 JComboBox 中?
【发布时间】:2015-12-13 09:45:52
【问题描述】:

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

更新这是我的错误:

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

这是我不完整的代码,它给了我一个错误,因为它无法找到我的数组列表:

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 的 User 类:

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

} 

【问题讨论】:

  • 你的问题是......?
  • UserHistory 如何与ManageUsersGUI 绑定?它们都有自己的main方法,它们是独立的程序吗?
  • @LittleSanti 我的问题是我不知道如何使我的 userList JcomboBox 从位于另一个类中的 ArrayList 中获取名称。
  • @WalterM 它们是不同的窗口,我稍后会将它们组合成一个完整的程序。我正在尝试制作一个跟踪用户家务和分数的家务评分程序。 ManageUsersGUI 将用户添加到程序中,您还可以从 JCheckbox 中删除用户。 UserHistory 告诉您您选择查看的每个用户的历史记录。还有一个主页,可让您单击用户历史记录或管理用户并将您重定向到每个框架。

标签: java arraylist jpanel jcombobox


【解决方案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) {
        }
    });

这两个更正你是否能够在组合框中列出用户名,并且用户列表的动态变化将反映在框中的列表中。

干杯。

【讨论】:

  • 问题是我无法初始化我的 userList,因为我不知道如何将 ArrayList 从我的 ManageUsersGUI 解释到 JComboBox 内的 UserHistory 类中。我已经添加了上面得到的错误。
  • 可能你有点糊涂了。不要担心初始化,因为它是在“popupMenuWillBecomeVisible”方法中完成的。只需按照我上传的代码进行操作即可。事实上,我在家里的电脑上有一个完整的运行版本。现在我在工作地点。
  • 我完全按照您的编码并将其放入我的代码中,但它仍然给我同样的错误。
  • ----jGRASP exec: javac -g UserHistory.java UserHistory.java:19: error: cannot find symbol String[] userListItems = users.toArray(new String[0]); ^ symbol: variable users location: class UserHistory UserHistory.java:29: error: cannot find symbol for (User user: users) { ^ symbol: variable users Note: UserHistory.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details. 2 errors ----jGRASP wedge2: exit code for process is 1. ----jGRASP: operation complete.
【解决方案2】:

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

  1. User.java -- 源代码如下(我不知道他们为什么开箱即用。)

    打包用户任务列表;

    公共类用户{

    私有字符串用户名; 私有 int 点 = 0;

    公共用户(字符串用户名){ this.userName = 用户名; }

    公共用户(){ 用户名 = ""; }

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

    公共字符串 getUserName() { 返回用户名; }

    public void addPoints(int chorePoints) { 点 += 杂务点; } }

  2. ManageUsersGUI.java -- 源代码如下(我不知道为什么它们是开箱即用的。)

    打包用户任务列表;

    导入 javax.swing.; 导入 java.awt.; 导入 java.awt.event.*; 导入 java.util.ArrayList; 导入 javax.swing.JCheckBox;

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

    导入 java.awt.; 导入 javax.swing.; 导入 javax.swing.event.PopupMenuEvent; 导入 javax.swing.event.PopupMenuListener; 导入 userchorelist.ManageUsersGUI; 导入静态 userchorelist.ManageUsersGUI.manageUsers; 导入静态 userchorelist.ManageUsersGUI.users; 导入userchorelist.User;

    公共类 UserHistory 扩展 JPanel { 私人 JLabel jcomp1; 私人 JComboBox 用户列表; 私人 JLabel jcomp3; 私人 JTextField selectedUser; 私人 JLabel jcomp5; 私人 JTextField 积分; 私人 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();
    }
    

    }

【讨论】:

  • 有没有办法在不使用包的情况下做到这一点?
  • 我试着用包做这件事,它给了我更多的错误,它仍然找不到用户的符号
【解决方案3】:

我建议您在UserHistoryManageUsersGUI 两个类中添加接收用户列表作为显式参数

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

然后,您可以创建一个唯一的用户列表作为外部类,比如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 方法中实例化这两个类时,您必须提供用户列表(以及将来您可能拥有的实例):

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()));
    ...
}

【讨论】:

  • 当我尝试添加显式参数时,它给了我一个错误“变量用户可能没有被初始化”这两个类。
  • @pyuntae 在每个类中声明只有一个构造函数,并在其中初始化实例变量users,作为构造函数中的第一件事,正如我发布的那样:@ 987654329@(作为“用户”参数的名称)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-05
  • 2013-07-27
  • 2016-06-21
相关资源
最近更新 更多