我已經寫了概念證明了這一點,它的工作原理究竟爲預期。當你運行它,一個JFrame
打開:
的JFrame
由JButton
的文本ATUL推,推!當你點擊這個按鈕會打開一個對話框:
我選擇一個文件夾(test
),我選擇一個文件名(test.pdf
)。然後點擊保存。這是我的文件夾中顯示的內容:
當我打開這個文件,我看到:
這是例子的完整代碼:
/*
* Example written in answer to:
* http://stackoverflow.com/questions/35669782/
*/
package sandbox.objects;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
/**
* @author Bruno Lowagie (iText Software)
*/
public class PdfOnButtonClick {
public class PdfActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
JFileChooser dialog = new JFileChooser();
int dialogResult = dialog.showSaveDialog(null);
if (dialogResult==JFileChooser.APPROVE_OPTION){
String filePath = dialog.getSelectedFile().getPath();
try {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(filePath));
document.open();
document.add(new Paragraph("File with path " + filePath));
document.close();
}
catch(DocumentException de) {
de.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(300, 300);
frame.setTitle("ATUL doesn't know how to code");
frame.setResizable(true);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JButton button = new JButton("Push ATUL, push!");
button.addActionListener(new PdfOnButtonClick().new PdfActionListener());
frame.getContentPane().add(button);
frame.setVisible(true);
}
}
我想通過「動態文件」和Swing你也許應該看看'JFileChooser'但我真的不明白這個問題之前,這句話..莫非你rephras e要求是什麼? –
我修復了永遠不會編譯的代碼。我也糾正了你的英語。我刪除了關於'JFileChooser'一個很奇怪的句子說:*所以這點你,我使用j個文件選擇用於生成用戶定義名稱的PDF *你的英語不好,但如果我理解正確的話,你說你是。使用'JFileChooser'。這不會反映在您的代碼中。你有沒有試過我在我的答案中分享的代碼?它有什麼問題?爲什麼它被低估?請解釋。 –
你剛剛讓你的問題變得更糟。現在沒人知道你在說什麼!閱讀[文檔](https://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html)並用'JFileChooser'解釋你的問題。也許你的問題甚至不在於文件選擇器。也許你不知道如何將「ActionListener」添加到「JButton」中(http://stackoverflow.com/questions/16351875/jfilechooser-on-a-button-click)。無論如何,你的問題仍然不值得重新投票。你的編輯*迷惑*,你需要*澄清*! –