简体   繁体   中英

How to display the full array contents in SWT styledtext?

I am trying to print the names of the files in the directory but only one of it gets shown. so How to display the full array contents in SWT styledtext ? and furthermore can anyone tell me some online tutorial for SWT?

package gui;
import java.io.*;

import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.custom.StyledText;

public class FileEditor {

    /**
     * Launch the application.
     * @param args
     */
    public static void main(String[] args) {
        Display display = Display.getDefault();
        Shell shell = new Shell();
        shell.setSize(450, 300);
        shell.setText("SWT Application");

        Button btnShow = new Button(shell, SWT.NONE);
        btnShow.addControlListener(new ControlAdapter() {
            @Override
            public void controlMoved(ControlEvent e) {

            }
        });

        StyledText styledText = new StyledText(shell, SWT.BORDER | SWT.FULL_SELECTION);
        styledText.setBounds(154, 36, 256, 191);

        btnShow.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                File newdir = new File("d:\\Softwares");
                String[] list= newdir.list();

                    if(newdir.isDirectory())
                {
                    for(int i=1;i<list.length;i++)
                    {   
                        styledText.setText(list[i]);

                    }
                }

            }
        });

        btnShow.setBounds(23, 146, 75, 25);
        btnShow.setText("Show");    

        shell.open();
        shell.layout();
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }
    }
}

The StyledText setText method replaces all the existing text with the new text so you are only getting the last item.

Instead you can use the append method to add to the end of the control, so something like:

for (String item : list)
 {   
   styledText.append(item + '\n');  // Add item with new line between entries
 }

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