James Gosling: idealism, the Internet and Java, Pt I

Monday 29 January 2018

Swing JLabel demo with example

This article is continuation of previous post JFrame usage demo. Please read it before continuing.

This post uses the same example code shown in JFrame usage demo with JLabel changes and introduces layout manager BorderLayout.

Layout Manager:

Layout manager is responsible to arrange components on containers. Usually every swing container is created with a default layout manager but can be changed with setLayout() api. For example JFrame uses BorderLayout as default layout amanger.

Java program for JLabel


2   import java.awt.BorderLayout;
3   import java.awt.Color;
4   import java.awt.Font;

6   import javax.swing.JFrame;
7   import javax.swing.JLabel;
8   import javax.swing.SwingUtilities;

10  /**
11   *
12   * Simple class to demonstrate JLabel of swing toolkit
13   *
14   * @author Nagasharath
15   *
16   */
17  public class LabelDemo extends JFrame {
18
19  private final String title = "It's all abt java!...  ";
20
21  private JLabel label;
22
23  /**
24  * set properties of the main window. Title, size of frame and position/location
25  */
26  public LabelDemo() {
27  this.setTitle(title);
28  this.setSize(300, 200);
29  this.setLocationRelativeTo(null);
30  initComponents();
31  }
32
33  /**
34  * instantiates controls controls.
35  *
36  */
37  private void initComponents() {
38  BorderLayout layout = new BorderLayout(20, 10);
39  this.setLayout(layout);
40
41  label = new JLabel("java-gui.blogspot.com");
42  label.setForeground(Color.RED);
43  label.setFont(new Font(Font.MONOSPACED, Font.BOLD, 25));
44  this.getContentPane().add(label, BorderLayout.CENTER);
45  }
46
47  public static void main(String[] args) {
48
49  Runnable r = () -> {
50  LabelDemo demo = new LabelDemo();
51  demo.setVisible(true);
52  };
53  SwingUtilities.invokeLater(r);
54  }
55  }
56


Line 21: Introduced new variable of type JLabel

Line 38 and Line 39: Used BorderLayout as layout manager to arrange label component on JFrame container

Line 41: Instantiated label with a text of String type.

Line 42 and Line 43:  label properties like foreground color, font style, size, type and background etc are specified

Line 44:  Finally added this label to the JFrame using add().

Output:


JFrme with JLabel

No comments:

Post a Comment

Popular posts

Demonstration of Java NullPointerException

NullPointerException causes and reasons Since Java is object oriented programming language, every thing is considered to be an object. and t...