ArrayList, JList, DefaultListModel, adding elements, displaying them etc

203 Views Asked by At

How can I change the output from JTextArea to JList? The reason: deleting elements, sorting them and editing them is easier. If I simply change the JTextArea to JList I have the problem of printing the ArrayList in the output area.

This is my code (I cut out certain (probably irrelevant) parts):

package personFiles;

import java.awt.*;
import java.util.List;
import java.awt.event.*;
import java.util.ArrayList;

import javax.swing.*;
import javax.swing.event.*;


@SuppressWarnings("serial")
public class Osoblje extends JFrame {
    private JTextArea outputJTA = new JTextArea("");
    private JScrollPane outputJTAScrollPane = new JScrollPane(outputJTA);

    List<Person> personList = new ArrayList<>();

    public Osoblje(String title) { 
        // Frame-Initialisierung
        super(title);
        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        int frameWidth = 310; 
        int frameHeight = 269;
        setSize(frameWidth, frameHeight);
        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
        int x = (d.width - getSize().width) / 2;
        int y = (d.height - getSize().height) / 2;
        setLocation(x, y);
        setResizable(false);
        Container cp = getContentPane();
        cp.setLayout(null);
        // Anfang Komponenten

        outputJTAScrollPane.setBounds(8, 8, 129, 217);
        cp.add(outputJTAScrollPane);

        setVisible(true);
    } // end of public Osoblje

    // Anfang Methoden

    public static void main(String[] args) {
        new Osoblje("Osoblje");
    } // end of main

    public void newPersonJB_ActionPerformed(ActionEvent evt) {
        personList.add(new Person(idJTF.getText(), nameJTF.getText(), surnameJTF.getText(), ageJTF.getText(), genderJTF.getText())); //create new person
    } // end of newPersonJB_ActionPerformed

    public void pokaziJB_ActionPerformed(ActionEvent evt) {
        outputJTA.setText(personList + "\n"); //display personList
    } // end of pokaziJB_ActionPerformed

}
2

There are 2 best solutions below

0
freedev On

Try switching from List<Person> onto java.util.List<Person>.

Or better, fix your imports.

0
J-Alex On

You're using java.awt.List instead of java.util.List.

Solution:

java.util.List<Main> m = new ArrayList<Main>();

Or do more strict imports like:

import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.Container;

Instead of:

import java.awt.*;