gpt4 book ai didi

java - JFrame 中的两个 JPanel,一个在另一个下

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:31:07 24 4
gpt4 key购买 nike

我的框架中有两个面板,我想将它们一个放在另一个下面,第一个的大小应为 9/10* 屏幕框架,第二个为 1/10。

我试过使用 GridLayout(2 行和 1 列),但我无法设置它们的特定大小。

我应该怎么做?


好吧,也许我会写一些我的代码:

我正在编写游戏 - 吃 bean ,在第一个面板中有一个完整的游戏,在这一秒中我想显示玩家信息(如分数、姓名等)。首先我想设置为 80%屏幕,其次是 20%。

更重要的是,我的框架应该可以调整大小并且包含在其中,所以当框架的大小发生变化时,我必须更改面板的大小(保持这 80% 到 20%)。所以我写了这个 InitComponents()。

package pacman;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.Toolkit;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import java.awt.Image;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;

public class Pacman extends JFrame implements items
{
Image image;
public Pacman()

{
initComponents();
try {
image = ImageIO.read( Pac.class.getResourceAsStream("/img/Pac02.gif"));
} catch (Exception e) {
System.out.println("Blad prz otwieraniu " + e);
System.exit(0);
}


int screen_width = Toolkit.getDefaultToolkit().getScreenSize().width;
int screen_height = Toolkit.getDefaultToolkit().getScreenSize().height;
this.setLocation(screen_width/3, screen_height/3);

this.setLayout(new BorderLayout());
this.getContentPane().add(panel, BorderLayout.CENTER);
this.getContentPane().add(panel2, BorderLayout.PAGE_END);



setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setIconImage(image);

setTitle("..::Pacman::..");
setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setPreferredSize(new Dimension(416,438));
this.pack();
setLocationRelativeTo(null);


setVisible(true);
}
private void initComponents() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

this.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {

int width = e.getComponent().getSize().width;
int height = e.getComponent().getSize().height;
panel.setSize(width, height*8/10) ;
panel2.setSize(width, height*2/10);

}
});


}

public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {

@Override
public void run() {
new Pacman();
}
});
}



}

最佳答案

如果您想要不同大小的组件,GridLayout 是错误的布局。作为javadoc状态:

The container is divided into equal-sized rectangles, and one component is placed in each rectangle.

如果您只有 JPanel,您可能需要考虑一个 JSplitPane - 请参阅 javadoctutorial .

编辑:根据您的编辑/代码,JSplitPane 确实看起来像是您问题的解决方案。然后,您可以在创建后使用 setDividerLocation(double) 设置分隔符位置 - 请参阅 javadoc - 例如

JSplitPane split = new JSplitPane(JSplitPane.VERTICAL);
split.setTopComponent(topPanel);
split.setBottomComponent(bottomPanel);
split.setDividerLocation(0.8);

或者,由于在不知道您对 GUI 的意图的情况下很难提出布局建议,因此您应该考虑查看 Visual Guide到布局。

关于java - JFrame 中的两个 JPanel,一个在另一个下,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10968853/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com