在对话框中显示两个评论(Java)

Display both comments on dialogbox(Java)

comment 1 comment 2

如何在对话框中显示两条评论?

下面是我的代码供参考。

private class HandleTextField implements ActionListener
{
    @Override
    public void actionPerformed (ActionEvent e)
    {
        String string  = "";

        if (e.getSource () == textFieldArray [0])
        {
            string = String.format("1. %s", e.getActionCommand());
        }
        else if (e.getSource () == textFieldArray [1])
        {
            string = String.format("2. %s", e.getActionCommand());
        }

        Object [] fields ={
            "Summary of my changes" , string
        };

        JOptionPane.showMessageDialog(null, fields, "My sugestion to the course", JOptionPane.WARNING_MESSAGE);
    }

}

}

因此,如果您观察到,您的字符串在每种情况下都是重叠的。如果你想要两者都出现,你至少应该这样做:

private class HandleTextField implements ActionListener {
   @Override
   public void actionPerformed (ActionEvent e) {
      String string  = "";

      if (e.getSource () == textFieldArray [0]){
         string += String.format("1. %s", e.getActionCommand());
      } 
      if (e.getSource () == textFieldArray [1]) {
         string += String.format("2. %s", e.getActionCommand());
      }

      String[] fields = {"Summary of my changes" , string};

      JOptionPane.showMessageDialog(null, fields, "My sugestion to the course", JOptionPane.WARNING_MESSAGE);
   }
}

我建议像这样执行此代码(更建议在 String 对象上附加内容):

private class HandleTextField implements ActionListener {
  @Override
  public void actionPerformed (ActionEvent e) {
     StringBuilder string  = new StringBuilder();

     if (e.getSource () == textFieldArray [0]){
        string.append(String.format("1. %s", e.getActionCommand()));
     } 
     if (e.getSource () == textFieldArray [1]) {
        if(string != null && string.toString().length() > 0){
           string.append(System.lineSeparator());
        }
        string.append(String.format("2. %s", e.getActionCommand()));
     }

     String[] fields = {"Summary of my changes" , string.toString()};

     JOptionPane.showMessageDialog(null, fields, "My sugestion to the course", JOptionPane.WARNING_MESSAGE);
  }
}

以下未经测试的代码将在两个 TextFields 中的任何一个触发操作时将其内容放入您的对话框中。

private class HandleTextField implements ActionListener {
  @Override
  public void actionPerformed (ActionEvent e) {
    StringBuilder string  = new StringBuilder();

    if (e.getSource () == textFieldArray[0] || 
        e.getSource () == textFieldArray[1]){
      string.append(String.format(
          "1. %s", textFieldArray[0].getText())
        );
      string.append(String.format(
          "2. %s", textFieldArray[1].getText())
        );
    }

    String[] fields = {"Summary of my changes" , string.toString()};

    JOptionPane.showMessageDialog(null, fields, "My suggestion to the course", JOptionPane.WARNING_MESSAGE);
  }
}