Google Tag Manager

2011/05/24

aterai

Change border of focused row in JTable

Code

class DotBorder extends EmptyBorder {
  public enum Type { START, END; }
  private static final BasicStroke dashed = new BasicStroke(
    1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER,
    10.0f, (new float[] {1.0f}), 0.0f);
  private static final Color dotColor = new Color(200,150,150);
  public DotBorder(int top, int left, int bottom, int right) {
    super(top, left, bottom, right);
  }
  public EnumSet type = EnumSet.noneOf(Type.class);
  @Override public boolean isBorderOpaque() {
    return true;
  }
  @Override public void paintBorder(
        Component c, Graphics g, int x, int y, int w, int h) {
    Graphics2D g2 = (Graphics2D)g;
    g2.translate(x,y);
    g2.setPaint(dotColor);
    g2.setStroke(dashed);
    if(type.contains(Type.START)) {
      g2.drawLine(0,0,0,h);
    }
    if(type.contains(Type.END)) {
      g2.drawLine(w-1,0,w-1,h);
    }
    if(c.getBounds().x%2==0) {
      g2.drawLine(0,0,w,0);
      g2.drawLine(0,h-1,w,h-1);
    }else{
      g2.drawLine(1,0,w,0);
      g2.drawLine(1,h-1,w,h-1);
    }
    g2.translate(-x,-y);
  }
}

//......
UIManager.put("Table.focusCellHighlightBorder", new DotBorder(2,2,2,2));
JTable table = new JTable(model) {
  private final DotBorder dotBorder = new DotBorder(2,2,2,2);
  private final Border emptyBorder  = BorderFactory.createEmptyBorder(2,2,2,2);
  private void updateBorderType(DotBorder border, int column) {
    border.type = EnumSet.noneOf(DotBorder.Type.class);
    if(column==0) border.type.add(DotBorder.Type.START);
    if(column==getColumnCount()-1) border.type.add(DotBorder.Type.END);
  }
  @Override public Component prepareRenderer(
      TableCellRenderer tcr, int row, int column) {
    Component c = super.prepareRenderer(tcr, row, column);
    if(row==getSelectionModel().getLeadSelectionIndex()) {
      ((JComponent)c).setBorder(dotBorder);
      updateBorderType(dotBorder, column);
    }else{
      ((JComponent)c).setBorder(emptyBorder);
    }
    return c;
  }
  @Override public Component prepareEditor(
      TableCellEditor editor, int row, int column) {
    Component c = super.prepareEditor(editor, row, column);
    if(c instanceof JCheckBox) {
      JCheckBox b = (JCheckBox)c;
      //System.out.println(b.getBorder());
      //b.setBorder(dotBorder);
      updateBorderType((DotBorder)b.getBorder(), column);
      b.setBorderPainted(true);
      b.setBackground(getSelectionBackground());
    }
    return c;
  }
};

References

No comments:

Post a Comment