如何从变量创建 JLabel? (即由变量命名和填充)

How do I create a JLabel from variables? (ie both named and populated by variables)

有没有办法从变量创建 JLabel?举一个简单的例子,我将使用一个调查创建器,第一个用户创建一系列问题供下一个用户回答,评分为 1-5。如果我希望第一个用户能够输入他们想要的问题数量而不是预定义的数量,我该如何实现以下伪代码的 JLabel 创建行?

for(int enterQuestion < int finishedEntering enterQuestion++)

(不是 for 循环 - 单个按钮操作,但它会一直持续到单击完成的按钮)

从用户那里获取输入(GUI,因此从 JTextField 获取输入)

将该输入分配给问题[enterQuestions]

创建JLabel (questionLabel + enterQuestions) = new JLabel(questions[enterQuestions]);

程序的其余部分我没有遇到任何问题,但是当我不执行 for 循环时我不知道如何生成那样的 labelID,因为它依赖于 buttonClick 来进行更改。

如果你制作一个 JLabelsArrayList,然后用 JButton 制作 JTextField,当你点击按钮时,得到文本的文本字段,然后将新的 JLabel 添加到 ArrayList 并将文本字段文本作为传递参数。在程序开始时,创建一个字段来跟踪有多少问题。然后你可以将它添加到 JPanel,有点像这样。

private int questionCount = 0;
private ArrayList questionLabelList;
public Survey()
{
    questionLabelList = new ArrayList();
    //instantiate the JTextField and JButton here along with adding the actionListener
}
private class ButtonListener implements ActionListener
{
    public void actionPerformed(ActionEvent e)
    {
        if(textField.getText() != null)
        {
             questionCount++;
             questionLabelList.add(new JLabel(questionCount + ". " + textField.getText()));
             add(questionLabelList[questionCount - 1]);
             textField.setText("");
        }
    }
}

你是这个意思吗?

您可以将响应放在一个集合中以删除重复项,然后迭代该集合以创建您的标签。 "new question" 按钮(不是完成按钮)会抓取文本字段的内容,将它们添加到集合中,清除字段,等等。完成的按钮操作将迭代集合并使用每个条目构造 JLabel:

Set<String> responses = new TreeSet<>();
.
.
newQuestionButton.addActionListener(ActionEvent evt)
{
    responses.add(userInputTextField.getText());
    userInputTextField.setText(""); //clear the field
}
.
.
.
finishedButton.addActionListener(ActionEvent evt)
{
    for(String question : responses)
    {
         add(new JLabel(question)); //or some variation, based on your layout.
    }
}

如果您想保留输入问题的顺序,您可以使用 LinkedHashSet 而不是 TreeSet。 TreeSet 将改为排序遍历。