-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);
}
}
該行'String thefilename = filelist;'是不必要的。但是對於其他問題:究竟哪些方法無效? –
我試圖從同一個項目中的另一個.java文件訪問字符串的文件名,但無法通過我找到的任何技術調用它。我將編輯原始問題以刪除多餘的行String thefilename = filelist; –
啊,好的。我會寫一個答案。 –