0

I'm trying to open a text file using JFilechooser and put strings in JList. I think all the strings go into the list but I don't know why the strings don't appear on JScrollPane. Is there any problem with grouplayout? i don't know what to change..

import javax.swing.*;

import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import java.util.*;
import java.util.List; 

public class WordFinder extends JFrame implements ActionListener {

    private WordList words = new WordList();

    private JScrollPane scroll;
    private JLabel label;
    private JLabel word;
    private JTextField textArea;
    private JButton button;

    private JMenuBar menuBar;
    private JMenu menu;
    private JMenuItem menuItem, menuItem2;

    private JFileChooser fc;

    private JList list;


    static private final String newline = "\n";

    private int lineCount;



    public WordFinder() {
        super("Word Finder");

        fc = new JFileChooser();
        fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);

        menuBar = new JMenuBar();
        menu = new JMenu("File");
        menuBar.add(menu);

        menuItem = new JMenuItem("Open...");
        menuItem.addActionListener(this);

        menuItem2 = new JMenuItem("Exit");
        menuItem2.addActionListener(this);

        menu.add(menuItem);
        menu.add(menuItem2);
        setJMenuBar(menuBar);

        label = new JLabel("Find: ");

        word = new JLabel(lineCount + " words total");

        textArea = new JTextField();
        textArea.setEditable(true);
        textArea.setPreferredSize(new Dimension(200, 20));


        button = new JButton("Clear");
        button.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        textArea.setText("");
                    }
                });

        scroll = makeListView();
        scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        scroll.setPreferredSize(new Dimension(200, 230));

        GroupLayout layout = new GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setAutoCreateGaps(true);
        layout.setAutoCreateContainerGaps(true);

        layout.setHorizontalGroup(layout.createSequentialGroup()
                .addComponent(label)
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                        .addComponent(textArea)
                        .addComponent(word)
                        .addComponent(scroll))
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                        .addComponent(button)));

        layout.setVerticalGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                        .addComponent(label)
                        .addComponent(textArea)
                        .addComponent(button))
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                        .addComponent(word))
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING))
                        .addComponent(scroll));

        setVisible(true);
        pack();
        // call System.exit() when user closes the window
        setDefaultCloseOperation(EXIT_ON_CLOSE);

    }


    private JScrollPane makeListView() {
    //      String[] labels = {"1", "2", "3"};
    //      list = new JList(labels);

        JScrollPane listScroller = new JScrollPane(list);
        return listScroller;
    }

    private void updateListView(DefaultListModel listModel) {
        list = new JList(listModel);
        scroll = new JScrollPane(list);
    }

    public void actionPerformed(ActionEvent e) {

        DefaultListModel listModel = new DefaultListModel();

        if (e.getSource() == menuItem) {
            int returnVal = fc.showOpenDialog(WordFinder.this);

            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                String fileName = file.getAbsolutePath();

                try {
                    FileReader files = new FileReader(fileName);
                    BufferedReader br = new BufferedReader(files);

                    String str;                 
                    while((str = br.readLine()) != null) {
                        listModel.addElement(str);
                        //System.out.println(str);
                        lineCount++;
                    }
                    System.out.println(lineCount);

                    updateListView(listModel);
                    br.close();
                } catch (Exception ex) {
                    ex.printStackTrace(System.out);
                    System.out.println("can't read file");
                }

                System.out.println("Opening: " + file.getName() + newline);
            }
        } else if (e.getSource() == menuItem2) {
            setVisible(false);
            dispose();
        }
    }


    /**
     * Main method.  Makes and displays a WordFinder window.
     * @param args Command-line arguments.  Ignored.
     */
    public static void main(String[] args) {
        // In general, Swing objects should only be accessed from
        // the event-handling thread -- not from the main thread
        // or other threads you create yourself.  SwingUtilities.invokeLater()
        // is a standard idiom for switching to the event-handling thread.
        SwingUtilities.invokeLater(new Runnable() {
            public void run () {
                // Make and display the WordFinder window.
                new WordFinder();
            }
        });
    }    
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319

1 Answers1

1

When you call makeListView the JList is null as it hasn't been initialized yet...thus, you are basically saying scroll = new JScrollPane(null);...which isn't particularly helpful...

Next, when you call updateListView, you create a new instance of the JList and JScrollPane and do nothing with them...

private void updateListView(DefaultListModel listModel) {
    list = new JList(listModel);
    scroll = new JScrollPane(list);
}

so they will never be displayed on the screen...

To rectify this, you will need to make some modifications...

  1. Create an instance of the JList and assign it to the instance field list, before you create the JScrollPane
  2. Instead of creating new instances of the list and scroll, simply use JList#setModel

You may also like to have a look at Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?

With JList, you affect the size of the JScrollPane through the use of JList#setVisibleRowCount and JList#setPrototypeCellValue

Community
  • 1
  • 1
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366