JComboBox 使用 swing 无效,打印时布局和 Apple 上的 NullPointerException 但不是 Windows

JComboBox using swing invalid,layout when printed and NullPointerException on Apple but not Windows

我正在使用 Swing 为 Java 构建一个带有 JCombobox 的简单 GUI。 GUI 在我的 PC 上加载,但在我的合作伙伴 Apple 计算机上导致 NullPointerException。

我尝试打印出 JComboBox,但收到以下 "invalid" 消息。有谁知道什么可能导致“...无效,布局...”以及为什么 JComboBox 在苹果而不是 Windows 笔记本电脑上导致 NullPointerException?

当我打印出 JComboBox 时的消息:

Jcombobox javax.swing.JComboBox[,0,0,0x0,invalid,layout=javax.swing.plaf.metal.MetalComboBoxUI$MetalComboBoxLayoutManager,alignmentX=0.0,alignmentY=0.0,border=,flags=328,maximumSize=,minimumSize=,preferredSize=,isEditable=false,lightWeightPopupEnabled=true,maximumRowCount=8,selectedItemReminder=Search your own pasted text]

当我尝试从 Oracle 的教程站点打印 JComboBox 时,我实际上发现了相同的 "invalid":https://docs.oracle.com/javase/tutorial/uiswing/examples/components/ComboBoxDemoProject/src/components/ComboBoxDemo.java [注意:通过打印出 JCombox petlist]:

  public ComboBoxDemo() {
        super(new BorderLayout());

        String[] petStrings = { "Bird", "Cat", "Dog", "Rabbit", "Pig" };

        //Create the combo box, select the item at index 4.
        //Indices start at 0, so 4 specifies the pig.
        JComboBox petList = new JComboBox(petStrings);
        petList.setSelectedIndex(4);
        petList.addActionListener(this);
        System.out.println(petList);

下面也是我们正在制作的项目的代码[只是 JComboBox 部分:

public String comboBox() {
        String str = "Search Lyric Database";
        String[] options = new String[] { "Search Lyric Database", "Search Books Database", "Search your own file", "Search website",
                "Search your own pasted text" };

        JComboBox<String> bookList = new JComboBox<>(options);
        bookList.setSelectedIndex(3);
        System.out.println("JCOMBOBOX" + bookList );

        pane.add(bookList, BorderLayout.PAGE_START);

并注意 windows 计算机输出 [打印时] 中的 "invalid"。

...javax.swing.JComboBox[,0,0,0x0,invalid,layout=javax.swing.plaf.metal.......

有谁知道"invalid"是什么意思? 有没有人知道为什么当从 Apple 计算机上单击 JCombobox 时它会导致 nullPointerException [但不会在 Windows] 上以及我们如何解决这个问题?

谢谢

"invalid" 基本上意味着 Component.isValid() returns false (https://github.com/AdoptOpenJDK/openjdk-jdk8u/blob/master/jdk/src/share/classes/java/awt/Component.java#L8134).

根据JavaDocisValid()方法

Determines whether this component is valid. A component is valid when it is correctly sized and positioned within its parent container and all its children are also valid. In order to account for peers' size requirements, components are invalidated before they are first shown on the screen. By the time the parent container is fully realized, all its components will be valid.

所以这可能只是意味着您从未将此 JComboBox 添加到容器 and/or 并且此容器从未显示过(还)。

所以这肯定不是你 NullPointerException

的原因