2013-03-20 153 views
3

我是Java編程的新手。我想在輸出窗口中顯示變量的值,而不是在控制檯視圖中顯示。 這裏談到的代碼:如何在JLabel中顯示變量值

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); 

    } 

} 
+0

你不需要編寫代碼來顯示消息 - 你可以使用已經存在的東西:看看JOptionPane.showMessage – evgenyl 2013-03-20 19:19:15

回答

4

總(你的結果變量)的值就傳遞給JLabel的constrcutor。

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

它付出了代價。非常感謝。 – 2013-03-20 19:07:49

8

做這樣的:

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

變量可以是整數,浮點,雙長。

+0

謝謝Johan :) – 2013-03-20 19:04:33