在类之间传递变量

时间:2013-10-25 17:57:50

标签: java variables

我正在尝试传递一个由类之间的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);
    }
}

1 个答案:

答案 0 :(得分:4)

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

public class FileChooser extends JFrame {
  private String filelist;
  // ... initialize string in constructor ..
  public String getFilelist() {
    return filelist;
  }
}
相关问题