简体   繁体   English

从通读按钮的文本文件中填充一个jlist

[英]Populate a jlist from text file read through button

在此处输入图片说明

Code: 码:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         

JFileChooser fileChooser = new JFileChooser();
//fileChooser.setCurrentDirectory(new     File(System.getProperty("user.home")));
int result = fileChooser.showOpenDialog(this);
if (result == JFileChooser.APPROVE_OPTION) 

{
File selectedFile = fileChooser.getSelectedFile();
System.out.println("Selected file: " + selectedFile.getAbsolutePath());
DefaultListModel lista = new DefaultListModel();
JList jList1 = new JList();

try {
        FileReader archivo = new     FileReader(selectedFile.getAbsolutePath());
        BufferedReader lector = new BufferedReader(archivo);
        String texto = null;
        while ((texto = lector.readLine()) != null) {
            lista.addElement(texto);
            //System.out.println("Lista:"+lista);
            //System.out.println(texto);
        }

        jList1.setModel(lista);
        System.out.println("jList1:"+jList1);

    } 

catch (FileNotFoundException e) {
        e.printStackTrace();
    } 

catch (IOException e) {
        e.printStackTrace();
    } 

}    

}                                        

I am trying to Populate a jlist from text file read through Read_file button 我正在尝试从通过Read_file按钮读取的文本文件中填充一个jlist

I am able to fetch the file path and the contents of the file correctly which I validated with a print statement, but still my jlist remains empty. 我可以正确获取文件路径和文件内容,这些内容已通过print语句验证,但我的jlist仍然为空。 In the design, I checked the variable name of the jlist, both matches what I have used in the code. 在设计中,我检查了jlist的变量名,两者均与我在代码中使用的名称匹配。

Please suggest me on the mistake. 请就错误建议我。

From what i see you create a new JList each time you hit the button. 从我看来,每当您按下按钮时,您就会创建一个新的JList You do properly fill the DefaultListModel but you assigned to some jList not to the one you have on your UI. 您确实正确地填充了DefaultListModel但是您分配给某个jList而不是您的UI上的jList。

Just clear the line : 只需清除界线:

JList jList1 = new JList(); 

then repaint and revalidate it's container after setModel 然后在setModel之后repaintrevalidate它的容器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM