JButton 未显示在 JFrame 中
各位程序员大家好!
JButtons 应该能够显示在 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);
}
}
Hello fellow programmers!
Are JButtons supposed to be able to show up in JFrame? I used the setVisible method on JButton but it would not appear.
Error Message:
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)
Code:
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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要将按钮添加到框架中,尝试
gameFrame.add(gameButton);
You need to add the button to the frame, try
gameFrame.add(gameButton);
您需要将按钮添加到框架中。
如
gameFrame.add(gameButton);
you need to add button to frame.
such as
gameFrame.add(gameButton);
将其添加到面板中,否则它永远不会显示。
gameFrame.add(gameButton);
Add it to the panel otherwise it won't show up, ever.
gameFrame.add(gameButton);
您必须向框架或面板添加按钮:例如
JFrame.add(gameButton);
you must have to add button to frame or panel : for example
JFrame.add(gameButton);