简体   繁体   中英

Create a .txt file populating it from a JList

Is it possible to write on a .txt file the content of a JList? If it's possible, can you give me a sample? Thanks

A JList is not a data structure, but a displaying component.

You should have the contents in a ListModel, and if the elements of this model are simple Strings (or something easily convertible to Strings, you could of course write it in a text file.

public static void exportList(ListModel model, File f) throws IOException {
    PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(f), "UTF-8"));
    try {
        int len = model.getSize();
        for (int i = 0; i < len; i++) {
            pw.println(model.getElementAt(i).toString());
        }
    } finally {
        pw.close();
    }
}

A list has a model and the model has data. You just have to write that data to a file:

import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.event.*;
import java.io.PrintStream;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
class ListDemo {
    public static void main( String ... args ) throws FileNotFoundException {
        // The data
        final Object [] data = {"A","B","C"};


        // Put it in the frame 
        JFrame frame = new JFrame();
        frame.add( new JScrollPane( new JList( data )));
        // write to a file  
        final PrintStream out = new PrintStream(new FileOutputStream("datos.txt"));
        frame.add( new JButton("Print"){{
            addActionListener( new ActionListener() {
                public void actionPerformed( ActionEvent e ) {
                    for( Object d : data ) { 
                            out.println( d );
                    }
                }
            });
        }}, BorderLayout.SOUTH);
        frame.pack();
        frame.setVisible( true );
    }
}

This is only a sample. You have to create a list model of our own and populate it with your own data.

Also I'm not closing the file here.

To know more about JList read here:

http://download.oracle.com/javase/tutorial/uiswing/components/list.html

To know more about stream here:

http://download.oracle.com/javase/tutorial/essential/io/charstreams.html

Is this a homework question ?
anyway yes it is possible from the the JList you can use the following method although i am sure its not the best way to do it it should work
where list is a JList

list.setSelectedIndex(int index); // sets one selection
list.getSelectedValue(); //returns Object

or

list.setSelectedIndices(int [] indices); // sets multiple selections
list.getSelectedValues(); //returns all selected values in an Object []

for writing/reading/deleting/created read this

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