我寫了一個簡單的GUI程序來搜索讀寫文本文件。如何讓全局選擇文件?
package MyGUIStuff;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.Scanner;
public class multiWinDemo {
public static void main(String[] args) {
JLabel lbl = new JLabel ("File Name:");
JTextField file = new JTextField (10);
file.setEditable(false);
JButton browse = new JButton ("Browse");
browse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ext) {
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
file.setText(selectedFile.getName());
}
}
});
JButton search = new JButton ("Search");
JButton write = new JButton ("Write");
JButton read = new JButton ("Read");
read.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ext) {
BufferedReader br = null;
try {
String currentLine;
br = new BufferedReader(new FileReader(selectedFile.getName()));
while ((currentLine=br.readLine()) != null) {
System.out.println(currentLine);
}
}catch (IOException e){
e.printStackTrace();
}finally {
try {
if (br != null) br.close();
}catch (IOException ex){
ex.printStackTrace();
}
}
}
});
JButton exit = new JButton ("Exit");
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ext) {
System.exit(0);
}
});
JPanel blank = new JPanel();
JPanel first = new JPanel();
first.setLayout(new GridLayout(3,0,5,5));
first.add(lbl);
first.add(file);
first.add(browse);
first.add(write);
first.add(search);
first.add(read);
first.add(blank);
first.add(exit);
JPanel rPanel = new JPanel();
JFrame multiWin = new JFrame ("MultiWin");
multiWin.setSize(300,130);
multiWin.setLayout(new CardLayout());
multiWin.setLocationRelativeTo(null);
multiWin.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
multiWin.setVisible(true);
multiWin.add(first);
}
}
我的問題是我該如何使行19-22全球選擇的文件?這樣我的整個程序就可以使用它?
任何幫助,非常感謝。謝謝! :D
全局通常是一個壞主意。你應該把它傳遞給需要它的類。 – SLaks
你是什麼意思傳遞它? – shrillhook