【问题标题】:Adding a JPanel into a BorderLayout of a JApplet将 JPanel 添加到 N Applet 的 BorderLayout
【发布时间】:2014-11-03 03:28:25
【问题描述】:

我无法将此 JPanel 添加到窗格的中心块中。本质上,这个主窗口是一个 BorderLayout,其中心有 centerPanel,而西和东块将是单独的 BorderLayouts。我已经用谷歌搜索了这个问题,并查看了我教授的示例代码以及 stackoverflow 上的示例代码,但我在我的代码中找不到问题。

我在 Eclipse 中完成所有编码,因此我使用集成的 AppletViewer。唯一出现的是一个空的灰色框,我希望在其中看到包括 JLabels 和 JTextAreas 的 centerPanel。

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class Lab7 extends JApplet implements ItemListener, ActionListener{

//variables
private JLabel currentOrder, total;
private JTextArea descTop, currentOrderTA, totalTA;
private JRadioButton sizeSmall, sizeMedium, sizeLarge, typeDeep, typePan, typeHand;
private JCheckBox pepperoni, bacon, extra_cheese, mushroom, pepper, sausage, tomato, olive;
private JButton orderButton, resetButton;
private ButtonGroup sizeBG, typeBG;
private BorderLayout borderLayoutMain, borderLayoutWest, borderLayoutEast;
private JPanel westPanel, centerPanel, eastPanel;

public void init(){       
    Container pane = getContentPane();
    pane.setLayout(borderLayoutMain);

    //borderLayoutMain centerPanel
    centerPanel = new JPanel();
    centerPanel.setLayout(null);

    currentOrder.setSize(200, 25);
    currentOrder.setLocation(100, 25);
    currentOrderTA.setSize(600, 400);
    currentOrderTA.setLocation(100, 50);
    currentOrderTA.setEditable(false);
    total.setSize(200, 25);
    totalTA.setLocation(100, 450);
    totalTA.setEditable(false);
    orderButton.setSize(100, 50);
    orderButton.setLocation(100, 500);
    resetButton.setSize(100, 50);
    resetButton.setLocation(400, 500);

    centerPanel.add(currentOrder);
    centerPanel.add(currentOrderTA);
    centerPanel.add(total);
    centerPanel.add(totalTA);
    centerPanel.add(orderButton);
    centerPanel.add(resetButton);

    pane.add(centerPanel, BorderLayout.CENTER);
}

【问题讨论】:

    标签: java jpanel japplet border-layout


    【解决方案1】:

    由于您已经取消了布局管理器 (centerPanel.setLayout(null);),BorderLayout 不再知道您的面板的大小应该是多少(因为容器的首选大小的值是由它确定的)布局管理器)

    考虑在centerPanel 上使用布局管理器,有关详细信息,请参阅Laying Out Components Within a Container

    避免使用null 布局,像素完美的布局是现代用户界面设计中的一种错觉。影响组件单个尺寸的因素太多,您无法控制。 Swing 旨在与核心的布局管理器一起工作,丢弃这些将导致无穷无尽的问题和问题,您将花费越来越多的时间来尝试纠正

    详情请见Why is it frowned upon to use a null layout in SWING?

    更新...

    当你打电话时

    pane.setLayout(borderLayoutMain);
    

    borderLayoutMainnull,因此您现在在顶级容器中有一个 null 布局。

    尝试使用...

    pane.setLayout(new BorderLayout());
    

    相反...

    【讨论】:

    • 我已将布局行更改为:centerPanel.setLayout(new GridLayout(5, 3));并注释掉 setSize 和 setLocation 行。我仍然没有看到 JApplet 中出现任何内容。我需要添加其他内容吗?
    • 添加(窗格);返回错误:java.lang.IllegalArgumentException:将容器的父级添加到自身
    • 解决了这个问题。谢谢您的帮助。对此,我真的非常感激。 :)
    • 很高兴它(最终)有所帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多