Java jlabel basic tutorial and examples

I can give you a basic tutorial and examples for using JLabel in Java.

JLabel is a class in the Java Swing package that provides a component for displaying a text or an image. You can create a JLabel and add it to a JFrame or other container to display text or an image to the user.

Here's an example of creating a simple JLabel:

refer to‮gi:‬iftidea.com
import javax.swing.JFrame;
import javax.swing.JLabel;

public class MyLabel extends JFrame {

  public MyLabel() {
    super("Label Example");
    JLabel label = new JLabel("Hello, World!");
    add(label);
    pack();
    setLocationRelativeTo(null);
    setVisible(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }

  public static void main(String[] args) {
    new MyLabel();
  }
}

In this example, we create a new JLabel with the text "Hello, World!" and add it to a JFrame using add(). We then call the pack() method to resize the JFrame to fit its contents, center it on the screen using setLocationRelativeTo(), make it visible with setVisible(true), and set the default close operation to exit the application when the JFrame is closed.

When you run this program, it will display a window with the label "Hello, World!" inside.

Here's an example of creating a JLabel with an image:

import java.awt.Image;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class MyLabel extends JFrame {

  public MyLabel() {
    super("Label Example");
    try {
      URL url = new URL("https://www.example.com/image.png");
      Image image = ImageIO.read(url);
      ImageIcon icon = new ImageIcon(image);
      JLabel label = new JLabel(icon);
      add(label);
    } catch (IOException e) {
      e.printStackTrace();
    }
    pack();
    setLocationRelativeTo(null);
    setVisible(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }

  public static void main(String[] args) {
    new MyLabel();
  }
}

In this example, we create a new JLabel with an image from a URL using ImageIO.read(). We then create a new ImageIcon with the image and create a JLabel with the ImageIcon. We add the JLabel to the JFrame and call the pack() method to resize the JFrame to fit its contents, center it on the screen using setLocationRelativeTo(), make it visible with setVisible(true), and set the default close operation to exit the application when the JFrame is closed.

When you run this program, it will display a window with the image inside the label.

I hope this helps you get started with using JLabel in Java!