Setting JTableHeader holder background colour

拟墨画扇 提交于 2019-12-02 00:07:06

Well as I expected we need to set the parent of the header to be the background color you want.

However the scroll pane is NOT the parent of the header as I expected.

When I added code like the following:

System.out.println( header.getParent() );

it showed a JViewport as the parent which confused me.

However when I added:

System.out.println( scroll.getViewport() );

I noticed that the two viewports were different. So it appears the viewport of the scrollpane is different than the viewport of the header.

so the solution to the problem is:

JTableHeader header = table.getTableHeader();
header.setBackground(Color.GREEN); 

and then AFTER the frame is visible you can do:

header.getParent().setBackground(Color.YELLOW);

(I used different colors just to show the effects of each statement)

Note the header is not added to the scrollpane until the frame is packed or made visible. If you try to set the background when the table is created you will get a NPE when trying to access the parent.

Or another option is to add an AncestorListener to the JTableHeader. Then the code can be invoked then header is added to a visible frame. For this type of approach check out the Request Focus Listener found in Dialog Focus

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!