我正在java中创建一个GUI,我想要一个带有按钮的表单,可以添加多一个条目(see an example of the form here。这是法语,但我认为没关系。)。由于添加/删除条目的逻辑在所有地方都是相同的,因此为每个表单创建父类似乎是逻辑。我的问题是:
答案 0 :(得分:0)
我有一个解决方案。您可以创建一个String数组(String [])并使用文本文件夹来跟踪您的条目。然后,您可以从文本文件中提取条目。这样,关闭程序时不会丢失任何数据。以下是您应该做的事情:
在运行程序的位置创建一个文件夹来存储文本文件。
在jButton的actionPreformed()参数中键入以下代码,或者您拥有的任何触发器:
File f = new File("Name Of Your Folder");
ArrayList<String> names = new ArrayList<String>(Arrays.asList(f.list()));
nameOfYourComboBox.setModel(new DefaultComboBoxModel(names.toArray()));
BufferedWriter bw = null;
try {
JTextPane textPane1 = new JTextPane();
//You can use other containers, I just used a text pane as an example.
JTextPane textPane2 = new JTextPane();
//This Pane is optional. It simply sets the contents of the file.
//Specify the file name and path here
File file = new File("/MyFolder'sNameGoesHere" + textPane1.getText());
/* This logic will make sure that the file
* gets created if it is not present at the
* specified location*/
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file);
bw = new BufferedWriter(fw);
bw.write(jTextPane2.getText());
System.out.println("File written Successfully");
} catch (IOException ioe) {
ioe.printStackTrace();
}
finally
{
try{
if(bw!=null)
bw.close();
}catch(Exception ex){
System.out.println("Error in closing the BufferedWriter"+ex);
}
}
NameOfMySecondClass nomsc = new NameOfMySecondClass();
nomsc.setVisible(true);
//This will only work if your second class has a .setVisible() constructor.