Yatrik Amrutiya
Yatrik Amrutiya

Reputation: 47

JComboBox dropdown stays empty even when I add elements to it

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

Upvotes: 1

Views: 99

Answers (1)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79105

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.

Upvotes: 2

Related Questions