Rotate a Swing JLabel

一个人想着一个人 提交于 2019-11-30 09:26:30

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;
}
Demi Ben-Ari

I don't know if it is relevant by now, But while searching for the same thing, i found a very good implementation in the web, http://macdevcenter.com/pub/a/mac/2002/03/22/vertical_text.html

Check it out, it is an implementation over the TabbedPane with vertical text, See if it suites you purposes.

I've had a play with this, it wasn't working very well initially because the label bounds were exactly square and caused components to the right of the label to shift and become obscured. But I then realised that it was because I am using JGoodies FormLayout. If you use this layout manager, make sure you set the column size to "preferred" not "default". HTH.

I think it is off because you are translating about the wrong point.

the size of the object depends on what container you have this in, so while your preferred size might be what you want, your actual size isn't?

if you have this label in the CENTER of a BorderLayout, the size is always the full size of the container (minus north+south height, minus east+west width)

so don't you have to translate about the actual size, not preferred size?

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!