JTable header alignment

本秂侑毒 提交于 2019-12-01 06:54:52

问题


I would like to set the vertical alignment of the label in the header of my JTable-derrived class.

I am aware of setVerticalAlignment(SwingConstants.BOTTOM);

My header is much higher than the font and I would like to place the text slightly below the vertical centre.

How can I do this, without overriding paint() ?

THX


回答1:


one of ways is to set Renderer, TableHeader by default returns JLabel, for example

  final TableCellRenderer tcrOs = myTable.getTableHeader().getDefaultRenderer();
       myTable.getTableHeader().setDefaultRenderer(new TableCellRenderer() {

            @Override
            public Component getTableCellRendererComponent(JTable table, 
                   Object value, boolean isSelected, boolean hasFocus, 
                   int row, int column) {
                JLabel lbl = (JLabel) tcrOs.getTableCellRendererComponent(table, 
                      value, isSelected, hasFocus, row, column);
                lbl.setForeground(AppVariables.textColor);
                lbl.setBorder(BorderFactory.createCompoundBorder(lbl.getBorder(), 
                      BorderFactory.createEmptyBorder(0, 5, 0, 0)));
                lbl.setHorizontalAlignment(SwingConstants.LEFT);
                if (isSelected) {
                    lbl.setForeground(Color.red);
                    lbl.setBackground(Color.lightGray);
                } else {
                    lbl.setForeground(Color.blue);
                    lbl.setBackground(Color.black);
                }
                return lbl;
            }
        });



回答2:


JTableHeader header = table.getTableHeader();
TableCellRenderer renderer = header.getDefaultRenderer();
renderer.setVerticalAlignment(SwingConstants.BOTTOM);


来源:https://stackoverflow.com/questions/8524037/jtable-header-alignment

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