gpt4 book ai didi

java - 具有多个文件扩展名的 JFileChooser 保存对话框

转载 作者:行者123 更新时间:2023-11-30 08:12:06 25 4
gpt4 key购买 nike

我正在尝试使用 JFileChooser 保存文件和一个 TxtWriter .txt 的类选项和一个 XmlWriter .xml 的类选项。起初我只尝试创建 txt选项,但它似乎不起作用。

这是 JFileChooser 的代码:

JMenuItem mntmCreate = new JMenuItem("Create Report");
mntmCreate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
switch (chooser.showSaveDialog(frame)){
case JFileChooser.APPROVE_OPTION:
File fileToWrite = chooser.getSelectedFile();
TxtWriter txtwriter = new TxtWriter(taxpayer);
txtwriter.writeReport(taxpayer);
System.out.println("Report taxpayer: " +taxpayer.toString());
}
}
});

TxtWriter :

public class TxtWriter implements Writer {

public TxtWriter(Taxpayer taxpayer) {
writeReport(taxpayer);
}

public void writeReport(Taxpayer taxpayer) {

PrintWriter writer;
try {
writer = new PrintWriter("Report.txt", "UTF-8");
printToWriterTaxpayerInfo(taxpayer, writer);
printToWriterTaxDetails(taxpayer, writer);
printToWriterReceiptsAmountDetails(taxpayer, writer);
writer.close();

} catch (FileNotFoundException | UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public void printToWriterTaxpayerInfo(Taxpayer taxpayer, PrintWriter writer) {
writer.println("Name: " + taxpayer.getName());
writer.println("AFM: " + taxpayer.getTaxRegistrationNumber());
writer.println("Status: " + taxpayer.getStatus());
writer.println("Income: " + taxpayer.getIncome());
}

public void printToWriterTaxDetails(Taxpayer taxpayer, PrintWriter writer) {
writer.println("Basic Tax: " + taxpayer.getBasicTax());
writer.println("Tax Increase: " + taxpayer.getTaxIncrease());
writer.println("Total Tax: "
+ (taxpayer.getBasicTax() + taxpayer.getTaxIncrease()));
}

public void printToWriterReceiptsAmountDetails(Taxpayer taxpayer,
PrintWriter writer) {
writer.println("Total Receipts Gathered: "
+ taxpayer.computeTotalReceiptsGathered());
writer.println("Entertainment: "
+ taxpayer.computeReceiptsAmountForKindEntertainment());
writer.println("Basic: " + taxpayer.computeReceiptsAmountForKindBasic());
writer.println("Travel: "
+ taxpayer.computeReceiptsAmountForKindTravel());
writer.println("Health: "
+ taxpayer.computeReceiptsAmountForKindHealth());
writer.println("Other: " + taxpayer.computeReceiptsAmountForKindOther());
}
}

同样,有一个XmlWriter xml 的类文件。
我想使用这两个编写器类来创建不同的文件类型。

最佳答案

您可以在 JFileChooser 中添加过滤器以仅允许文本和 xml 文件。

JFileChooser jf = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("TEXT FILES", "txt", "text");
jf.setFileFilter(filter);

或使用 addChoosableFileFilter

fc.addChoosableFileFilter(new FileNameExtensionFilter("XMl and text Files", "xml","txt");

关于java - 具有多个文件扩展名的 JFileChooser 保存对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30708832/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com