java - 如何使用 ActionListener 中使用的变量?

标签 java swing arraylist jtable

正如您在图片中看到的,我正在设置一个表格,显示特定路径中的所有文件(稍后我将仅实现 pdf 文件的过滤器)。首先,所有文件都会同时显示,但我想在表的构建过程中查看路径的每个文件。所以我把它改成了数组列表,但是有两个错误我真的无法解决......

希望你能帮助我;-) enter image description here

class FileModel extends AbstractTableModel implements FilenameFilter {   

String titles[] = new String[] { "Path" };
Class<?> types[] = new Class[] { String.class, String.class };
private List<Object[]> data = new ArrayList<>();

public FileModel() {
    this("C:\\");
}

public FileModel(String dir) {
    File pwd = new File(dir);
    setFileStats(pwd);
}

// Implement the methods of the TableModel interface we're interested
// in. Only getRowCount(), getColumnCount() and getValueAt() are
// required. The other methods tailor the look of the table.
@Override
public int getRowCount() {
    return this.data.size();
}

@Override
public int getColumnCount() {
    return this.titles.length;
}

@Override
public String getColumnName(int c) {
    return this.titles[c];
}

@Override
public Class<?> getColumnClass(int c) {
    return this.types[c];
}

@Override
public Object getValueAt(int r, int c) {
    return this.data.get(r)[c];
}

// Our own method for setting/changing the current directory
// being displayed. This method fills the data set with file info
// from the given directory. It also fires an update event so this
// method could also be called after the table is on display.
public void setFileStats(File dir) {
    System.out.println("SET MY DIR " + dir);

    this.data = new ArrayList<>();

    this.fireTableDataChanged();

    String files[] = dir.list();

    this.data = new Object[files.length][this.titles.length];   **// Here error #1**

    for (int i = 0; i < files.length; i++) {
        File tmp = new File(files[i]);

        this.data[i][0] = tmp.getAbsolutePath();                **// Here error #2**
    }        
    this.fireTableDataChanged();
}

@Override
public boolean accept(File dir, String name) {
    // TODO Auto-generated method stub
    return false;
}
}

这是 JFrame 窗口的代码:

public class FileFrame extends JFrame {

protected FileModel fileModel = new FileModel();
{
    this.setSize(500, 400);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setLocationRelativeTo(null);
    JTable FileTable = new JTable(this.fileModel);
    TableRowSorter<TableModel> TableRowSorter = new TableRowSorter<TableModel>(this.fileModel);
    FileTable.setRowSorter(TableRowSorter);
    FileTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
    FileTable.setColumnSelectionAllowed(true);
    FileTable.setDefaultRenderer(Number.class, new BigRenderer(1000));
    JScrollPane JScrollPane = new JScrollPane(FileTable);
    getContentPane().add(JScrollPane, BorderLayout.CENTER);
}

public static void main(String args[]) {
    final FileFrame FileFrame = new FileFrame();

    // Create menubar
    JMenuBar menubar = new JMenuBar();
    // Create JMenu object
    JMenu menu = new JMenu("File");
    // Create JMenuItem object
    final JMenuItem openItem = new JMenuItem("Open");
    JMenuItem exititem = new JMenuItem("Exit");
    // Add JMenuItem to JMenu
    menu.add(openItem);
    menu.add(exititem);
    // Add menu to menubar
    menubar.add(menu);
    // Add menubar to dialog
    FileFrame.setJMenuBar(menubar);
    // Show dialog
    FileFrame.setVisible(true);

    // Integrate ActionListener as anonymous class
    openItem.addActionListener(new java.awt.event.ActionListener() {
        public File savedPath;
        public final JFileChooser FileChooser = new JFileChooser("C:\\");

        // Initialize actionPerformed
        @Override
        public void actionPerformed(ActionEvent e) {
            // Generate choose file
            this.FileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            this.FileChooser.setDialogTitle("Selection of pdf directory");
            this.FileChooser.setAcceptAllFileFilterUsed(false);
            // Set the text
            this.FileChooser.setApproveButtonText("Open directory");
            // Set the tool tip
            this.FileChooser.setApproveButtonToolTipText("Select pdf directory ");
            if (this.savedPath != null)
                this.FileChooser.setCurrentDirectory(this.savedPath);
            int returnVal = this.FileChooser.showOpenDialog(openItem);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                this.savedPath = this.FileChooser.getSelectedFile();
                FileFrame.fileModel.setFileStats(this.savedPath);
            }
        }
    });

    // Integrate ActionListener as anonymous class
    exititem.addActionListener(new java.awt.event.ActionListener() {
        // Initialize actionPerformed
        @Override
        public void actionPerformed(ActionEvent e) {
            // Close program
            System.exit(0);
        }
    });
}
}

最佳答案

问题是您正在尝试访问data就好像它是一个数组

private List<Object[]> data = new ArrayList<>();
...
this.data = new Object[files.length][this.titles.length]; 
this.data[i][0] = tmp.getAbsolutePath(); 

但是data实际上是一个List<Object[]>

所以你可能想做

//data.add(new Object[files.length][this.titles.length]);
data.add(new Object[files.length]); // can only be one dimensional

 and 

((Object[])data.get(i))[0] = tmp.getAbsolutePath(); 

相反

查看有关如何使用 Lists 的更多信息在The List Interface

<小时/>

更新

将您的模型代码更改为此

String files[] = dir.list();

for (int i = 0; i < files.length; i++) {
    File tmp = new File(files[i]);
    data.add(new Object[] { tmp.getAbsolutePath()}) ;           
}

您所需要做的就是添加新的 Object[]仅包含文件路径的列表(内部),因为这似乎就是您所需要的。之前不要添加一个。

关于java - 如何使用 ActionListener 中使用的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25501746/

相关文章:

java - 在同一帧中使用 2 个面板

java - 在 arraylist 中查找重复值

Java GUI : Image will be overwritten, 路径相同 -> 在框架中显示它(图像仍然相同)

java - 如何将原始 XML 文本添加到 SOAPBody 元素

java - 从数据库填充 JTree

java.math.BigDecimal 到 Avro .avdl 文件

java - 如何在 Java 中将 JButton 转换为 JToggleButton?

java - 您可以对 Object 实例中的 ArrayList 使用 remove.(this) 吗?

java - 如何以所需格式打印数组列表?

java - 设计输出多个文件(包括二进制输出)的 Apache Beam 转换的理想方法是什么?