为了更好的可读性,我在类中移动了一些生成 GUI 的代码。不幸的是我不得不在某个地方犯错误,因为现在我收到了这个错误:
线程“AWT-EventQueue-0”中出现异常
在java.lang.NullPointerException
:javax.swing.plaf.basic.BasicTabbedPaneUI$ScrollableTabSupport.updateView(BasicTabbedPaneUI.java
)3351
它发生在
javax/swing/plaf/basic/BasicTabbedPaneUI.java
这条线上:
private void updateView() {
ERROR HERE: int tabPlacement = tabPane.getTabPlacement();
int tabCount = tabPane.getTabCount();
这个类中有一个方法可以将
tabPane
设置为 null,但我绝对不会调用它:
public void uninstallUI(JComponent c) {
uninstallKeyboardActions();
uninstallListeners();
uninstallDefaults();
uninstallComponents();
c.setLayout(null);
this.tabPane = null;
}
我使用 TabbedWindow 类创建选项卡式 GUI:
public final JTabbedPane container;
public TabbedWindow() {
container = new JTabbedPane();
container.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
//More code but nothing with container
}
然后我将其附加到主 JPane:
public void createTabs(Container pane) {
pane.setLayout(new GridLayout(1, 1));
System.out.println("Creating tabbed window.");
TabbedWindow win = new TabbedWindow();
//Inbetween, I append some JFrames to the win.container
//Adding to main pane:
pane.add(win.container);
System.out.println("Done.");
我现在的问题是:
我无法确定真正的原因,但是
uninstallUI
已被调用,因为我在附加其他元素之前使用了
container.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
。
因为坦白说我不明白整个事情是如何运作的,所以我决定采取安全的方式:
public void close() {
container.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
closed = true;
}
调用 close 后,就不能再向 GUI 添加任何内容了。
除了 uninstallUI 之外,对外观框架的其他调用也可以删除 UI。例如updateComponentTreeUI(),可以导致所有组件更新,例如组件具有如下所示的 setUI。它将卸载并安装 UI。我猜在某些情况下稍后的安装可能会失败。
protected void setUI(ComponentUI newUI) {
/* We do not check that the UI instance is different
* before allowing the switch in order to enable the
* same UI instance *with different default settings*
* to be installed.
*/
uninstallUIAndProperties();
// aaText shouldn't persist between look and feels, reset it.
aaHint = UIManager.getDefaults().get(
RenderingHints.KEY_TEXT_ANTIALIASING);
lcdRenderingHint = UIManager.getDefaults().get(
RenderingHints.KEY_TEXT_LCD_CONTRAST);
ComponentUI oldUI = ui;
ui = newUI;
if (ui != null) {
ui.installUI(this);
}
firePropertyChange("UI", oldUI, newUI);
revalidate();
repaint();
}