英文:
JComboBox dropdown stays empty even when I add elements to it
问题
在ChatFrame
类的BuildGUI
方法中,有一个名为dropdown
的JComboBox
,我试图用来填充来自populate
类的ArrayList
。但是每当我运行这个类时,列表成功地获取了我想要添加到JComboBox
的数据,但它却没有添加到下拉框中。
下拉框保持为空。我尝试使用 dropdown.addItem("String");
来添加元素,它可以工作,但为什么当我使用来自另一个类或者使用循环从同一个类的ArrayList
时却不起作用呢?
以下是代码片段:
// Class to manage Client chat Box.
public class ChatClient {
// ...(省略其他代码)
static class ChatFrame extends JFrame implements Observer {
private JTextArea textArea;
private JTextField inputTextField;
private JButton sendButton;
private ChatAccess chatAccess;
private JList<String> list;
public DefaultComboBoxModel<String> mod;
private JScrollPane jscrollpane;
public static JComboBox<String> dropdown;
// ...(省略其他代码)
private void buildGUI() {
for (int j = 0; j < usr.size(); j++) {
array[j] = usr.get(j);
System.out.print("testing" + array[j]);
}
mod = new DefaultComboBoxModel<String>();
list = new javax.swing.JList<>(mod);
list.setBounds(30, 30, 30, 30);
// ...(省略其他代码)
dropdown = new JComboBox<>(array);
dropdown.setBounds(24, 138, 72, 20);
dropdown.setPrototypeDisplayValue("XXXXXXXXXXXXXXXXXXXX");
// ...(省略其他代码)
}
// ...(省略其他代码)
}
static class populate {
// ...(省略其他代码)
public void getarr(String name) {
naam.add(name);
System.out.print("populate" + naam);
dl = new JComboBox<String>();
dl.addItem(name);
// ...(省略其他代码)
}
}
public static void main(String[] args) {
// ...(省略其他代码)
}
}
请注意,上述代码只是你提供的代码片段的翻译,可能并不包含完整的上下文,因此可能会存在一些缺失的信息。
英文:
In the BuildGUI method in class ChatFrame, there is a JCombobox named dropdown which I tried to populate with an arraylist from class populate. But whenever I run the class, list successfully fetches the data I want to add to JComboBox but it doesn't add it to the combobox.
The combobox stays empty. I tried to add element to it by dropdown.addItem("String");
. It worked but why it is not working when I use araylist from another class or same class using for loop?
Here's the code:
// Class to manage Client chat Box.
public class ChatClient {
/** Chat client access */
static class ChatAccess extends Observable {
private Socket socket;
private OutputStream outputStream;
@Override
public void notifyObservers(Object arg) {
super.setChanged();
super.notifyObservers(arg);
}
/** Create socket, and receiving thread */
public void InitSocket(String server, int port) throws IOException {
socket = new Socket(server, port);
outputStream = socket.getOutputStream();
Thread receivingThread = new Thread() {
@Override
public void run() {
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
String line;
while ((line = reader.readLine()) != null)
notifyObservers(line);
} catch (IOException ex) {
notifyObservers(ex);
}
}
};
receivingThread.start();
}
private static final String CRLF = "\r\n"; // newline
/** Send a line of text */
public void send(String text) {
try {
outputStream.write((text + CRLF).getBytes());
outputStream.flush();
} catch (IOException ex) {
notifyObservers(ex);
}
}
/** Close the socket */
public void close() {
try {
socket.close();
} catch (IOException ex) {
notifyObservers(ex);
}
}
}
/** Chat client UI */
static class ChatFrame extends JFrame implements Observer {
private JTextArea textArea;
private JTextField inputTextField;
private JButton sendButton;
private ChatAccess chatAccess;
private JList<String> list;
public DefaultComboBoxModel<String> mod;
private JScrollPane jscrollpane;
public static JComboBox<String> dropdown;
//clientThread ct=new clientThread();
public static ArrayList<String> usr=new ArrayList<String>();
public static String array[]=new String[usr.size()];
public ChatFrame(ChatAccess chatAccess) {
this.chatAccess = chatAccess;
chatAccess.addObserver(this);
buildGUI();
}
/** Builds the user interface */
private void buildGUI() {
for(int j =0;j<usr.size();j++){
array[j] = usr.get(j);
System.out.print("testing"+array[j]);
}
//usr=clientThread.acces();
//System.out.print("test"+usr);
mod = new DefaultComboBoxModel<String>();
list = new javax.swing.JList<>(mod);
list.setBounds(30, 30, 30, 30);
textArea = new JTextArea(20, 50);
textArea.setEditable(false);
textArea.setLineWrap(true);
add(new JScrollPane(textArea), BorderLayout.WEST);
jscrollpane=new JScrollPane();
jscrollpane.setViewportView(list);
add(new JScrollPane(list), BorderLayout.EAST);
Box box = Box.createHorizontalBox();
add(box, BorderLayout.SOUTH);
inputTextField = new JTextField();
dropdown=new JComboBox(array);
dropdown.setBounds(24, 138, 72, 20);
dropdown.setPrototypeDisplayValue("XXXXXXXXXXXXXXXXXXXX");
sendButton = new JButton("Send");
box.add(inputTextField);
box.add(sendButton);
box.add(dropdown);
box.add(populate.dl);
ActionListener sendListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
String str = inputTextField.getText();
if (str != null && str.trim().length() > 0)
chatAccess.send(str);
inputTextField.selectAll();
inputTextField.requestFocus();
inputTextField.setText("");
}
};
inputTextField.addActionListener(sendListener);
sendButton.addActionListener(sendListener);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
chatAccess.close();
}
});
}
/** Updates the UI depending on the Object argument */
public void update(Observable o, Object arg) {
final Object finalArg = arg;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
textArea.append(finalArg.toString());
textArea.append("\n");
}
});
}
}
static class populate{
public static ArrayList<String> naam=new ArrayList<String>();
public static JComboBox<String> dl=new JComboBox<String>();
public void getarr(String name) {
naam.add(name);
System.out.print("populate"+naam);
dl=new JComboBox<String>();
dl.addItem(name);
//ChatFrame.usr.add(name);
//System.out.print("chatframeclass"+ChatFrame.usr);
}
}
public static void main(String[] args) {
String server = args[0];
int port =2222;
ChatAccess access = new ChatAccess();
JFrame frame = new ChatFrame(access);
frame.setTitle("MyChatApp - connected to " + server + ":" + port);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
try {
access.InitSocket(server,port);
} catch (IOException ex) {
System.out.println("Cannot connect to " + server + ":" + port);
ex.printStackTrace();
System.exit(0);
}
}
}
答案1
得分: 2
你的代码问题在于,当你将 array
添加到以下行中的 dropdown
时,array
是空的:
dropdown = new JComboBox(array);
你可以通过在将其添加到 dropdown
之前打印 array
,例如 System.out.println(Arrays.toString(array));
来验证这一点。
以下是将 String
数组添加到 JComboBox<String>
的最小可复现示例:
String[] arr = {"Hello", "Hi", "Bye"};
dropdown = new JComboBox(arr);
在 GUI 中,你会看到 dropdown
已经被 arr[]
的元素填充。如果你将上述代码替换为以下内容:
String[] arr = {};
dropdown = new JComboBox(arr);
你会发现 dropdown
变成了空的。
英文:
The problem with your code is that array
is empty when you are adding it to dropdown
in the following line:
dropdown=new JComboBox(array);
You can verify this by printing array
e.g. System.out.println(Arrays.toString(array));
before adding it to dropdown
.
Given below is the minimal reproducible example of how adding a String
array to JComboBox<String>
works:
String[]arr= {"Hello","Hi","Bye"};
dropdown = new JComboBox(arr);
In the GUI, you will see that dropdown
has been populated with the elements of arr[]
. If you replace the above code as follows
String[]arr= {};
dropdown = new JComboBox(arr);
you will find that dropdown
has become empty.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论