简体   繁体   中英

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. 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...

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

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 . You could use StringJoiner for this:

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 .

You could find more about how to use StringJoiner here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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