【问题标题】:Exception in thread "main" java.awt.AWTError: BoxLayout can't be shared线程“主”java.awt.AWTError 中的异常:无法共享 BoxLayout
【发布时间】:2011-09-15 14:42:59
【问题描述】:

我在这段代码中遇到了这个错误:

    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

【问题讨论】:

    标签: java swing


    【解决方案1】:

    您的问题来自以下行(所有其他行看起来都一样):

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

    new BoxLayout(...) 被调用时,pnlLabels 仍然是null,因为它还没有被分配。正确的做法是分两步:

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

    问题应该会消失(前提是您对与该代码行类似的所有其他代码行都这样做了)。

    【讨论】:

    • 1+ 比我快 20 秒。 :)
    猜你喜欢
    • 2019-04-06
    • 2014-12-25
    • 1970-01-01
    • 2016-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-20
    相关资源
    最近更新 更多