Google Tag Manager

2018/10/31

aterai

Create an Image Comparison Slider with JSplitPane

Code

ImageIcon icon = new ImageIcon(getClass().getResource("test.png"));

Component beforeCanvas = new JComponent() {
  @Override protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    int iw = icon.getIconWidth();
    int ih = icon.getIconHeight();
    g.drawImage(icon.getImage(), 0, 0, iw, ih, this);
  }
};
split.setLeftComponent(beforeCanvas);

Component afterCanvas = new JComponent() {
  @Override protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g.create();
    int iw = icon.getIconWidth();
    int ih = icon.getIconHeight();
    if (check.isSelected()) {
      g2.setColor(getBackground());
      g2.setXORMode(Color.BLUE);
    } else {
      g2.setPaintMode();
    }
    Point pt = getLocation();
    Insets ins = split.getBorder().getBorderInsets(split);
    g2.translate(-pt.x + ins.left, 0);
    g2.drawImage(icon.getImage(), 0, 0, iw, ih, this);
    g2.dispose();
  }
};
split.setRightComponent(afterCanvas);

References

2018/09/30

aterai

Expand the zip file selected by JFileChooser

Code

JButton button1 = new JButton("unzip");
button1.addActionListener(e -> {
  String str = field.getText();
  Path path = Paths.get(str);
  if (str.isEmpty() || Files.notExists(path)) {
    return;
  }
  String name = Objects.toString(path.getFileName());
  int lastDotPos = name.lastIndexOf('.');
  if (lastDotPos > 0) {
    name = name.substring(0, lastDotPos);
  }
  Path destDir = path.resolveSibling(name);
  try {
    if (Files.exists(destDir)) {
      String m = String.format(
          "%s already exists.
Do you want to overwrite it?", destDir.toString()); int rv = JOptionPane.showConfirmDialog( button1.getRootPane(), m, "Unzip", JOptionPane.YES_NO_OPTION); if (rv != JOptionPane.YES_OPTION) { return; } } else { if (LOGGER.isLoggable(Level.INFO)) { LOGGER.info("mkdir0: " + destDir.toString()); } Files.createDirectories(destDir); } ZipUtil.unzip(path, destDir); } catch (IOException ex) { ex.printStackTrace(); } }); // ... public static void unzip(Path zipFilePath, Path destDir) throws IOException { try (ZipFile zipFile = new ZipFile(zipFilePath.toString())) { Enumeration e = zipFile.entries(); while (e.hasMoreElements()) { ZipEntry zipEntry = e.nextElement(); String name = zipEntry.getName(); Path path = destDir.resolve(name); if (name.endsWith("/")) { // if (Files.isDirectory(path)) { log("mkdir1: " + path.toString()); Files.createDirectories(path); } else { Path parent = path.getParent(); if (Files.notExists(parent)) { log("mkdir2: " + parent.toString()); Files.createDirectories(parent); } log("copy: " + path.toString()); Files.copy(zipFile.getInputStream(zipEntry), path, StandardCopyOption.REPLACE_EXISTING); } } } } //... public static void zip(Path srcDir, Path zip) throws IOException { try (Stream s = Files.walk(srcDir).filter(Files::isRegularFile)) { List files = s.collect(Collectors.toList()); try (ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(zip))) { for (Path f: files) { String relativePath = srcDir.relativize(f).toString(); ZipEntry ze = new ZipEntry(relativePath.replace('\\', '/')); zos.putNextEntry(ze); Files.copy(f, zos); } } } }

References

2018/08/29

aterai

Change the tab of JTabbedPane to a flat design style

Code

UIManager.put("TabbedPane.tabInsets", new Insets(5, 10, 5, 10));
UIManager.put("TabbedPane.tabAreaInsets", new Insets(0, 0, 0, 0));
UIManager.put("TabbedPane.selectedLabelShift", 0);
UIManager.put("TabbedPane.labelShift", 0);

// UIManager.put("TabbedPane.foreground", Color.WHITE);
// UIManager.put("TabbedPane.selectedForeground", Color.WHITE);
// UIManager.put("TabbedPane.unselectedBackground", UNSELECTED_BG);
UIManager.put("TabbedPane.tabAreaBackground", UNSELECTED_BG);

JTabbedPane tabs = new JTabbedPane() {
  @Override public void updateUI() {
    super.updateUI();
    setUI(new BasicTabbedPaneUI() {
      @Override protected void paintFocusIndicator(
          Graphics g, int tabPlacement, Rectangle[] rects, int tabIndex,
          Rectangle iconRect, Rectangle textRect, boolean isSelected) {
        // Do not paint anything
      }
      @Override protected void paintTabBorder(
          Graphics g, int tabPlacement, int tabIndex,
          int x, int y, int w, int h, boolean isSelected) {
        // Do not paint anything
      }
      @Override  protected void paintTabBackground(
          Graphics g, int tabPlacement, int tabIndex,
          int x, int y, int w, int h, boolean isSelected) {
        g.setColor(isSelected ? SELECTED_BG : UNSELECTED_BG);
        g.fillRect(x, y, w, h);
      }
      @Override protected void paintContentBorderRightEdge(
          Graphics g, int tabPlacement, int selectedIndex,
          int x, int y, int w, int h) {
        g.setColor(SELECTED_BG);
        g.fillRect(x, y, w, h);
      }
      // ...
    });
    setOpaque(true);
    setForeground(Color.WHITE);
    setTabPlacement(SwingConstants.LEFT);
    setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
  }
};

References

2018/07/31

aterai

Syntax highlighting the source code in the JEditorPane

Code

// NG: color:#RGB
// OK: color:#RRGGBB
StyleSheet styleSheet = new StyleSheet();
styleSheet.addRule(".str {color:#008800}");
styleSheet.addRule(".kwd {color:#000088}");
styleSheet.addRule(".com {color:#880000}");
styleSheet.addRule(".typ {color:#660066}");
styleSheet.addRule(".lit {color:#006666}");
styleSheet.addRule(".pun {color:#666600}");
styleSheet.addRule(".pln {color:#000000}");
styleSheet.addRule(".tag {color:#000088}");
styleSheet.addRule(".atn {color:#660066}");
styleSheet.addRule(".atv {color:#008800}");
styleSheet.addRule(".dec {color:#660066}");

HTMLEditorKit htmlEditorKit = new HTMLEditorKit();
htmlEditorKit.setStyleSheet(styleSheet);
editor.setEditorKit(htmlEditorKit);
editor.setEditable(false);
// ...

private void loadFile(String path) {
  try (Stream<String> lines = Files.lines(
      Paths.get(path), Charset.forName("UTF-8"))) {
    String txt = lines.map(s -> s.replace("&", "&amp;")
                                 .replace("<", "&lt;")
                                 .replace(">", "&gt;"))
      .collect(Collectors.joining("\n"));
    editor.setText("<pre>" + prettify(engine, txt) + "\n</pre>");
  } catch (IOException ex) {
    ex.printStackTrace();
  }
}
private static ScriptEngine createEngine() {
  ScriptEngineManager manager = new ScriptEngineManager();
  ScriptEngine engine = manager.getEngineByName("JavaScript");
  try {
    Path path = Paths.get(MainPanel.class.getResource("prettify.js").toURI());
    try (Reader r = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
      engine.eval("var window={}, navigator=null;");
      engine.eval(r);
      return engine;
    }
  } catch (IOException | ScriptException | URISyntaxException ex) {
    ex.printStackTrace();
  }
  return null;
}
private static String prettify(ScriptEngine engine, String src) {
  try {
    Object w = engine.get("window");
    return (String) ((Invocable) engine).invokeMethod(
        w, "prettyPrintOne", src);
  } catch (ScriptException | NoSuchMethodException ex) {
    ex.printStackTrace();
    return "";
  }
}

References

2018/06/29

aterai

Move items by copying and pasting between JLists

Code

class ListPopupMenu extends JPopupMenu {
  private final JMenuItem cutItem;
  private final JMenuItem copyItem;
  protected ListPopupMenu(JList list) {
    super();
    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    TransferHandler handler = list.getTransferHandler();
    cutItem = add("cut");
    cutItem.addActionListener(e -> {
      handler.exportToClipboard(list, clipboard, TransferHandler.MOVE);
    });
    copyItem = add("copy");
    copyItem.addActionListener(e -> {
      handler.exportToClipboard(list, clipboard, TransferHandler.COPY);
    });
    add("paste").addActionListener(e -> {
      handler.importData(list, clipboard.getContents(null));
    });
    addSeparator();
    add("clearSelection").addActionListener(e -> list.clearSelection());
  }
  @Override public void show(Component c, int x, int y) {
    if (c instanceof JList) {
      boolean isSelected = !((JList) c).isSelectionEmpty();
      cutItem.setEnabled(isSelected);
      copyItem.setEnabled(isSelected);
      super.show(c, x, y);
    }
  }
}

// ...
private static int getIndex(TransferHandler.TransferSupport info) {
  JList target = (JList) info.getComponent();
  int index; // = dl.getIndex();
  if (info.isDrop()) { // Mouse Drag & Drop
    System.out.println("Mouse Drag & Drop");
    TransferHandler.DropLocation tdl = info.getDropLocation();
    if (tdl instanceof JList.DropLocation) {
      index = ((JList.DropLocation) tdl).getIndex();
    } else {
      index = target.getSelectedIndex();
    }
  } else { // Keyboard Copy & Paste
    index = target.getSelectedIndex();
  }
  DefaultListModel listModel = (DefaultListModel) target.getModel();
  // boolean insert = dl.isInsert();
  int max = listModel.getSize();
  // int index = dl.getIndex();
  index = index < 0 ? max : index; // If it is out of range, it is appended to the end
  index = Math.min(index, max);
  return index;
}

References