2012-02-14 109 views
-2

你好同事!JButton沒有顯示在JFrame中

JButton應該能夠顯示在JFrame中嗎?我在JButton上使用了setVisible方法,但它不會出現。

錯誤消息:

Exception in thread "main" java.lang.IllegalArgumentException: adding a window to a container 
    at java.awt.Container.checkNotAWindow(Unknown Source) 
    at java.awt.Container.addImpl(Unknown Source) 
    at javax.swing.AbstractButton.addImpl(Unknown Source) 
    at java.awt.Container.add(Unknown Source) 
    at FrameTest.initializeGameFrame(FrameTest.java:27) 
    at FrameTest.main(FrameTest.java:17) 

代碼:

import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 


public class FrameTest extends JFrame{ 

    private static final int gameWindowHeight = 700; 
    private static final int gameWindowLength = 700; 

    /** Set up frame for game window 
    * 
    */ 

    public static void main(String[] args) 
    { 
     FrameTest.initializeGameFrame(); 

    } 

    public static void initializeGameFrame() 
    { 
     FrameTest gameFrame = new FrameTest(); 
     gameFrame.setSize(gameWindowLength, gameWindowHeight); 
     gameFrame.setTitle("Frame Test- by Me"); 
     JButton gameButton = new JButton("Start Game"); 
     gameButton.add(gameFrame); 
     gameButton.setLocation(250, 250); 
     gameButton.setVisible(true); 
     gameFrame.setVisible(true); 

    } 


} 
+1

如果你讀你得到它提供了一個小的洞察力,以您的問題異常:「增加一個窗口添加到容器」。 IE,你正在將'JFrame'添加到你的'JButton'而不是其他的方式。 – Jeffrey 2012-02-14 23:36:43

+1

下次在詢問之前實際上試圖找出問題。 – Jimmt 2012-02-14 23:49:15

回答

6

您需要將按鈕添加到框架,嘗試gameFrame.add(gameButton);

4

你需要添加按鈕幀。 如gameFrame.add(gameButton);

4

將其添加到面板,否則它不會顯示,永遠。 gameframe.add(gameButton); gameFrame.add(gameButton);

0

您必須添加按鈕框架或面板:例如JFrame.add(gameButton);