简体   繁体   English

如何将元素从列表添加到标签?

[英]How to add elements from list to label?

I have a variable like this: 我有一个像这样的变量:

List<Double> data = new LinkedList<Double>();
JTextField field = new JTextField(" ");
JLabel label = new JLabel(" ");
JButton button = new JButton(" "); 

data are values from list, that I need to get from user from JTextField. 数据是列表中的值,我需要从JTextField的用户那里获取。 I need them to be added to a Label: user writes a value in TextField, clicks a button, the value is added to the label, writes a new value, clicks the button again, the value is visible next to the previous, and so on... 我需要将它们添加到标签中:用户在TextField中写入一个值,单击一个按钮,将该值添加到标签中,写入一个新值,再次单击该按钮,该值在前一个旁边可见,依此类推上...

button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent a) {
                //data = Double.parseDouble(field.getText());
                //label.setText(String.valueOf(data));

                for(int i=0; i<10; i++)
                {
                    data = Double.parseDouble(field.getText()); //not working
                    label.setText(String.valueOf(data));
                }
            }
    });

it works only for one double variable (code //) 它仅适用于一个双精度变量(代码//)

My questions: how to change double list elements to be addable to the label? 我的问题:如何更改可添加到标签的重复列表元素? How to make new values visible next to the previous values? 如何使新值在以前的值旁边可见? (loop?) (环?)

Statement label.setText(String.valueOf(data)); 语句label.setText(String.valueOf(data)); do not append the parameter to the label but sets it. 不要将参数附加到标签上,而是进行设置。 In your cycle data has always the same value, so its sets 10 times the same string to label's text. 在循环中, data始终具有相同的值,因此它会将相同字符串设置为标签文本的10倍。

If you want to append the String.valueOf(data) to the text of label, you need to build text of label first from your List . 如果要将String.valueOf(data)附加到label的文本,则需要首先从List生成label的文本。 You could use StringJoiner for this: 您可以为此使用StringJoiner

StringJoiner joiner = new StringJoiner(" ");
data.stream().map(String::valueOf).forEach(joiner::add);
label.setText(joiner.toString());

So in actionPerformed method, you add Double.parseDouble(field.getText()) to the list, then build the text as showed before and set it to label using setText . 因此,在actionPerformed方法中,将Double.parseDouble(field.getText())添加到列表中,然后如前所示构建文本,并使用setText将其设置为label。

You could find more about how to use StringJoiner here . 您可以在此处找到有关如何使用StringJoiner的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM