Search code examples
javaswingjlabel

Update the JLabel's label text during the event - Swing


Basically I want change the JLabel's Label text during on-click the button 'Generate PDF Record Book'

enter image description here

From the previous example says:

label.setText("new value");

when I do that, the label value doesn't change at all, please give me some directions, thanks

initialize();

JLabel lblNewLabel = new JLabel("513 k bytes");
    lblNewLabel.setBounds(407, 713, 151, 14);
    frmViperManufacturingRecord.getContentPane().add(lblNewLabel);

On button Generate PDF Record Book click

        JButton btnGeneratePdfHeader = new JButton("Generate PDF Record Book");
    btnGeneratePdfHeader.setMnemonic('G');
    btnGeneratePdfHeader.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {

            final JLabel lblNewLabel = new JLabel("513 k bytes");

            //java.io.File file = new java.io.File(strdfile);
            //lblNewLabel.setSize(file.length());
            //System.out.println(file.length());

            String fileSize = file.length() + " k bytes";
            System.out.println("I am here");

            lblNewLabel.setText("new value");
        }
    });

Solution

  • You are creating a new JLabel when pressing the button and then set the text of that label to "new value"

    final JLabel lblNewLabel = new JLabel("513 k bytes");
    lblNewLabel.setText("new value");
    

    rather than changing the text of the label on your UI. You will need to call setText("new value") on a reference to the label you've already added to the UI instead. For instance, that label would neeed to be a field in your UI class, eg final JLabel fileSizeLabel and you would set that labels text by calling

    fileSizeLabel.setText("new value");
    

    inside the buttons action listener.