-1

我正在尝试传递由类之间的 JFileChooser 生成的字符串。我程序的另一部分工作正常。如果我在本地将文件路径定义为字符串,它运行得很好。

我需要实现这样的代码,这在这个简单的示例中运行良好,但我无法使用下面进一步发布的代码。

public class A {
private static final String x = "This is X";
public static String getX() { return x;}
}

public class B {
public static void main(String args[]) {
String x = A.get();
System.out.println("x = " + x);}
}

我的完整代码:

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;

public class FileChooser extends JFrame {


    public FileChooser() {
        super("File Chooser Test Frame");
        setSize(350, 200);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        Container c = getContentPane();
        c.setLayout(new FlowLayout());

        JButton openButton = new JButton("Open");
        JButton goButton = new JButton("Go");
        final JLabel statusbar = new JLabel(
                "Output of your selection will go here");

        openButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                JFileChooser chooser = new JFileChooser();
                chooser.setMultiSelectionEnabled(true);
                int option = chooser.showOpenDialog(FileChooser.this);
                if (option == JFileChooser.APPROVE_OPTION) {
                    File[] sf = chooser.getSelectedFiles();
                    String filelist = "nothing";
                    if (sf.length > 0)
                        filelist = sf[0].getName();
                    for (int i = 1; i < sf.length; i++) {
                        filelist += ", " + sf[i].getName();
                    }
                    statusbar.setText(filelist);
                    String thefilename = filelist;

                } else {
                    statusbar.setText("You canceled.");
                }
            }
        });

        goButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent ae) {

                String filepath = statusbar.getText();
                System.out.println(filepath);
            }
        });

        c.add(openButton);
        c.add(goButton);
        c.add(statusbar);
    }

    public static void main(String args[]) {
        FileChooser sfc = new FileChooser();
        sfc.setVisible(true);
    }
}
4

1 回答 1

4

如果您需要String filelist在另一个类中,请将其设为实例变量并添加一个 getter 方法。

public class FileChooser extends JFrame {
  private String filelist;
  // ... initialize string in constructor ..
  public String getFilelist() {
    return filelist;
  }
}
于 2013-10-25T18:10:02.927 回答