Java JFrame 方法 pack()

标签 java user-interface jframe jpanel packaging

我有一个包含 4 个 JPanel 和 1 个 JScrollPane 的框架,这 4 个面板的边框布局为北、东、南、西,滚动 Pane 位于中心。

我一直在尝试获取框架功能的 pack 方法,但运行时您只会获得窗口的标题栏。

有什么想法吗?

    JFrame conFrame;
    JPanel panel1;
    JPanel panel2;
    JPanel panel3;
    JPanel panel4;
    JScrollPane listPane;
    JList list;
    Object namesAr[];
    ...
    ...
    ...
    namesAr= namesA.toArray();
    list = new JList(namesAr); 
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    list.setLayoutOrientation(JList.HORIZONTAL_WRAP);
    list.setVisibleRowCount(-3);
    list.addListSelectionListener(this);

    listPane = new JScrollPane(list);

    panel1 = new JPanel();
    panel2 = new JPanel();
    panel3 = new JPanel();
    panel4 = new JPanel();

    conFrame.setLayout(new BorderLayout());

    panel1.setPreferredSize(new Dimension(100, 100));
    panel2.setPreferredSize(new Dimension(100, 100));
    panel3.setPreferredSize(new Dimension(100, 100));
    panel4.setPreferredSize(new Dimension(100, 100));

    panel1.setBackground(Color.red);
    panel2.setBackground(Color.red);
    panel3.setBackground(Color.red);
    panel4.setBackground(Color.red);

    conFrame.pack();

    conFrame.add(panel1, BorderLayout.NORTH);
    conFrame.add(panel2, BorderLayout.EAST);
    conFrame.add(panel3, BorderLayout.SOUTH);
    conFrame.add(panel4, BorderLayout.WEST);
    conFrame.add(listPane, BorderLayout.CENTER);
    conFrame.setVisible(true);

最佳答案

您需要在执行 pack() 之前将面板添加到框架中,否则就没有任何东西可以打包。

此外,框架的默认布局是 BorderLayout。

关于Java JFrame 方法 pack(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2440754/

相关文章:

java - setUndecorated(true) 与 toFront() 混淆

java - 实现 spring security 时出现 xmlBeanDefinitionStoreException

java - 斯坦福解析器java错误

CSS "nested"If - 将属性添加到不同的类

Android的悬浮窗加上FLAG_SHOW_WHEN_LOCKED失效

java.awt.event.MouseAdapter 的循环速度很慢

java - caritem 和 Invoice 的生命周期关系..对实现 Shoppingcart 的疑问

Java 枚举静态最终实例变量

.net - 如何以编程方式使 ListView 的列自动调整大小?

Java在jframe中打开文件窗口