java - 添加 JPanel 时 JTable 列标题消失

标签 java swing jtable jpanel jscrollpane

将我的 JTable(带有列标题的表)添加到 JScrollPane 中,两者都显示良好...

如果相同的 JTable + 一些 JPanel...都添加到主 JPanel(BorderLayout),然后将此主 JPanel 添加到 JScrollPane ....表格的列标题停止显示,而表格显示?!

知道为什么以及如何解决这个问题..

somePanel=new JPanel (new FlowLayout ());
somePanel.setPreferredSize (new Dimension (600,50));
somePanel.setBackground (Color.lightGray);

mainPane=new JPanel (new BorderLayout ());
mainPane.setPreferredSize (new Dimension (600,550));
mainPane.setBackground (Color.lightGray);
mainPane.add (somePanel,BorderLayout.NORTH);
mainPane.add (table,BorderLayout.CENTER);

scrollBar=new JscrollBar();
scrollBar.setVisible (true);
scrollBar.setVisibleAmount (10);
scrollBar.setEnabled (true);
scrollBar.setOrientation (Adjustable.VERTICAL);

scrollPane=new JScrollPane ();
scrollPane.setVerticalScrollBar (scrollBar);
scrollPane.setVerticalScrollBarPolicy 
(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setPreferredSize (new Dimension (600,650));
scrollPane.setViewportView (mainPane);



/*the createExamsSchedualTable()  is inside inner class in the Jframe 
and called by class constructor*/
private void createExamsSchedualTable(){
table=new JTable (new TheTableModel ());
table.setPreferredScrollableViewportSize (new Dimension (600,570));
table.setFillsViewportHeight (true);
table.setAutoResizeMode (JTable.AUTO_RESIZE_ALL_COLUMNS);
table.setAutoCreateRowSorter (true);
table.setSelectionBackground (Color.LIGHT_GRAY);
table.setDragEnabled (true);
table.setGridColor (Color.LIGHT_GRAY);
table.setIntercellSpacing (new Dimension (3,3));
table.setRowSelectionAllowed (true);
table.setColumnSelectionAllowed (true);
table.setCellSelectionEnabled (true);
table.setShowGrid (true);
table.setShowHorizontalLines (true);
table.setVerifyInputWhenFocusTarget (true);
table.setToolTipText ("Exams Scheduals Times Table");
}
/*TheTableModel class extends AbstractTableModel */

最佳答案

still don't know why the header disappear though !!

当您将 JTable 添加到 JScrollPane 时,JTable 的 JTableHeader 将添加到滚动 Pane 的列标题。这是JTable的特殊逻辑。

如果将 JTable 直接添加到 JPanel,则您负责在面板上显示标题。像这样的东西:

JPanel panel = new JPanel( new BorderLayout() );
panel.add(table, BorderLayout.CENTER);
panel.add(table.getTableHeader(), BorderLayout.PAGE_START);
panel.add(anotherPanel, BorderLayout.PAGE_END);

或者您可以自己将标题添加到scrollPane>

JPanel panel = new JPanel(...);
panel.add(table, ...);
panel.add(anotherPanel, ...);
JScrollPane scrollPane = new JScrollPane(panel);
scrollPane.setColumnHeaderView(table.getTableHeader());

关于java - 添加 JPanel 时 JTable 列标题消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46545202/

相关文章:

java - 为什么我们不在 getter 中使用 'this'?

java - 递归函数 : Check for palindrome in Java

java - Java 中的多个输入/输出流?

java - 使用定时器实现长按

java - 按列值动态过滤 jTable

java - 所有标签的访问者方法

java - 组件必须有一个有效的对等体 - BufferStrategy

java - 拖放 JTableHeader

java - 如何清除jtable中的数据

java - 将文件路径拖放到 Java Swing JTextField