Rotate a Swing JLabel

后端 未结 4 1498
走了就别回头了
走了就别回头了 2020-12-31 20:42

I am currently trying to implement a Swing component, inheriting from JLabel which should simply represent a label that can be oriented vertically.

Begi

4条回答
  •  北海茫月
    2020-12-31 21:03

    I got it to work now with a little help of a coworker. Basically I now have a field that indicates whether to swap height/width which is only active for the time when the original JLabel does its painting.

    private boolean needsRotate;
    
    @Override
    public Dimension getSize() {
      if (!needsRotate) {
        return super.getSize();
      }
    
      Dimension size = super.getSize();
    
      switch (getDirection()) {
      case VERTICAL_DOWN:
      case VERTICAL_UP:
          return new Dimension(size.height, size.width);
      default:
        return super.getSize();
      }
    }
    
    @Override
    public int getHeight() {
      return getSize().height;
    }
    
    @Override
    public int getWidth() {
      return getSize().width;
    }
    
    @Override
    protected void paintComponent(Graphics g) {
      Graphics2D gr = (Graphics2D) g.create();
    
      switch (getDirection()) {
      case VERTICAL_UP:
        gr.translate(0, getSize().getHeight());
        gr.transform(AffineTransform.getQuadrantRotateInstance(-1));
        break;
      case VERTICAL_DOWN:
        gr.transform(AffineTransform.getQuadrantRotateInstance(1));
        gr.translate(0, -getSize().getWidth());
        break;
      default:
      }
    
      needsRotate = true;
      super.paintComponent(gr);
      needsRotate = false;
    }
    

提交回复
热议问题