Search code examples
user-interfacearraylisttextareajoptionpane

Displaying arraylist with Jtextarea in a single iteration?


I'm having trouble displaying and array list the way I want it. Instead of the full list of strings being displayed, one String is displayed at a time with each dialog box. Once I heit okay on the dialog box, the next item in the array pops up in a new one until it goes through all of them. I want all of them to pop up in one dialog box. Any help is appreciated.

b3.addActionListener(new ActionListener() {
        /**
         * Displays the arraylist.
         */
        public void actionPerformed(ActionEvent e) {

            ImageIcon icon = new ImageIcon(Window.class.getResource("/car.png"));
            for(int i=0; i < cars.size(); i++) {
                JTextArea textArea = new JTextArea(cars.get(i) + '\n');
                JScrollPane scrollPane = new JScrollPane(textArea);  
                textArea.setLineWrap(true);  
                textArea.setWrapStyleWord(true); 
                scrollPane.setPreferredSize(new Dimension( 150, 200 ));
                JOptionPane.showMessageDialog(null, scrollPane);

Solution

  • You have the creation of your text areas and other widgets inside the for-loop. You want to create these outside the loop and then set the contents of the text area to a string representation of your ArrayList.

    Try this:

    ImageIcon icon = new ImageIcon(Window.class.getResource("/car.png"));
    StringBuilder sb = new StringBuilder(); // this will be the contents of your list
    
    for(int i=0; i < cars.size(); i++) {
        sb.append(cars.get(i) + "\n"); // add each element to the string   
    }
    
    // create the text area widgets
    JTextArea textArea = new JTextArea(sb.toString());  // add the string you built
    JScrollPane scrollPane = new JScrollPane(textArea);  
    textArea.setLineWrap(true);  
    textArea.setWrapStyleWord(true); 
    scrollPane.setPreferredSize(new Dimension( 150, 200 ));
    JOptionPane.showMessageDialog(null, scrollPane);