Behzad Moradi
Behzad Moradi

Reputation: 67

How to show a variable value in JLabel

I am new to Java programming. I want to show the value of my variable in the output window not in the console view. Here comes the code:

import java.awt.BorderLayout;

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

public class ShowAFrame {

    public static void main(String[] args) {

        // Variables in this code
        int one = 12;
        int two = 22;
        int total = one + two;
        System.out.println(total);

        JFrame myFrame = new JFrame("Test GUI");
        myFrame.setVisible(true);
        myFrame.setBounds(300, 200, 700, 400);
        JLabel myText = new JLabel("I'm a label in the window",
                SwingConstants.CENTER);
        myFrame.getContentPane().add(myText, BorderLayout.CENTER);

    }

}

Upvotes: 3

Views: 44670

Answers (2)

A human being
A human being

Reputation: 1220

do it like this :

label.setText(String.valueOf(variable));

variable can be an int, float, double, long.

Upvotes: 8

VishalDevgire
VishalDevgire

Reputation: 4278

Just pass total (your result variable) value to JLabel constrcutor.

JLabel myText = new JLabel("I'm a label in the window, output : "+total,
        SwingConstants.CENTER);

Upvotes: 4

Related Questions