Slav Georgiev
Slav Georgiev

Reputation: 101

How to update a JLabel text?

I am making a Hangman game and one of the things I want to make is JLabel text , which updates with ex."_ _ _ _ ", depending on word.

I can share code if you want.

Upvotes: 7

Views: 96566

Answers (5)

AM_Hawk
AM_Hawk

Reputation: 681

Try using setText(); with your JLabel.

Upvotes: 11

JLabel.setText("ex."+text);
super.update(this.getGraphics());

Upvotes: 6

Gayan Liyanaarachchi
Gayan Liyanaarachchi

Reputation: 19

public void updatemylabel(String text){

JLabel.setText("ex."+text);

//place this method inside your Jframe class extend from javax.swing.Jframe
}

Upvotes: 1

Zycro
Zycro

Reputation: 81

This will create a new jLabel and set its text.

JLabel label = new JLabel();
label.setText("____");

You will need to add this label to something like a JFrame.

If you want to quick and easy, here is the code to make a simple window with a label.

import javax.swing.JFrame;
import javax.swing.JLabel;

public class App {

  public static void main(String[] args) {
    JFrame frame = new JFrame("Swing Frame");

    JLabel label = new JLabel("This is a Swing frame", JLabel.CENTER);
    label.setText("____");  // Look familiar?  <----------

    frame.add(label);

    frame.setSize(350, 200); // width=350, height=200
    frame.setVisible(true); // Display the frame
  }

}

Upvotes: 4

Devolus
Devolus

Reputation: 22074

To update the text in a label you use label.setText("New text").

However, without seeing the code, it's hard to say why it doesn't update, as there may be other things wrong.

Upvotes: 1

Related Questions