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

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

JComboBox dropdown stays empty even when I add elements to it

问题

ChatFrame类的BuildGUI方法中,有一个名为dropdownJComboBox,我试图用来填充来自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(&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:

// 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 = &quot;\r\n&quot;; // 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&lt;String&gt; list;
public DefaultComboBoxModel&lt;String&gt; mod;
private JScrollPane jscrollpane;
public static JComboBox&lt;String&gt; dropdown;
//clientThread ct=new clientThread();
public static  ArrayList&lt;String&gt; usr=new ArrayList&lt;String&gt;();
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&lt;usr.size();j++){
array[j] = usr.get(j);
System.out.print(&quot;testing&quot;+array[j]);
}
//usr=clientThread.acces();
//System.out.print(&quot;test&quot;+usr);
mod = new DefaultComboBoxModel&lt;String&gt;();
list = new javax.swing.JList&lt;&gt;(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(&quot;XXXXXXXXXXXXXXXXXXXX&quot;);
sendButton = new JButton(&quot;Send&quot;);
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 &amp;&amp; str.trim().length() &gt; 0)
chatAccess.send(str);
inputTextField.selectAll();
inputTextField.requestFocus();
inputTextField.setText(&quot;&quot;);
}
};
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(&quot;\n&quot;);
}
});
}
}
static class populate{   
public static ArrayList&lt;String&gt; naam=new ArrayList&lt;String&gt;();
public static JComboBox&lt;String&gt; dl=new JComboBox&lt;String&gt;();
public void getarr(String name) {
naam.add(name);
System.out.print(&quot;populate&quot;+naam);
dl=new JComboBox&lt;String&gt;();
dl.addItem(name);
//ChatFrame.usr.add(name);         
//System.out.print(&quot;chatframeclass&quot;+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(&quot;MyChatApp - connected to &quot; + server + &quot;:&quot; + 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(&quot;Cannot connect to &quot; + server + &quot;:&quot; + 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&lt;String&gt; works:

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

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:

确定