Google Tag Manager

Showing posts with label JLayer. Show all posts
Showing posts with label JLayer. Show all posts

2016/03/03

aterai

Validating input on an editable JComboBox with InputVerifier and JLayer

Code

JComboBox comboBox = new JComboBox(model) {
  @Override public void updateUI() {
    getActionMap().put(ENTER_PRESSED, null);
    super.updateUI();
    final JComboBox cb = this;
    final Action defalutEnterPressedAction = getActionMap().get(ENTER_PRESSED);
    getActionMap().put(ENTER_PRESSED, new AbstractAction() {
      @Override public void actionPerformed(ActionEvent e) {
        boolean isPopupVisible = isPopupVisible();
        setPopupVisible(false);
        DefaultComboBoxModel m = (DefaultComboBoxModel) getModel();
        String str = Objects.toString(getEditor().getItem(), "");
        if (m.getIndexOf(str) < 0 && getInputVerifier().verify(cb)) {
          m.removeElement(str);
          m.insertElementAt(str, 0);
          if (m.getSize() > 10) {
            m.removeElementAt(10);
          }
          setSelectedIndex(0);
          setPopupVisible(isPopupVisible);
        } else {
          defalutEnterPressedAction.actionPerformed(e);
        }
      }
    });
  }
};
comboBox.setEditable(true);
comboBox.setInputVerifier(new LengthInputVerifier());
comboBox.setEditor(new BasicComboBoxEditor() {
  private Component editorComponent;
  @Override public Component getEditorComponent() {
    if (editorComponent == null) {
      JTextComponent tc = (JTextComponent) super.getEditorComponent();
      editorComponent = new JLayer(tc, new ValidationLayerUI());
    }
    return editorComponent;
  }
});

class LengthInputVerifier extends InputVerifier {
  private static final int MAX_LEN = 6;
  @Override public boolean verify(JComponent c) {
    if (c instanceof JComboBox) {
      JComboBox cb = (JComboBox) c;
      String str = Objects.toString(cb.getEditor().getItem(), "");
      return MAX_LEN - str.length() >= 0;
    }
    return false;
  }
}

References

2014/09/01

aterai

Forward a mouse wheel scroll event in nested JScrollPane to the parent JScrollPane

Code

class WheelScrollLayerUI extends LayerUI {
  @Override public void installUI(JComponent c) {
    super.installUI(c);
    if (c instanceof JLayer) {
      ((JLayer) c).setLayerEventMask(AWTEvent.MOUSE_WHEEL_EVENT_MASK);
    }
  }
  @Override public void uninstallUI(JComponent c) {
    if (c instanceof JLayer) {
      ((JLayer) c).setLayerEventMask(0);
    }
    super.uninstallUI(c);
  }
  @Override protected void processMouseWheelEvent(
      MouseWheelEvent e, JLayer l) {
    Component c = e.getComponent();
    int dir = e.getWheelRotation();
    JScrollPane main = l.getView();
    if (c instanceof JScrollPane && !c.equals(main)) {
      JScrollPane child = (JScrollPane) c;
      BoundedRangeModel m = child.getVerticalScrollBar().getModel();
      int extent  = m.getExtent();
      int minimum = m.getMinimum();
      int maximum = m.getMaximum();
      int value   = m.getValue();
      if (value + extent >= maximum && dir > 0 || value <= minimum && dir < 0) {
        main.dispatchEvent(SwingUtilities.convertMouseEvent(c, e, main));
      }
    }
  }
}

References

2014/07/23

aterai

Highlight all search pattern matches in the JTextArea

Code

private Pattern getPattern() {
  String text = field.getText();
  if (text == null || text.isEmpty()) {
    return null;
  }
  try {
    String cw = checkWord.isSelected() ? "\\b" : "";
    String pattern = String.format("%s%s%s", cw, text, cw);
    int flags = checkCase.isSelected()
      ? 0
      : Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE;
    return Pattern.compile(pattern, flags);
  } catch (PatternSyntaxException ex) {
    field.setBackground(WARNING_COLOR);
    return null;
  }
}

private void changeHighlight() {
  field.setBackground(Color.WHITE);
  Highlighter highlighter = textArea.getHighlighter();
  highlighter.removeAllHighlights();
  Document doc = textArea.getDocument();
  try {
    Pattern pattern = getPattern();
    if (pattern != null) {
      Matcher matcher = pattern.matcher(doc.getText(0, doc.getLength()));
      int pos = 0;
      while (matcher.find(pos)) {
        int start = matcher.start();
        int end   = matcher.end();
        highlighter.addHighlight(start, end, highlightPainter);
        pos = end;
      }
    }
    JLabel label = layerUI.hint;
    Highlighter.Highlight[] array = highlighter.getHighlights();
    int hits = array.length;
    if (hits == 0) {
      current = -1;
      label.setOpaque(true);
    } else {
      current = (current + hits) % hits;
      label.setOpaque(false);
      Highlighter.Highlight hh = highlighter.getHighlights()[current];
      highlighter.removeHighlight(hh);
      highlighter.addHighlight(
          hh.getStartOffset(), hh.getEndOffset(), currentPainter);
      scrollToCenter(textArea, hh.getStartOffset());
    }
    label.setText(String.format("%02d / %02d%n", current + 1, hits));
  } catch (BadLocationException e) {
    e.printStackTrace();
  }
  field.repaint();
}

References

2013/06/28

aterai

Turn the JProgressBar red with JLayer and RGBImageFilter

Code

class BlockedColorLayerUI extends LayerUI{
  public boolean isPreventing = false;
  private BufferedImage bi;
  private int prevw = -1;
  private int prevh = -1;
  @Override public void paint(Graphics g, JComponent c) {
    if(isPreventing) {
      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()));
      //BUG: cause an infinite repaint loop: g.drawImage(image, 0, 0, c);
      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 & 0xff000000) | (g<<16) | (r<<8) | (b);
  }
}

References

2012/01/25

aterai

Sharing tabs between 2 JFrames

Code

//Display "DropLocation" using JLayer 
class DropLocationLayerUI extends LayerUI {
  private static final int LINEWIDTH = 3;
  private final Rectangle lineRect = new Rectangle();
  @Override public void paint(Graphics g, JComponent c) {
    super.paint (g, c);
    JLayer layer = (JLayer)c;
    DnDTabbedPane tabbedPane = (DnDTabbedPane)layer.getView();
    DnDTabbedPane.DropLocation loc = tabbedPane.getDropLocation();
    if(loc != null && loc.isDropable() && loc.getIndex()>=0) {
      int index = loc.getIndex();
      boolean isZero = index==0;
      Rectangle r = tabbedPane.getBoundsAt(isZero?0:index-1);
      if(tabbedPane.getTabPlacement()==JTabbedPane.TOP ||
         tabbedPane.getTabPlacement()==JTabbedPane.BOTTOM) {
        lineRect.setRect(
            r.x-LINEWIDTH/2+r.width*(isZero?0:1), r.y,LINEWIDTH,r.height);
      }else{
        lineRect.setRect(
            r.x,r.y-LINEWIDTH/2+r.height*(isZero?0:1), r.width,LINEWIDTH);
      }
      Graphics2D g2 = (Graphics2D)g.create();
      g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));
      g2.setColor(Color.RED);
      g2.fill(lineRect);
      g2.dispose();
    }
  }
}
private final JLabel label = new JLabel() {
// https://free-the-pixel.blogspot.com/2010/04/ghost-drag-and-drop-over-multiple.html
// Free the pixel: GHOST drag and drop, over multiple windows]
  @Override public boolean contains(int x, int y) {
    return false;
  }
};
private final JWindow dialog = new JWindow();
public TabTransferHandler() {
  dialog.add(label);
  //dialog.setAlwaysOnTop(true); // Web Start
  dialog.setOpacity(0.5f);
  //com.sun.awt.AWTUtilities.setWindowOpacity(dialog, 0.5f); // JDK 1.6.0
  DragSource.getDefaultDragSource().addDragSourceMotionListener(
      new DragSourceMotionListener() {
    @Override public void dragMouseMoved(DragSourceDragEvent dsde) {
      Point pt = dsde.getLocation();
      pt.translate(5, 5); // offset
      dialog.setLocation(pt);
    }
  });
//...

References