在对话框(Java)上显示两条注释

时间:2018-04-23 02:36:56

标签: java swing dialog awt joptionpane

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);
    }

}

}

2 个答案:

答案 0 :(得分:0)

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

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);
  }
}

答案 1 :(得分:0)

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

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);
  }
}