Google Tag Manager

2013/09/12

How to sort JTree nodes

Code

public static void sortTree(DefaultMutableTreeNode root) {
  Enumeration e = root.depthFirstEnumeration();
  while (e.hasMoreElements()) {
    DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.nextElement();
    if (!node.isLeaf()) {
      sort2(node);    // selection sort
      // sort3(node); // JDK 1.6.0: iterative merge sort
      // sort3(node); // JDK 1.7.0: TimSort
    }
  }
}

public static Comparator<DefaultMutableTreeNode> tnc = new Comparator<DefaultMutableTreeNode>() {
  @Override public int compare(DefaultMutableTreeNode a, DefaultMutableTreeNode b) {
    // ...
  }
};
// JDK 1.8.0
// a lambda expression Comparator
// Comparator< DefaultMutableTreeNode> tnc = Comparator.comparing(DefaultMutableTreeNode::isLeaf)
//                                                     .thenComparing(n -> n.getUserObject().toString());
// selection sort
public static void sort2(DefaultMutableTreeNode parent) {
  int n = parent.getChildCount();
  for (int i = 0; i < n - 1; i++) {
    int min = i;
    for (int j = i + 1; j < n; j++) {
      if (tnc.compare((DefaultMutableTreeNode) parent.getChildAt(min),
                      (DefaultMutableTreeNode) parent.getChildAt(j)) > 0) {
        min = j;
      }
    }
    if (i != min) {
      MutableTreeNode a = (MutableTreeNode) parent.getChildAt(i);
      MutableTreeNode b = (MutableTreeNode) parent.getChildAt(min);
      parent.insert(b, i);
      parent.insert(a, min);
    }
  }
}
public static void sort3(DefaultMutableTreeNode parent) {
  int n = parent.getChildCount();
  // @SuppressWarnings("unchecked")
  // Enumeration<DefaultMutableTreeNode> e = parent.children();
  // ArrayList<DefaultMutableTreeNode> children = Collections.list(e);
  List<DefaultMutableTreeNode> children = new ArrayList<>(n);
  for (int i = 0; i < n; i++) {
    children.add((DefaultMutableTreeNode) parent.getChildAt(i));
  }
  Collections.sort(children, tnc); // using Arrays.sort(...)
  parent.removeAllChildren();
  for (MutableTreeNode node: children) {
    parent.add(node);
  }
}

References

2013/08/29

Create 9-slice scaling image JButton

Code

class NineSliceScalingIcon implements Icon {
  private final BufferedImage image;
  private final int leftw;
  private final int rightw;
  private final int toph;
  private final int bottomh;
  private int width;
  private int height;
  protected NineSliceScalingIcon(
      BufferedImage image, int leftw, int rightw, int toph, int bottomh) {
    this.image = image;
    this.leftw = leftw;
    this.rightw = rightw;
    this.toph = toph;
    this.bottomh = bottomh;
  }

  @Override public int getIconWidth() {
    return width; // Math.max(image.getWidth(null), width);
  }

  @Override public int getIconHeight() {
    return Math.max(image.getHeight(null), height);
  }

  @Override public void paintIcon(Component cmp, Graphics g, int x, int y) {
    Graphics2D g2 = (Graphics2D) g.create();
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                        RenderingHints.VALUE_ANTIALIAS_ON);
    Insets i = cmp instanceof Container ? ((Container) cmp).getInsets()
                                        : new Insets(0, 0, 0, 0);
    // g2.translate(x, y); // 1.8.0: work fine?
    int iw = image.getWidth(cmp);
    int ih = image.getHeight(cmp);
    width  = cmp.getWidth() - i.left - i.right;
    height = cmp.getHeight() - i.top - i.bottom;

    g2.drawImage(
        image.getSubimage(leftw, toph, iw - leftw - rightw, ih - toph - bottomh),
        leftw, toph, width - leftw - rightw, height - toph - bottomh, cmp);
    if (leftw > 0 && rightw > 0 && toph > 0 && bottomh > 0) {
      g2.drawImage(image.getSubimage(leftw, 0, iw - leftw - rightw, toph),
                   leftw, 0, width - leftw - rightw, toph, cmp);
      g2.drawImage(image.getSubimage(leftw, ih - bottomh, iw - leftw - rightw, bottomh),
                   leftw, height - bottomh, width - leftw - rightw, bottomh, cmp);
      g2.drawImage(image.getSubimage(0, toph, leftw, ih - toph - bottomh),
                   0, toph, leftw, height - toph - bottomh, cmp);
      g2.drawImage(image.getSubimage(iw - rightw, toph, rightw, ih - toph - bottomh),
                   width - rightw, toph, rightw, height - toph - bottomh, cmp);

      g2.drawImage(image.getSubimage(0, 0, leftw, toph),
                   0, 0, cmp);
      g2.drawImage(image.getSubimage(iw - rightw, 0, rightw, toph),
                   width - rightw, 0, cmp);
      g2.drawImage(image.getSubimage(0, ih - bottomh, leftw, bottomh),
                   0, height - bottomh, cmp);
      g2.drawImage(image.getSubimage(iw - rightw, ih - bottomh, rightw, bottomh),
                   width - rightw, height - bottomh, cmp);
    }
    g2.dispose();
  }
}

References

2013/07/29

JTable highlighting and filtering with regular expression

Code

class HighlightTableCellRenderer
    extends JTextField implements TableCellRenderer {
  private static final Color BGC= new Color(220, 240, 255);
  private final transient Highlighter.HighlightPainter highlightPainter
    = new DefaultHighlighter.DefaultHighlightPainter(Color.YELLOW);
  private String pattern = "";
  private String prev;

  public boolean setPattern(String str) {
    if (str == null || str.equals(pattern)) {
      return false;
    } else {
      prev = pattern;
      pattern = str;
      return true;
    }
  }

  public HighlightTableCellRenderer() {
    super();
    setOpaque(true);
    setBorder(BorderFactory.createEmptyBorder());
    setForeground(Color.BLACK);
    setBackground(Color.WHITE);
    setEditable(false);
  }

  @Override public Component getTableCellRendererComponent(
      JTable table, Object value, boolean isSelected,
      boolean hasFocus, int row, int column) {
    String txt = Objects.toString(value, "");
    Highlighter highlighter = getHighlighter();
    highlighter.removeAllHighlights();
    setText(txt);
    setBackground(isSelected ? BGC : Color.WHITE);
    if (pattern != null && !pattern.isEmpty() && !pattern.equals(prev)) {
      Matcher matcher = Pattern.compile(pattern).matcher(txt);
      int pos = 0;
      while (matcher.find(pos) && !matcher.group().isEmpty()) {
        int start = matcher.start();
        int end   = matcher.end();
        try {
          highlighter.addHighlight(start, end, highlightPainter);
        } catch (BadLocationException | PatternSyntaxException e) {
          e.printStackTrace();
        }
        pos = end;
      }
    }
    return this;
  }
}

References

2013/06/28

Turn the JProgressBar red with JLayer and RGBImageFilter

Code

class BlockedColorLayerUI extends LayerUI<JProgressBar> {
  public boolean isPreventing;
  private transient BufferedImage bi;
  private int prevw = -1;
  private int prevh = -1;

  @Override public void paint(Graphics g, JComponent c) {
    if (isPreventing && c instanceof JLayer) {
      JLayer jlayer = (JLayer) c;
      JProgressBar progress = (JProgressBar) jlayer.getView();
      int w = progress.getSize().width;
      int h = progress.getSize().height;

      if (bi == null || w != prevw || h != prevh) {
        bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
      }
      prevw = w;
      prevh = h;

      Graphics2D g2 = bi.createGraphics();
      super.paint(g2, c);
      g2.dispose();

      Image image = c.createImage(new FilteredImageSource(
          bi.getSource(), new RedGreenChannelSwapFilter()));
      g.drawImage(image, 0, 0, null);
    } else {
      super.paint(g, c);
    }
  }
}

class RedGreenChannelSwapFilter extends RGBImageFilter {
  @Override public int filterRGB(int x, int y, int argb) {
    int r = (int) ((argb >> 16) & 0xFF);
    int g = (int) ((argb >> 8) & 0xFF);
    int b = (int) (argb & 0xFF);
    return (argb & 0xFF_00_00_00) | (g << 16) | (r << 8) | (b);
  }
}

References

2013/05/29

Column spanning TableCellRenderer

Code

class ColumnSpanningCellRenderer extends JPanel implements TableCellRenderer {
  private static final int TARGET_COLIDX = 0;
  private final JTextArea textArea = new JTextArea(2, 999999);
  private final JLabel label = new JLabel();
  private final JLabel iconLabel = new JLabel();
  private final JScrollPane scroll = new JScrollPane(textArea);

  protected ColumnSpanningCellRenderer() {
    super(new BorderLayout());

    scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
    scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    scroll.setBorder(BorderFactory.createEmptyBorder());
    scroll.setViewportBorder(BorderFactory.createEmptyBorder());
    scroll.setOpaque(false);
    scroll.getViewport().setOpaque(false);

    textArea.setBorder(BorderFactory.createEmptyBorder());
    textArea.setMargin(new Insets(0, 0, 0, 0));
    textArea.setForeground(Color.RED);
    textArea.setEditable(false);
    textArea.setFocusable(false);
    textArea.setOpaque(false);

    iconLabel.setBorder(BorderFactory.createEmptyBorder(0, 4, 0, 4));
    iconLabel.setOpaque(false);

    Border b1 = BorderFactory.createEmptyBorder(2, 2, 2, 2);
    Border b2 = BorderFactory.createMatteBorder(0, 0, 1, 1, Color.GRAY);
    label.setBorder(BorderFactory.createCompoundBorder(b2, b1));

    setBackground(textArea.getBackground());
    setOpaque(true);
    add(label, BorderLayout.NORTH);
    add(scroll);
  }
  @Override public Component getTableCellRendererComponent(
      JTable table, Object value, boolean isSelected,
      boolean hasFocus, int row, int column) {
    OptionPaneDescription d;
    if (value instanceof OptionPaneDescription) {
      d = (OptionPaneDescription) value;
      add(iconLabel, BorderLayout.WEST);
    } else {
      String title = Objects.toString(value, "");
      int mrow = table.convertRowIndexToModel(row);
      Object o = table.getModel().getValueAt(mrow, 0);
      if (o instanceof OptionPaneDescription) {
        OptionPaneDescription t = (OptionPaneDescription) o;
        d = new OptionPaneDescription(title, t.icon, t.text);
      } else {
        d = new OptionPaneDescription(title, null, "");
      }
      remove(iconLabel);
    }
    label.setText(d.title);
    textArea.setText(d.text);
    iconLabel.setIcon(d.icon);

    Rectangle cr = table.getCellRect(row, column, false);
    if (column != TARGET_COLIDX) {
      cr.x -= iconLabel.getPreferredSize().width;
    }
    scroll.getViewport().setViewPosition(cr.getLocation());

    if (isSelected) {
      setBackground(Color.ORANGE);
    } else {
      setBackground(Color.WHITE);
    }
    return this;
  }
}

class OptionPaneDescription {
  public final String title;
  public final Icon icon;
  public final String text;
  protected OptionPaneDescription(String title, Icon icon, String text) {
    this.title = title;
    this.icon  = icon;
    this.text  = text;
  }
}

References