【发布时间】:2012-06-19 05:18:24
【问题描述】:
我想知道我们能否拥有一个具有除父 JFrame 之外的布局的 JPanel。例如。如果我有带有边框布局的 JFrame,并且我们嵌入了一个 JPanel,并且它具有不同的布局。有可能吗?
我正在努力做到这一点。但是这样 JPanel 的组件就没有显示出来。
问题来了:
我有一个 JFrame,它的布局是边框布局。我在这个框架上添加了一个 JPanel。如果我没有为 JPanel 设置任何布局。 JPanel 的所有组件都显示在窗口上,但是当我为 JPanel 设置网格布局时,JPanel 的组件不可见。我正在向 JPanel 添加布局以对齐组件。以下是我的代码:
我有一个主类、一个框架类和一个 Jpanel 类。
public class AppMain {
public static void main(String[] args) {
AppPage1 page1 = new AppPage1("test");
page1.setVisible(true);
}
}
public class AppPage1 extends JFrame {
public AppPage1(String title) throws HeadlessException {
super(title);
this.setLayout(new BorderLayout());
addWindowListener(new WindowAdapter() {
public void windowOpened(WindowEvent e) {
setExtendedState(MAXIMIZED_BOTH);
}
});
//Panel for logo
JLabel testLogo = new JLabel("");
testLogo.setIcon(new javax.swing.ImageIcon("test.JPG"));
List<JComponent> componentList = new ArrayList<JComponent>();
componentList.add(testLogo);
PagePanel logoPanel = new PagePanel(componentList,null);
this.add(logoPanel, BorderLayout.NORTH);
//Panel for Button and checkboxes
JLabel panelTitle = new JLabel("test Wizard");
JRadioButton rdButton_ExistingConfigurationFile = new JRadioButton("Existing Configuration File");
JRadioButton rdButton_ConfigureNewPropertyFile = new JRadioButton("Configure new Property File");
componentList = new ArrayList<JComponent>();
componentList.add(panelTitle);
componentList.add(rdButton_ExistingConfigurationFile);
componentList.add(rdButton_ConfigureNewPropertyFile);
PagePanel buttonPanel = new PagePanel(componentList,new GroupLayout(this));
this.add(buttonPanel, BorderLayout.CENTER);
this.pack();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
validate();
}
}
public class PagePanel extends JPanel {
public PagePanel(List<JComponent> componentList, LayoutManager layOutManager) {
this.setBackground(Color.decode("#4E6987"));
if (layOutManager != null) {
this.setLayout(null);
}
for (JComponent jComponent : componentList) {
jComponent.setBackground(Color.decode("#4E6987"));
this.add(jComponent);
}
}
}
提前致谢 拉维库马尔
【问题讨论】:
-
是的,这是可能的。虽然为什么它没有发生在你身边,但为此你需要准确地展示你在做什么!这将帮助任何人回答你,所以你身边的一些代码将不胜感激。默认情况下
JFrame has BorderLayout和JPanel has FLowLayout,因此无需执行任何操作,只需在JPanel上添加组件并将其添加到JFrame而不使用任何其他行,您将得到“是”作为您问题的答案:- ) -
当然,您可以为层次结构的每个组件使用不同的布局管理器。默认情况下,JPanel 使用 FlowLayout。如果您遇到问题,请发帖SSCCE 以获得更好的帮助。
标签: swing user-interface jframe jpanel layout-manager