java - "add one more entry"模式类的好名字

标签 java swing naming-conventions

我正在用java创建一个GUI,有多个地方我想要一个带有按钮的表单来添加一个条目( see an example of the form here 。它是法语,但我认为这并不重要。)。由于添加/删除条目的逻辑在所有地方都是相同的,因此为每个表单创建一个父类似乎是合乎逻辑的。我的问题是:

  • 是否已经有一个我不知道的类可以做同样的事情? (好像会有,因为这是一个经常使用的模式,但我找不到它)
  • 有“添加一个条目”模式的术语吗?

enter image description here

最佳答案

我有一个解决方案。您可以创建一个字符串数组 (String[]) 并使用文本文件文件夹来跟踪您的条目。然后,您可以从文本文件中提取条目。这样,关闭程序时就不会丢失任何数据。以下是您应该执行的操作的演练:

  1. 在运行程序的位置创建一个文件夹来存储文本文件。

  2. 在 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()));
  • 创建一个新类,根据用户输入的名称写入文本文件。您可以将此代码放入 main[] 参数中:
  • 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.

  • 制作可选的删除按钮,用于在用户选择文件时将其删除。如果需要,您可以使用 JFileChooser,不过组合框对我来说就很好。
  • 关于java - "add one more entry"模式类的好名字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34423690/

    相关文章:

    java - 当 jSlider 为 100 时如何启用 jButton?

    java - JFrame 之上的额外层

    java - 使用来自另一个 JComboBox 的值在 JComboBox 中显示数据

    java - 使用 Eclipse Code Formatter for Java 在 if() 中的条件缩进

    java - 获取对象字段先前的值 hibernate JPA

    java - 使用 AssertJ 在测试中获取 JSlider 值

    api - Qt 命名类的方式背后的基本原理是什么?

    java - Java的通用类型参数命名约定(带有多个字符)?

    java - 如何命名存储库和服务接口(interface)?

    java.lang.RuntimeException : Unable to start activity