JLabel setText not updating text

前端 未结 5 1820
日久生厌
日久生厌 2020-12-21 16:44

I am trying to update a JLabel by using the setText() method, but I can\'t redraw JLabel. Do I have to use the repaint() method to do that?

5条回答
  •  我在风中等你
    2020-12-21 17:21

    This simple example works for me so problem is not JLabel but some bug in other part of your source code. Please post full source code.

    import java.awt.BorderLayout;
    import java.awt.Button;
    import java.awt.GridLayout;
    import java.awt.Panel;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    
    public class Application {
    
    public static void main(String[] args) {
        JFrame frame = new JFrame("JLabel test");
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    
        Panel p = new Panel();
        p.setLayout(new GridLayout());
    
        Button button = new Button("Change");
        final JLabel label = new JLabel(Long.toString(Long.MAX_VALUE));
    
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                label.setText(Long.toString(e.getWhen()));
            }
        });
    
        p.add(button);
        p.add(label);
        frame.add(p, BorderLayout.NORTH);
        frame.pack();
    
    }
    }
    

提交回复
热议问题