JTableHeader添加全选, 反选checkbox

在JTableHeader 上画了组件, 例如一个一个checkbox, 再给checkbox一个监听, 会发现checkbox的选择消息怎样也不会给触发, 这里做了一个很土的方法, 给TableHeader添加鼠标单击消息监听器.
老实说做做 SWING要做特效的时候经常要到处找, 要么就是添加新的Renderer, 新的Model, 冇法子MVC嘛.
还好做得不多.
哪位大仙要是有更好的方法, 能让TableHeader更加灵活的添加组件并且相应的, 记得回个帖. 因为这个用鼠标监听确定哪列确实应用有限.... 能够解决TableHeader能传递消息到 checkbox的监听器的话, 那肯定是对SWING很有研究的.

     
final   int  tableFirstColumn  =   0 ;
        final JTableHeader tableHeader = table.getTableHeader();
        
final JCheckBox selectBox = new JCheckBox(tblModel
                .getColumnName(tableFirstColumn));
        selectBox.setSelected(
true);
        tableHeader.setDefaultRenderer(
new TableCellRenderer() {
            
public Component getTableCellRendererComponent(JTable table,
                    Object value, 
boolean isSelected, boolean hasFocus,
                    
int row, int column) {
                String valueStr 
= (String) value;
                JLabel label 
= new JLabel(valueStr);
                label.setHorizontalAlignment(JLabel.CENTER);
                selectBox.setHorizontalAlignment(JLabel.CENTER);
                selectBox.setBorderPainted(
true);
                JComponent component 
= (column == tableFirstColumn) ? selectBox
                        : label;
                component.setForeground(tableHeader.getForeground());
                component.setBackground(tableHeader.getBackground());
                component.setFont(tableHeader.getFont());
                component.setBorder(UIManager
                        .getBorder(
"TableHeader.cellBorder"));

                
return component;

            }

        }
);
        tableHeader.addMouseListener(
new MouseListener() {
            
public void mouseClicked(MouseEvent e) {
                
if (e.getClickCount() > 0{
                    
int selectColumn = tableHeader.columnAtPoint(e.getPoint());
                    
if (selectColumn == tableFirstColumn) {
                        
boolean value = !selectBox.isSelected();
                        selectBox.setSelected(value);
                        tblModel.selectAll(value);
                        tableHeader.repaint();
                    }

                }

            }


            
public void mouseEntered(MouseEvent e) {
            }


            
public void mouseExited(MouseEvent e) {
            }


            
public void mousePressed(MouseEvent e) {
            }


            
public void mouseReleased(MouseEvent e) {
            }

        }
);
 

你可能感兴趣的:(User,Interface)