3

I am creating a GUI in java and there are multiple places where I want a form with a button to add one more entry ( see an example of the form here. It is in french, but I think it does not matter. ). Since the logic to add/delete entries is the same in all places, it seems logic to create a parent class for each form. My questions are :

  • Is there already a class I don't know about that does the same thing? (it seems like there would be since it is a frequently used pattern, but I could not find it)
  • Is there a term for the "add one more entry" pattern?

enter image description here

Frakcool
  • 10,915
  • 9
  • 50
  • 89
fredq
  • 141
  • 4

1 Answers1

0

I have a solution. You can create a String array (String[]) and use a folder of text files to track your entries. Then, you can pull up your entries from the text files. This way, you won't lose any data when you close the program. Here is a walk through of what you should do:

  1. Make a folder in the location you are running the program to store text files.

  2. Type the following code in the actionPreformed() argument of your jButton, or whatever trigger you have:

File f = new File("Name Of Your Folder");
ArrayList<String> names = new ArrayList<String>(Arrays.asList(f.list()));
nameOfYourComboBox.setModel(new DefaultComboBoxModel(names.toArray()));
  1. Create a new class that writes text files based on the name the user enters. You can put this code in your main[] argument:
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);
        }
    }
  1. Make a button in your first class that calls the second class:

NameOfMySecondClass nomsc = new NameOfMySecondClass();
nomsc.setVisible(true);
//This will only work if your second class has a .setVisible() constructor.
  1. Make optional delete buttons that remove files when the user selects them. You can use a JFileChooser if you want, although a combo box is fine for me.
Hackstaar
  • 233
  • 2
  • 13