JComboBox下拉菜单即使我添加了元素也保持为空。

huangapple go评论110阅读模式
英文:

JComboBox dropdown stays empty even when I add elements to it

问题

ChatFrame类的BuildGUI方法中,有一个名为dropdownJComboBox,我试图用来填充来自populate类的ArrayList。但是每当我运行这个类时,列表成功地获取了我想要添加到JComboBox的数据,但它却没有添加到下拉框中。

下拉框保持为空。我尝试使用 dropdown.addItem("String"); 来添加元素,它可以工作,但为什么当我使用来自另一个类或者使用循环从同一个类的ArrayList时却不起作用呢?

以下是代码片段:

  1. // Class to manage Client chat Box.
  2. public class ChatClient {
  3. // ...(省略其他代码)
  4. static class ChatFrame extends JFrame implements Observer {
  5. private JTextArea textArea;
  6. private JTextField inputTextField;
  7. private JButton sendButton;
  8. private ChatAccess chatAccess;
  9. private JList<String> list;
  10. public DefaultComboBoxModel<String> mod;
  11. private JScrollPane jscrollpane;
  12. public static JComboBox<String> dropdown;
  13. // ...(省略其他代码)
  14. private void buildGUI() {
  15. for (int j = 0; j < usr.size(); j++) {
  16. array[j] = usr.get(j);
  17. System.out.print("testing" + array[j]);
  18. }
  19. mod = new DefaultComboBoxModel<String>();
  20. list = new javax.swing.JList<>(mod);
  21. list.setBounds(30, 30, 30, 30);
  22. // ...(省略其他代码)
  23. dropdown = new JComboBox<>(array);
  24. dropdown.setBounds(24, 138, 72, 20);
  25. dropdown.setPrototypeDisplayValue("XXXXXXXXXXXXXXXXXXXX");
  26. // ...(省略其他代码)
  27. }
  28. // ...(省略其他代码)
  29. }
  30. static class populate {
  31. // ...(省略其他代码)
  32. public void getarr(String name) {
  33. naam.add(name);
  34. System.out.print("populate" + naam);
  35. dl = new JComboBox<String>();
  36. dl.addItem(name);
  37. // ...(省略其他代码)
  38. }
  39. }
  40. public static void main(String[] args) {
  41. // ...(省略其他代码)
  42. }
  43. }

请注意,上述代码只是你提供的代码片段的翻译,可能并不包含完整的上下文,因此可能会存在一些缺失的信息。

英文:

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(&quot;String&quot;);. 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:

  1. // Class to manage Client chat Box.
  2. public class ChatClient {
  3. /** Chat client access */
  4. static class ChatAccess extends Observable {
  5. private Socket socket;
  6. private OutputStream outputStream;
  7. @Override
  8. public void notifyObservers(Object arg) {
  9. super.setChanged();
  10. super.notifyObservers(arg);
  11. }
  12. /** Create socket, and receiving thread */
  13. public void InitSocket(String server, int port) throws IOException {
  14. socket = new Socket(server, port);
  15. outputStream = socket.getOutputStream();
  16. Thread receivingThread = new Thread() {
  17. @Override
  18. public void run() {
  19. try {
  20. BufferedReader reader = new BufferedReader(
  21. new InputStreamReader(socket.getInputStream()));
  22. String line;
  23. while ((line = reader.readLine()) != null)
  24. notifyObservers(line);
  25. } catch (IOException ex) {
  26. notifyObservers(ex);
  27. }
  28. }
  29. };
  30. receivingThread.start();
  31. }
  32. private static final String CRLF = &quot;\r\n&quot;; // newline
  33. /** Send a line of text */
  34. public void send(String text) {
  35. try {
  36. outputStream.write((text + CRLF).getBytes());
  37. outputStream.flush();
  38. } catch (IOException ex) {
  39. notifyObservers(ex);
  40. }
  41. }
  42. /** Close the socket */
  43. public void close() {
  44. try {
  45. socket.close();
  46. } catch (IOException ex) {
  47. notifyObservers(ex);
  48. }
  49. }
  50. }
  51. /** Chat client UI */
  52. static class ChatFrame extends JFrame implements Observer {
  53. private JTextArea textArea;
  54. private JTextField inputTextField;
  55. private JButton sendButton;
  56. private ChatAccess chatAccess;
  57. private JList&lt;String&gt; list;
  58. public DefaultComboBoxModel&lt;String&gt; mod;
  59. private JScrollPane jscrollpane;
  60. public static JComboBox&lt;String&gt; dropdown;
  61. //clientThread ct=new clientThread();
  62. public static ArrayList&lt;String&gt; usr=new ArrayList&lt;String&gt;();
  63. public static String array[]=new String[usr.size()];
  64. public ChatFrame(ChatAccess chatAccess) {
  65. this.chatAccess = chatAccess;
  66. chatAccess.addObserver(this);
  67. buildGUI();
  68. }
  69. /** Builds the user interface */
  70. private void buildGUI() {
  71. for(int j =0;j&lt;usr.size();j++){
  72. array[j] = usr.get(j);
  73. System.out.print(&quot;testing&quot;+array[j]);
  74. }
  75. //usr=clientThread.acces();
  76. //System.out.print(&quot;test&quot;+usr);
  77. mod = new DefaultComboBoxModel&lt;String&gt;();
  78. list = new javax.swing.JList&lt;&gt;(mod);
  79. list.setBounds(30, 30, 30, 30);
  80. textArea = new JTextArea(20, 50);
  81. textArea.setEditable(false);
  82. textArea.setLineWrap(true);
  83. add(new JScrollPane(textArea), BorderLayout.WEST);
  84. jscrollpane=new JScrollPane();
  85. jscrollpane.setViewportView(list);
  86. add(new JScrollPane(list), BorderLayout.EAST);
  87. Box box = Box.createHorizontalBox();
  88. add(box, BorderLayout.SOUTH);
  89. inputTextField = new JTextField();
  90. dropdown=new JComboBox(array);
  91. dropdown.setBounds(24, 138, 72, 20);
  92. dropdown.setPrototypeDisplayValue(&quot;XXXXXXXXXXXXXXXXXXXX&quot;);
  93. sendButton = new JButton(&quot;Send&quot;);
  94. box.add(inputTextField);
  95. box.add(sendButton);
  96. box.add(dropdown);
  97. box.add(populate.dl);
  98. ActionListener sendListener = new ActionListener() {
  99. public void actionPerformed(ActionEvent e) {
  100. String str = inputTextField.getText();
  101. if (str != null &amp;&amp; str.trim().length() &gt; 0)
  102. chatAccess.send(str);
  103. inputTextField.selectAll();
  104. inputTextField.requestFocus();
  105. inputTextField.setText(&quot;&quot;);
  106. }
  107. };
  108. inputTextField.addActionListener(sendListener);
  109. sendButton.addActionListener(sendListener);
  110. this.addWindowListener(new WindowAdapter() {
  111. @Override
  112. public void windowClosing(WindowEvent e) {
  113. chatAccess.close();
  114. }
  115. });
  116. }
  117. /** Updates the UI depending on the Object argument */
  118. public void update(Observable o, Object arg) {
  119. final Object finalArg = arg;
  120. SwingUtilities.invokeLater(new Runnable() {
  121. public void run() {
  122. textArea.append(finalArg.toString());
  123. textArea.append(&quot;\n&quot;);
  124. }
  125. });
  126. }
  127. }
  128. static class populate{
  129. public static ArrayList&lt;String&gt; naam=new ArrayList&lt;String&gt;();
  130. public static JComboBox&lt;String&gt; dl=new JComboBox&lt;String&gt;();
  131. public void getarr(String name) {
  132. naam.add(name);
  133. System.out.print(&quot;populate&quot;+naam);
  134. dl=new JComboBox&lt;String&gt;();
  135. dl.addItem(name);
  136. //ChatFrame.usr.add(name);
  137. //System.out.print(&quot;chatframeclass&quot;+ChatFrame.usr);
  138. }
  139. }
  140. public static void main(String[] args) {
  141. String server = args[0];
  142. int port =2222;
  143. ChatAccess access = new ChatAccess();
  144. JFrame frame = new ChatFrame(access);
  145. frame.setTitle(&quot;MyChatApp - connected to &quot; + server + &quot;:&quot; + port);
  146. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  147. frame.pack();
  148. frame.setLocationRelativeTo(null);
  149. frame.setResizable(false);
  150. frame.setVisible(true);
  151. try {
  152. access.InitSocket(server,port);
  153. } catch (IOException ex) {
  154. System.out.println(&quot;Cannot connect to &quot; + server + &quot;:&quot; + port);
  155. ex.printStackTrace();
  156. System.exit(0);
  157. }
  158. }
  159. }

答案1

得分: 2

你的代码问题在于,当你将 array 添加到以下行中的 dropdown 时,array 是空的:

  1. dropdown = new JComboBox(array);

你可以通过在将其添加到 dropdown 之前打印 array,例如 System.out.println(Arrays.toString(array)); 来验证这一点。

以下是将 String 数组添加到 JComboBox<String> 的最小可复现示例:

  1. String[] arr = {"Hello", "Hi", "Bye"};
  2. dropdown = new JComboBox(arr);

在 GUI 中,你会看到 dropdown 已经被 arr[] 的元素填充。如果你将上述代码替换为以下内容:

  1. String[] arr = {};
  2. 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:

  1. 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&lt;String&gt; works:

  1. String[]arr= {&quot;Hello&quot;,&quot;Hi&quot;,&quot;Bye&quot;};
  2. 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

  1. String[]arr= {};
  2. dropdown = new JComboBox(arr);

you will find that dropdown has become empty.

huangapple
  • 本文由 发表于 2020年5月3日 17:37:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/61572360.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定