你说的另外一个按钮中的意思是 这个按钮的click事件中吧。如果是这样,把file声明为成员变量。给两个button添加ActionListener时,用inner class。 比如: button1.addActionListener(new ActionListener(){ public void actionPerformed( ActionEvent e ){ //在此处理文件 } }); button2.addActionListener(new ActionListener(){ public void actionPerformed( ActionEvent e ){ //在此处理文件 } });这个办法不知道是不是你想要的
to small_roc(小飞): 可是绝对路径可能是变化的呀,那该怎么办? to zh9625(短笛) : 对,我就是要在click事件中处理file你说的inner class我不太明白,麻烦你能不能说的清楚点
上面我写的addActionListener()函数的参数 就是一个inner class(嵌套在别的类或方法中的类)。 参数new ActionListener(){ public void actionPerformed( ActionEvent e ){ //在此处理文件 } } 是inner class 中的特殊情况——匿名类。格式为new Xxxx(){/* class body */}。它可以访问它所在类中的成员,或是所在方法中的final变量。
如果我没理解错的话,你的程序大概可以这样写吧(下面程序并没编译):public class Frame1 extends Frame{ File file; Frame1(){ Button button1 = new Button("button1 "); Button button2 = new Button("button2 ");
button1.addActionListener(new ActionListener(){ public void actionPerformed( ActionEvent e ){
FileDialog dg=new FileDialog(frame,"open a file",0); dg.show (); file=new File(dg.getDirectory (),dg.getFile ()); } }); button2.addActionListener(new ActionListener(){ public void actionPerformed( ActionEvent e ){ RandomAccessFile f=new RandomAccessFile(file,"rw"); } }); add(button1); add(button2); } public static void main(String args[]){ Frame1 frame=new Frame1(); frame.setVisible(true); } }
可以将文件的绝对路径设成变量。
button1.addActionListener(new ActionListener(){
public void actionPerformed( ActionEvent e ){
//在此处理文件
}
});
button2.addActionListener(new ActionListener(){
public void actionPerformed( ActionEvent e ){
//在此处理文件
}
});这个办法不知道是不是你想要的
可是绝对路径可能是变化的呀,那该怎么办?
to zh9625(短笛) :
对,我就是要在click事件中处理file你说的inner class我不太明白,麻烦你能不能说的清楚点
参数new ActionListener(){
public void actionPerformed( ActionEvent e ){
//在此处理文件
}
}
是inner class 中的特殊情况——匿名类。格式为new Xxxx(){/* class body */}。它可以访问它所在类中的成员,或是所在方法中的final变量。
File file;
Frame1(){
Button button1 = new Button("button1 ");
Button button2 = new Button("button2 ");
button1.addActionListener(new ActionListener(){
public void actionPerformed( ActionEvent e ){
FileDialog dg=new FileDialog(frame,"open a file",0);
dg.show ();
file=new File(dg.getDirectory (),dg.getFile ()); }
});
button2.addActionListener(new ActionListener(){
public void actionPerformed( ActionEvent e ){ RandomAccessFile f=new RandomAccessFile(file,"rw");
}
}); add(button1);
add(button2);
}
public static void main(String args[]){
Frame1 frame=new Frame1();
frame.setVisible(true);
}
}