[英]How to get ArrayList from another class to show up inside a JComboBox?
我正在嘗試構建程序, 但無法從另一個類中獲取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.
這是我不完整的代碼,由於無法找到我的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的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";
// }
}
首先,您最好從歷史記錄主目錄調用用戶管理器模塊,例如
JFrame frame = new JFrame ("UserHistory");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new UserHistory());
frame.pack();
frame.setVisible (true);
manageUsers();
這將啟動兩個JPanels,因此您可以同時管理用戶和觀看歷史記錄。
另外,
// 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) {
}
});
通過這兩項更正,您將能夠在組合框中列出用戶名,並且用戶列表的動態更改將反映到該框中的列表中。
干杯。
讓我在這里上傳整個源代碼
User.java-源代碼隨即出現(我不知道為什么它們不符合要求。)
打包用戶選擇列表;
公共類用戶{
私有字符串userName; private int積分= 0;
public User(String userName){this.userName = userName; }
public User(){userName =“”; }
公共無效setUserName(String userName){this.userName = userName;
}
public String getUserName(){return userName; }
公共無效addPoints(int chorePoints){點+ = chorePoints; }}
ManageUsersGUI.java -緊隨其后的是源代碼(我不知道為什么它們還是再次出現。)
打包用戶選擇列表;
導入javax.swing。 ; 導入java.awt。 ; 導入java.awt.event。*; 導入java.util.ArrayList; 導入javax.swing.JCheckBox;
公共類ManageUsersGUI擴展了JPanel {公共靜態ArrayList用戶=新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); }
}
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 {private JLabel jcomp1; 私人JComboBox userList; 私人JLabel jcomp3; 私有JTextField selectedUser; 私人JLabel jcomp5; 私人JTextField pointsEarned; 私人JLabel jcomp7; 私人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(); }
}
我建議您在類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;
...
}
}
然后,您可以創建一個唯一的用戶列表作為外部類,例如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()));
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.