Home » Java » java – Refresh data in a JLabel-Exceptionshub

java – Refresh data in a JLabel-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have a program which calculates an integer and then uses the value within a JLabel. On intital creation everything is fine with the initialized value, but when I change the value of the int within the label I can’t seem to find a way to update the JLabel. The relevant code is as follows:

    JLabel carbLbl;
    int totCarbs = 0;

    public Main() {
        carbLbl = new JLabel("Total Carbs: " + totCarbs);
        carbLbl.setFont(new Font("KidSans", Font.PLAIN, 38));
        carbLbl.setAlignmentX(Component.RIGHT_ALIGNMENT);

    void addFoodToTable() {
        String[] s = new String[3];
        s = (String[]) foodData.get(foodChoice.getSelectedIndex());
        foodList.addRow(s);
        totCarbs += Integer.parseInt(s[2]);
        carbLbl.repaint();
    }
}

There’s obviously much more code, but it’s too long to include the entire script. Is there a way I can have the label update whenever I invoke the addFoodToTable() method?

How to&Answers:

The JLabel is not “bound” to your integer variable. When you change the integer you need to update the JLabel using carbLbl.setText(String.valueOf(totCarbs))

Answer:

Is there not a way to simply update the JLabel using the initial constructor parameters?

carbLbl = new JLabel("Total Carbs: " + totCarbs);

What parameters? There is only a single parameter, the String to be displayed.

The compiler concatenates the hard coded String with the value of your “totCarbs” variable to create a single String.

The compiler will essentially treat the above code like:

String text = "Total Carbs" + totCarbs;
carbLbl = new JLabel( text );

The JLabel has no idea how the String was created (ie. that a variable was used to build the string).

I understand the concept of concatenation, but I just feel like that’s a workaround

It is not a work around. The API of the setText(…) method states you provide a single String. So, if you want to update the label you need to provide the entire String.