2016-04-23 42 views
0

我想用Swing寫一個小的UI程序。我需要有幾個文本框,但是定義一個新的文本框或者textarea(我甚至不必將它添加到框架中)會隨機地阻止自己以及代碼中添加的任何內容出現在屏幕上。我可以重新編譯相同的代碼而不做任何更改,也許可以在1/3的時間內正常工作。什麼導致這個問題,有什麼辦法可以改變它嗎?我會粘貼代碼波紋管:JTextField隨機沒有出現在程序中,即使代碼沒有改變

import java.awt.*; 
import javax.swing.*; 

public class ThisApp 
{ 
    public static void main(String [] Args) 
    { 
     new ThisUI();  
    } 
} 


class ThisUI extends JFrame //implements ActionListener 
{ 
    public ThisUI() 
    { 
     setTitle("ThisApp - Best in the business"); 
     setResizable(false); 
     setVisible(true); 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     setSize(300, 200); 
     setLayout(new GridLayout(2,1)); 

     JButton cat = new JButton("Cat"); 

     this.add(new JButton("Button")); 
     this.add(new JTextField("CAT CAT",10));  
    } 
} 

感謝在先進的任何幫助!

回答

3

問題是你添加組件到框架之後,框架是可見的,不要調用佈局管理器,所以所有組件的大小爲0,所以沒有什麼可以繪製。

框架必須在所有組件都添加到框架後變爲可見。

所以你的代碼的結構應該是這樣的:

setTitle("ThisApp - Best in the business"); 
setResizable(false); 
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

setLayout(new GridLayout(2,1)); 

JButton cat = new JButton("Cat"); 
this.add(new JButton("Button")); 
this.add(new JTextField("CAT CAT",10));  

setSize(300, 200); 
setLocationRelativeTo(null); 
setVisible(true); 
+0

這做到了。太感謝了! – cafemolecular