如何将 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
(如果您设置了任何),否则它使用标签和/或图标。
关于java - 在 JTabbedPane 中设置特定选项卡的可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12181841/