Google Tag Manager

2015/12/28

Copy on select for JTextArea

Code

class CopyOnSelectListener
    extends MouseAdapter
    implements CaretListener, KeyListener {
  private boolean dragActive;
  private boolean shiftActive;
  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());
  }

  @Override public void keyPressed(KeyEvent e) {
    shiftActive = (e.getModifiersEx() & KeyEvent.SHIFT_DOWN_MASK) != 0;
  }

  @Override public void keyReleased(KeyEvent e) {
    shiftActive = (e.getModifiersEx() & KeyEvent.SHIFT_DOWN_MASK) != 0;
    if (!shiftActive) {
      fire(e.getSource());
    }
  }

  @Override public void keyTyped(KeyEvent e) {
    /* empty */
  }

  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

JTable table = new JTable(model) {
  @Override public String getToolTipText(MouseEvent e) {
    Point pt = e.getPoint();
    int vrow = rowAtPoint(pt);
    int vcol = columnAtPoint(pt);
    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);
        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

2015/10/30

Display tooltip while dragging JSlider thumb

Code

class SliderPopupListener extends MouseAdapter {
  private final JWindow toolTip = new JWindow();
  private final JLabel label = new JLabel("", SwingConstants.CENTER);
  private final Dimension size = new Dimension(30, 20);
  private int prevValue = -1;

  public SliderPopupListener() {
    label.setOpaque(false);
    label.setBackground(UIManager.getColor("ToolTip.background"));
    label.setBorder(UIManager.getBorder("ToolTip.border"));
    toolTip.add(label);
    toolTip.setSize(size);
  }

  protected void updateToolTip(MouseEvent me) {
    JSlider slider = (JSlider) me.getSource();
    int intValue = (int) slider.getValue();
    if (prevValue != intValue) {
      label.setText(String.format("%03d", slider.getValue()));
      Point pt = me.getPoint();
      pt.y = -size.height;
      SwingUtilities.convertPointToScreen(pt, (Component) me.getSource());
      pt.translate(-size.width / 2, 0);
      toolTip.setLocation(pt);
    }
    prevValue = intValue;
  }

  @Override public void mouseDragged(MouseEvent me) {
    updateToolTip(me);
  }

  @Override public void mousePressed(MouseEvent me) {
    toolTip.setVisible(true);
    updateToolTip(me);
  }

  @Override public void mouseReleased(MouseEvent me) {
    toolTip.setVisible(false);
  }
}

References

2015/09/30

Adjust the height of every row in the JTable to fit the JViewport

Code

JTable table = new JTable(model) {
  int prevHeight = -1;
  int prevCount = -1;

  public void updateRowsHeigth(JViewport vport) {
    int height = vport.getExtentSize().height;
    int rowCount = getModel().getRowCount();
    int defautlRowHeight = height / rowCount;
    if ((height != prevHeight || rowCount != prevCount) && defautlRowHeight > 0) {
      int over = height - rowCount * defautlRowHeight;
      for (int i = 0; i < rowCount; i++) {
        int a = over-- > 0 ? i == rowCount - 1 ? over : 1 : 0;
        setRowHeight(i, defautlRowHeight + a);
      }
    }
    prevHeight = height;
    prevCount = rowCount;
  }

  @Override public void doLayout() {
    super.doLayout();
    Container p = SwingUtilities.getAncestorOfClass(JViewport.class, this);
    if (p instanceof JViewport) {
      updateRowsHeigth((JViewport) p);
    }
  }
};

References

2015/08/31

Change the indeterminate JProgressBar animation patterns

Code

class StripedProgressBarUI extends BasicProgressBarUI {
  private final boolean dir;
  private final boolean slope;
  public StripedProgressBarUI(boolean dir, boolean slope) {
    super();
    this.dir = dir;
    this.slope = slope;
  }

  @Override protected int getBoxLength(
        int availableLength, int otherDimension) {
    return availableLength; // (int) Math.round(availableLength / 6d);
  }

  @Override public void paintIndeterminate(Graphics g, JComponent c) {
    if (!(g instanceof Graphics2D)) {
      return;
    }

    Insets b = progressBar.getInsets(); // area for border
    int barRectWidth  = progressBar.getWidth() - b.right - b.left;
    int barRectHeight = progressBar.getHeight() - b.top - b.bottom;

    if (barRectWidth <= 0 || barRectHeight <= 0) {
      return;
    }

    Graphics2D g2 = (Graphics2D) g;
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                        RenderingHints.VALUE_ANTIALIAS_ON);

    // Paint the striped box.
    boxRect = getBox(boxRect);
    if (boxRect != null) {
      int w = 10;
      int x = getAnimationIndex();
      GeneralPath p = new GeneralPath();
      if (dir) {
        p.moveTo(boxRect.x,           boxRect.y);
        p.lineTo(boxRect.x + w * .5f, boxRect.y + boxRect.height);
        p.lineTo(boxRect.x + w,       boxRect.y + boxRect.height);
        p.lineTo(boxRect.x + w * .5f, boxRect.y);
      } else {
        p.moveTo(boxRect.x,           boxRect.y + boxRect.height);
        p.lineTo(boxRect.x + w * .5f, boxRect.y + boxRect.height);
        p.lineTo(boxRect.x + w,       boxRect.y);
        p.lineTo(boxRect.x + w * .5f, boxRect.y);
      }
      p.closePath();
      g2.setColor(progressBar.getForeground());
      if (slope) {
        for (int i = boxRect.width + x; i > -w; i -= w) {
          g2.fill(AffineTransform.getTranslateInstance(i, 0)
                                 .createTransformedShape(p));
        }
      } else {
        for (int i = -x; i < boxRect.width; i += w) {
          g2.fill(AffineTransform.getTranslateInstance(i, 0)
                                 .createTransformedShape(p));
        }
      }
    }
  }
}

References