简体   繁体   中英

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'

在此处输入图片说明

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");
        }
    });

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.

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