Google Tag Manager

2020/09/30

Creating StatusBar with size grips to resize the JFrame

Code

class ResizeWindowListener extends MouseInputAdapter {
  private final Rectangle rect = new Rectangle();
  private final Point startPt = new Point();

  @Override public void mousePressed(MouseEvent e) {
    Component p = SwingUtilities.getRoot(e.getComponent());
    if (p instanceof Window) {
      startPt.setLocation(e.getPoint());
      rect.setBounds(p.getBounds());
    }
  }

  @Override public void mouseDragged(MouseEvent e) {
    Component p = SwingUtilities.getRoot(e.getComponent());
    if (!rect.isEmpty() && p instanceof Window) {
      Point pt = e.getPoint();
      rect.width += pt.x - startPt.x;
      rect.height += pt.y - startPt.y;
      p.setBounds(rect);
    }
  }
}

// Size Grip
// Create a GripIcon with a JLabel and position it at the right end(BorderLayout.EAST) of the StatusBar
class BottomRightCornerLabel extends JLabel {
  private transient MouseInputListener handler;

  protected BottomRightCornerLabel() {
    super(new BottomRightCornerIcon());
  }

  @Override public void updateUI() {
    removeMouseListener(handler);
    removeMouseMotionListener(handler);
    super.updateUI();
    handler = new ResizeWindowListener();
    addMouseListener(handler);
    addMouseMotionListener(handler);
    setCursor(Cursor.getPredefinedCursor(Cursor.SE_RESIZE_CURSOR));
  }
}

// Grip Icon
// Draw six rectangles to create a Windows 10 like icon
class BottomRightCornerIcon implements Icon {
  private static final Color SQUARE_COLOR = new Color(160, 160, 160, 160);

  @Override public void paintIcon(Component c, Graphics g, int x, int y) {
    int diff = 3;
    Graphics2D g2 = (Graphics2D) g.create();
    g2.translate(getIconWidth() - diff * 3 - 1, getIconHeight() - diff * 3 - 1);

    int firstRow = 0;
    int secondRow = firstRow + diff;
    int thirdRow = secondRow + diff;

    int firstColumn = 0;
    drawSquare(g2, firstColumn, thirdRow);

    int secondColumn = firstColumn + diff;
    drawSquare(g2, secondColumn, secondRow);
    drawSquare(g2, secondColumn, thirdRow);

    int thirdColumn = secondColumn + diff;
    drawSquare(g2, thirdColumn, firstRow);
    drawSquare(g2, thirdColumn, secondRow);
    drawSquare(g2, thirdColumn, thirdRow);

    g2.dispose();
  }

  @Override public int getIconWidth() {
    return 16;
  }

  @Override public int getIconHeight() {
    return 20;
  }

  private void drawSquare(Graphics g, int x, int y) {
    g.setColor(SQUARE_COLOR);
    g.fillRect(x, y, 2, 2);
  }
}

References

No comments:

Post a Comment