gpt4 book ai didi

java - 设计 JFrame 并安装多个 JPanel?

转载 作者:太空宇宙 更新时间:2023-11-04 13:37:54 25 4
gpt4 key购买 nike

我是新的 java GUI 开发人员,我有一个问题。

是否可以创建一个包含多个 Jpanel 的 Jframe?我的想法是创建一个类,其中添加了 JPanel 中的组件,并从另一个类创建 JFrame 添加 JPanel 类的多个对象。

目前我正在做测试:

public class Principal {

private JFrame window;

public Principal(){

window = new JFrame("Principal");
}

/**
* @return the finestra
*/
public JFrame getFinestra() {
return window;
}
}`

子类

public class Childs {

private JPanel panel;
private JLabel text1;

public Childs(){
panel = new JPanel();
text1 = new JLabel();

text1.setText("TEXT");
panel.add(text1);
}

/**
* @return the panel
*/
public JPanel getPanel() {
return panel;
}
}

TestFrame类

public class TestFrame {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {

Principal p = new Principal();
Childs c = new Childs();
Childs c2 = new Childs();

p.getFinestra().add(c.getPanel());
p.getFinestra().add(c2.getPanel());
p.getFinestra().setVisible(true);
}
}
`

最佳答案

一个 JFrame 中当然可以有多个 JPanel。您可以使用 getContentPane() 从 JFrame 获取组件 Container,在您的示例中它将作为

p.getFinestra().getContentPane();

要了解如何将 JPanel 放置到 JFrame 中,您应该研究一些 Layout。这是一个很好的资源,该网站还有更多资源:https://docs.oracle.com/javase/tutorial/uiswing/layout/index.html

例如使用FlowLayout(默认)

p.getFinestra().getContentPane().setLayout(new FlowLayout());
p.getFinestra().getContentPane().add(c);
p.getFinestra().getContentPane().add(c2);

//It is also a good habit to call pack() before setting to visible
p.getFinestra().pack()
p.getFinestra().setVisible(true);

作为英语简短类(class),child 的复数形式是 children

关于java - 设计 JFrame 并安装多个 JPanel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31536489/

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