我做一个程序来计算DAG的关键路径方法,程序逻辑是完美的,但是我在尝试集成图形用户界面时遇到了问题。该接口允许我通过 JFileChooser 选择程序的输入文件,但我不知道如何将该参数传递给位于主操作中的函数"readfile"。
赫雷斯的虚空主代码:
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
JFrameConFondo jf = new EjemploJFrameConFondo();
jf.setLocationRelativeTo(null);
jf.setTitle("CPM");
jf.setVisible(true);
readfile(route);
////I need to pass a filename to the program which calculate the critical path,
}
});
}
}
这是函数"readfile"的代码:
public static void leer_archivo(String fileName){
try{
File archivo=new File(fileName);
FileReader fr= new FileReader(archivo);
BufferedReader br= new BufferedReader(fr);
String linea;
linea=br.readLine();
c=Integer.parseInt(linea);
for(int i=0;i<c;i++){
CrearCaso(br, i+1);
}
}catch(Exception e){
}
}
我正在为文件选择界面上的按钮执行此操作,我希望该文件的名称可以以某种方式发送到 void main,以便能够使用"readfile"功能:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
JFileChooser filechooser = new JFileChooser();
int option = filechooser.showOpenDialog (this);
if (option==JFileChooser.APPROVE_OPTION){
cajaTexto.setText(filechooser.getSelectedFile().getPath());
}
我希望有人能帮我一把,我被困了几天,我对Java世界真的很陌生。我没有放置整个代码,因为有几个类和几行代码。
您需要在两个位置更改代码。我假设按钮操作实际上正在工作。我假设,你的"主"类被称为"我的程序"。
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
JFileChooser filechooser = new JFileChooser();
int option = filechooser.showOpenDialog (this);
if (option==JFileChooser.APPROVE_OPTION){
String filename = filechooser.getSelectedFile().getPath();
cajaTexto.setText(filename);
// call main():
MyProgram.main(new String[] { filename });
}
public static void main(String args[]) {
// assign file name
final String route = args[0];
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
JFrameConFondo jf = new EjemploJFrameConFondo();
jf.setLocationRelativeTo(null);
jf.setTitle("CPM");
jf.setVisible(true);
readfile(route);
}
});
}
}
好的,让我检查一下我是否正确理解了您的问题...
您有一个要在 main
函数中调用的函数readfile(String filename)
。
您可以使用 filechooser.getSelectedFile().getPath()
获取文件的路径。
在这种情况下,可以将所选路径导出到公共类的静态变量中。
所以创建一个新类:
public class Globals
{
private static String FilePath;
public static String GetFilePath()
{
return FilePath;
}
public static void SetFilePath(String NewPath)
{
FilePath = NewPath;
}
}
使用按钮设置它:
Globals.SetFilePath(filechooser.getSelectedFile().getPath());
然后使用它:
readfile(Globals.GetFilePath());
笔记*
这不一定是可用的最佳解决方案。不过,它涉及对已经存在的源代码的最少更改。另外,请原谅我的帕斯卡符号,来自C#的习惯。