Google Tag Manager

2015/12/28

Copy on select for JTextArea

Code

class CopyOnSelectListener extends MouseAdapter implements CaretListener {
  private boolean dragActive;
  private int dot;
  private int mark;
  @Override public final void caretUpdate(CaretEvent e) {
    if (!dragActive) {
      fire(e.getSource());
    }
  }
  @Override public final void mousePressed(MouseEvent e) {
    dragActive = true;
  }
  @Override public final void mouseReleased(MouseEvent e) {
    dragActive = false;
    fire(e.getSource());
  }
  private void fire(Object c) {
    if (c instanceof JTextComponent) {
      JTextComponent tc = (JTextComponent) c;
      Caret caret = tc.getCaret();
      int d = caret.getDot();
      int m = caret.getMark();
      if (d != m && (dot != d || mark != m)) {
        String str = tc.getSelectedText();
        if (Objects.nonNull(str)) {
          //StringSelection data = new StringSelection(str);
          //Toolkit tk = Toolkit.getDefaultToolkit();
          //tk.getSystemClipboard().setContents(data, data);
          tc.copy();
        }
      }
      dot = d;
      mark = m;
    }
  }
}

References

2015/12/01

Show JToolTip for Icons placed in the cell of the JTable

Code

private final JTable table = new JTable(model) {
  @Override public String getToolTipText(MouseEvent e) {
    Point pt = e.getPoint();
    int vrow = rowAtPoint(pt);
    int vcol = columnAtPoint(pt);
    //int mrow = convertRowIndexToModel(vrow);
    int mcol = convertColumnIndexToModel(vcol);
    if (mcol == 1) {
      TableCellRenderer tcr = getCellRenderer(vrow, vcol);
      Component c = prepareRenderer(tcr, vrow, vcol);
      if (c instanceof JPanel) {
        Rectangle r = getCellRect(vrow, vcol, true);
        c.setBounds(r);
        //@see https://stackoverflow.com/questions/10854831/tool-tip-in-jpanel-in-jtable-not-working
        c.doLayout();
        pt.translate(-r.x, -r.y);
        Component l = SwingUtilities.getDeepestComponentAt(c, pt.x, pt.y);
        if (l instanceof JLabel) {
          ImageIcon icon = (ImageIcon)((JLabel) l).getIcon();
          return icon.getDescription();
        }
      }
    }
    return super.getToolTipText(e);
  }
};
class ListIconRenderer implements TableCellRenderer {
  private final JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT));
  @Override public Component getTableCellRendererComponent(
      JTable table, Object value,
      boolean isSelected, boolean hasFocus, int row, int column) {
    p.removeAll();
    if (isSelected) {
      p.setOpaque(true);
      p.setBackground(table.getSelectionBackground());
    } else {
      p.setOpaque(false);
    }
    if (value instanceof List) {
      for (Object o : (List) value) {
        if (o instanceof Icon) {
          Icon icon = (Icon) o;
          JLabel label = new JLabel(icon);
          label.setToolTipText(icon.toString());
          p.add(label);
        }
      }
    }
    return p;
  }
}

References