Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swing JLabel text change on the running application

Tags:

java

swing

jlabel

I have a Swing window which contains a button a text box and a JLabel named as flag. According to the input after I click the button, the label should change from flag to some value.

How to achieve this in the same window?

like image 724
JavaBits Avatar asked Jul 05 '11 05:07

JavaBits


1 Answers

Use setText(str) method of JLabel to dynamically change text displayed. In actionPerform of button write this:

jLabel.setText("new Value");

A simple demo code will be:

    JFrame frame = new JFrame("Demo");
    frame.setLayout(new BorderLayout());
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.setSize(250,100);

    final JLabel label = new JLabel("flag");
    JButton button = new JButton("Change flag");
    button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            label.setText("new value");
        }
    });

    frame.add(label, BorderLayout.NORTH);
    frame.add(button, BorderLayout.CENTER);
    frame.setVisible(true);
like image 81
Harry Joy Avatar answered Sep 30 '22 20:09

Harry Joy