2013-03-03 45 views
-1

我在做使用java swing從一個位置複製到另一個位置的代碼。我在這裏爲Browse。但我不知道如何添加複製按鈕的功能。請幫助我的代碼。提前致謝。這是我的完整代碼。 (抱歉,如果我錯了,我用這是第一次)如何在java swing中的複製按鈕中添加拷貝功能

/* 
For Browse button. 
*/ 
package com.design; 

import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import javax.swing.JButton; 
import javax.swing.JFileChooser; 
import javax.swing.JFrame; 
import javax.swing.JTextField; 

public class Browse extends JFrame implements 

ActionListener { 

JButton button1, button2 ; 
JTextField field1, field2; 

public Browse() { 
this.setLayout(null); 

button1 = new JButton("Browse"); 
field1 = new JTextField(); 

field1.setBounds(30, 50, 200, 25); 
button1.setBounds(240, 50, 100, 25); 
this.add(field1); 
this.add(button1); 

button2 = new JButton("Copy"); 
button2.setBounds(150, 150, 100, 25); 
this.add(button2); 

button1.addActionListener(this); 
setDefaultCloseOperation 

(javax.swing.WindowConstants.EXIT_ON_CLOSE 

); 



} 

public void actionPerformed(ActionEvent e) { 
Chooser frame = new Chooser(); 
field1.setText(frame.fileName); 

} 

public static void main(String args[]) { 

Browse frame = new Browse(); 
frame.setSize(400, 300); 
frame.setLocation(200, 100); 
frame.setVisible(true); 


} 
} 

class Chooser extends JFrame { 

JFileChooser chooser; 
String fileName; 

public Chooser() { 
chooser = new JFileChooser(); 
int r = chooser.showOpenDialog(new JFrame()); 
if (r == JFileChooser.APPROVE_OPTION) { 
fileName = chooser.getSelectedFile().getPath(); 
System.out.println(fileName); 
} 
} 
} 
+1

你說你需要「複製功能」,但是那是什麼?複製什麼?請解釋你的問題的細節,並告訴你爲什麼你現在的代碼不適合你。 – 2013-03-03 07:36:09

+1

而且你的代碼總是完全左對齊嗎?格式化後的代碼難道不難讀懂嗎?這對我們來說確實很難。請儘快修復您的錯誤代碼格式。 – 2013-03-03 07:38:27

+1

'選擇器'聽起來不太好,所有的JFrame's。 – Mordechai 2013-03-03 07:40:05

回答

1

這是片段複製一個文件與Java 7

try { 
    Files.copy(new File(your_source_file).toPath(), new File(your_target_file).toPath(), StandardCopyOption.REPLACE_EXISTING); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 

不過,我不知道它是還支持與Java 6和以前的版本,所以這是一個「DIY」片段,應與所有Java版本中運行,它返回true如果該文件已被複制,如果false一些異常被拋出:

public boolean copyfile(String sourceFile, String targetFile) { 
    try { 
     File f1 = new File(sourceFile); 
     File f2 = new File(targetFile); 
     InputStream in = new FileInputStream(f1); 

     //Write to the new file 
     OutputStream out = new FileOutputStream(f2); 

     byte[] buf = new byte[1024]; 
     int len; 
     while ((len = in.read(buf)) > 0) { 
     out.write(buf, 0, len); 
     } 
     in.close(); 
     out.close(); 
     System.out.println("File copied."); 
    } catch (Exception ex) { 
     ex.printStackTrace(); 
     return false; 
    } 
    return true; 
} 

希望這可以幫助