繁体   English   中英

线程“main”java.awt.AWTError中的异常:BoxLayout无法共享

[英]Exception in thread “main” java.awt.AWTError: BoxLayout can't be shared

我在这段代码上收到此错误:

    super("Trace Masker");
    setLayout(new BoxLayout(getContentPane(), BoxLayout.PAGE_AXIS));

    label1 = new JLabel("Source directory:");
    label2 = new JLabel("Target directory:");
    label3 = new JLabel("Defect number:");
    label4 = new JLabel("Slice tokens:");
    label4.setToolTipText("Seperate multiple tokens with comma");

    txtSourceDirectory = new JTextField(30);
    txtTargetDirectory = new JTextField(30);
    txtDefectNumber = new JTextField(30);
    txtSliceTokens = new JTextField(30);

    btnBrowseSourceDirectory = new JButton("...");
    btnBrowseTargetDirectory = new JButton("...");
    btnStart = new JButton("Start");
    btnCancel = new JButton("Cancel");

    pnlLabels = new JPanel(new BoxLayout(pnlLabels, BoxLayout.PAGE_AXIS));
    pnlText = new JPanel(new BoxLayout(pnlText, BoxLayout.PAGE_AXIS));
    pnlBrowseButtons = new JPanel(new BoxLayout(pnlBrowseButtons, BoxLayout.PAGE_AXIS));
    pnlTop = new JPanel(new BoxLayout(pnlTop, BoxLayout.LINE_AXIS));
    pnlActionButtons = new JPanel(new FlowLayout(FlowLayout.RIGHT));

    pnlLabels.add(label1);
    pnlLabels.add(label2);
    pnlLabels.add(label3);
    pnlLabels.add(label4);

    pnlText.add(txtSourceDirectory);
    pnlText.add(txtTargetDirectory);
    pnlText.add(txtDefectNumber);
    pnlText.add(txtSliceTokens);

    pnlBrowseButtons.add(btnBrowseSourceDirectory);
    pnlBrowseButtons.add(btnBrowseTargetDirectory);

    pnlTop.add(pnlLabels);
    pnlTop.add(pnlText);
    pnlTop.add(pnlBrowseButtons);

    pnlActionButtons.add(btnStart);
    pnlActionButtons.add(btnCancel);

    add(pnlTop);
    add(pnlActionButtons);

错误在这一行:

pnlLabels.add(label1);

只是为了检查这是否与pnlLabels有关,我评论了它的所有行。 然后错误发生在:

pnlText.add(txtSourceDirectory);

我已经在这里检查了其他2个问题并修复了JFrame的setLayout声明: Question1 Question2

您的问题来自以下行(以及所有其他行看起来相同):

pnlLabels = new JPanel(new BoxLayout(pnlLabels, BoxLayout.PAGE_AXIS));

当调用new BoxLayout(...)pnlLabels仍为null因为它尚未分配。 正确的方法分为两步:

pnlLabels = new JPanel();
pnlLabels.setLayout(new BoxLayout(pnlLabels, BoxLayout.PAGE_AXIS);

问题应该消失(假设您对所有其他类似的代码行执行此操作)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM