首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JList没有出现在JScrollPane上

JList没有出现在JScrollPane上
EN

Stack Overflow用户
提问于 2014-10-17 09:04:36
回答 1查看 728关注 0票数 0

我试图使用JFilechooser打开一个文本文件,并将字符串放在JList中。我认为所有的字符串都会出现在列表中,但我不知道为什么这些字符串没有出现在JScrollPane上。团体赛有什么问题吗?我不知道该换什么..。

代码语言:javascript
复制
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();
            }
        });
    }    
}
EN

回答 1

Stack Overflow用户

发布于 2014-10-17 09:17:08

当您调用makeListView时,JListnull,因为它还没有初始化yet...thus,您基本上是说scroll = new JScrollPane(null);...which并不特别有用.

接下来,当您调用updateListView时,您将创建JListJScrollPane的一个新实例,并且对它们不做任何操作.

代码语言:javascript
复制
private void updateListView(DefaultListModel listModel) {
    list = new JList(listModel);
    scroll = new JScrollPane(list);
}

所以它们永远不会显示在屏幕上..。

为了纠正这个问题,你需要做一些修改.

  1. 在创建JList之前,创建一个JScrollPane实例并将其分配给实例字段list
  2. 不要创建listscroll的新实例,只需使用JList#setModel

您可能还想看看Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?

使用JList,可以通过使用JList#setVisibleRowCountJList#setPrototypeCellValue来影响JScrollPane的大小。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26421548

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档