java - 在 JTabbedPane 中设置特定选项卡的可见性

标签 java swing nullpointerexception visibility jtabbedpane

如何将 JTabbedPane 中的某些选项卡设置为不可见?我尝试使用 JTabbedPane#getTabComponentAt(index).setVisible(false);,但它抛出一个 NullPointerException。我可以禁用选项卡,但不能使它们不可见。

中南合作:

import java.awt.Dimension;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTabbedPane;

public class Main {
    public static void main(String[] args) {
        JTabbedPane tabbedPane = new JTabbedPane();
        tabbedPane.setPreferredSize(new Dimension(400, 100));
        for (int i = 0; i < 7; i++)
            tabbedPane.add("tab " + i, new JLabel("content " + i));

        // this throws a NullPointerException
        tabbedPane.getTabComponentAt(1).setVisible(false);
        // this works
        tabbedPane.setEnabledAt(1, false);

        JFrame frame = new JFrame();
        frame.setContentPane(tabbedPane);
        frame.pack();
        frame.setVisible(true);
    }
}

我找不到我做错了什么。

最佳答案

查看对应setter的javadoc:

Sets the component that is responsible for rendering the title for the specified tab. A null value means JTabbedPane will render the title and/or icon for the specified tab. A non-null value means the component will render the title and JTabbedPane will not render the title and/or icon.

因此 JTabbedPane#getTabComponentAt(index) 方法返回用于呈现选项卡的 Component(如果您设置了任何),否则它使用标签和/或图标。

不确定是否可以让选项卡不可见,但绝对可以remove他们和insert他们。这可能是一个可接受的解决方案

关于java - 在 JTabbedPane 中设置特定选项卡的可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12181841/

相关文章:

java - 我在 java 程序中遇到 NullPointerException

Android - 如何覆盖 "Back"按钮,使其不会完成()我的 Activity ?

java - 显示 imageview onclick 并发布,如果为空则不显示 imageview

java - 为什么我的 Java 程序在尝试使用 SSL 从 Twitch.tv API 获取 token 时挂起?

java - 寻找一种有效的方法来对 3D 数组的周围值求和

java - 如何将随机 int 分配给 JButton

java - Micrometer 库是否支持 OpenTsdb 作为监控系统?

java - 为什么这三个使用 GridBagLayout 的面板使用不同的额外空间,以及如何使它们统一

java - 嵌套 GridBagLayout - 如何将子级的列与父级的列对齐

java - "NullPointerException"对双链表进行排序时