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

7

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

    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);

我已经检查了这里的其他两个关于此问题的问题,并为JFrame修复了setLayout声明: 问题1 问题2

1个回答

12

你的问题来自以下代码行(以及所有其他相似的代码行):

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

在调用new BoxLayout(...)时,pnlLabels仍然为null,因为它尚未被分配。 正确的方法是分两步进行:

pnlLabels = new JPanel();
pnlLabels.setLayout(new BoxLayout(pnlLabels, BoxLayout.PAGE_AXIS);
问题应该会消失(只要您对所有类似于那一行的代码进行相同的操作)。

2
1+ 比我快了20秒。 :) - Hovercraft Full Of Eels

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接