简体   繁体   中英

Displaying ArrayList<String> in JTextArea

So when a button is clicked my method returns an arraylist of strings, I'm trying to display the strings line by line in a JtextArea. This is my first time playing around with GUIs in eclipse, but so far I'm at

JButton btnNewButton_1 = new JButton("Coordinate Anomalies");
btnNewButton_1.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
        ArrayList<String> anomalies = vessels.coordinateAnomaly(); 
    }
});
btnNewButton_1.setBounds(10, 45, 172, 23);
frame.getContentPane().add(btnNewButton_1);

JTextArea textArea = new JTextArea();
textArea.setBounds(10, 79, 172, 339);
frame.getContentPane().add(textArea);

I was thinking that I could potentially do

JButton btnNewButton_1 = new JButton("Coordinate Anomalies");
btnNewButton_1.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
        ArrayList<String> anomalies = vessels.coordinateAnomaly(); 
        JTextArea textArea = new JTextArea();
        textArea.setText(anomalies);
        textArea.setBounds(10, 79, 172, 339);
        frame.getContentPane().add(textArea);
    }
});

This definitely does not work, and if it did would display strings in ArrayList formatting, So I should have a loop some wheres, but I'm a little lost.
Any help would be awesome.

Try this one:

for(String a : anomalies){
   textArea.append(a + "\n");
}

instead of:

textArea.setText(anomalies);

when adding JTextArea to JFrame just add scroll pane in it like this

add(new JScrollPane(textarea));

Ended up following m.cekiera advice

  for(String a : anomalies){
                        if(a.equals(anomalies.get(anomalies.size()-1))){
                            textArea_1.append(a);
                        }else{
                           textArea_1.append(a + "\n");
                        }
                    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM