简体   繁体   English

如何使用Runnable方法将JPanel添加到JFrame

[英]How to add a JPanel to a JFrame with Runnable method

When i create a JPanel and add it to my JFrame and add my canvas to it (space) it will show just the JPanel and not the any of the graphics. 当我创建一个JPanel并将其添加到我的JFrame并将我的画布添加到它(空间)时,它将仅显示JPanel而不显示任何图形。 Why is it only showing the JPanel when i want it to show both of them at the same time? 为什么当我希望它同时显示两个面板时只显示JPanel?

Source Code: http://pastebin.com/Cw9E0a8j 源代码: http : //pastebin.com/Cw9E0a8j

If youre intent was to add the your canvas inside the jPanel you try change the following lines in your source 如果您打算将画布添加到jPanel中,请尝试更改源代码中的以下几行

Original Code : 原始代码:

frame.add(p);
frame.add(space, BorderLayout.CENTER);

Suggested Code : 建议代码:

 p.add(space);
 frame.add(p, BorderLayout.CENTER);

If You are willing to view both JPanel and the canvas in the JFrame try giving positioning to the canvas also.But a different layout will do better. 如果您愿意在JFrame中同时查看JPanel和画布,请尝试也给画布定位,但是使用不同的布局会更好。 Try out the given example. 试试给定的例子。

Original Code : 原始代码:

    frame.setLayout(new BorderLayout());

    frame.add(p);
    frame.add(space, BorderLayout.CENTER);

Suggested Code 1 : By providing the position to the JPanle in the Border Layout. 建议的代码1:通过在边框布局中为JPanle提供位置。

    frame.setLayout(new BorderLayout());

    frame.add(p, BorderLayout.NORTH);
    frame.add(space, BorderLayout.CENTER);

Suggested Code 2 : By Changing the Layout of the JFrame. 建议的代码2:通过更改JFrame的布局。

    frame.setLayout(new GridLayout(0,2));       

    frame.add(p);
    frame.add(space);

For more information please refer official documentation[1]. 有关更多信息,请参阅官方文档[1]。
[1]. [1]。 https://docs.oracle.com/javase/tutorial/uiswing/layout/index.html https://docs.oracle.com/javase/tutorial/uiswing/layout/index.html

The solution is very simple. 解决方案非常简单。 In your code you are placing the 'space' in the center of the window, therefore you are telling it to take up the whole screen. 在您的代码中,您将“空格”放置在窗口的中央,因此您要告诉它占据整个屏幕。 What you should do is this. 您应该做的是这个。

frame.add(p, BorderLayout.EAST);//EAST for the rigth
frame.add(space, BorderLayout.WEST);//WEST for the left

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM