旋转Swing JLabel [英] Rotate a Swing JLabel
问题描述
我目前正在尝试实现一个Swing组件,继承自 JLabel
,它应该只代表一个可以垂直定向的标签。
I am currently trying to implement a Swing component, inheriting from JLabel
which should simply represent a label that can be oriented vertically.
从这开始:
public class RotatedLabel extends JLabel {
public enum Direction {
HORIZONTAL,
VERTICAL_UP,
VERTICAL_DOWN
}
private Direction direction;
我认为改变 getPreferredSize的结果是个不错的主意( )
:
@Override
public Dimension getPreferredSize() {
// swap size for vertical alignments
switch (getDirection()) {
case VERTICAL_UP:
case VERTICAL_DOWN:
return new Dimension(super.getPreferredSize().height, super
.getPreferredSize().width);
default:
return super.getPreferredSize();
}
}
然后只需转换在我将绘画卸载到原始
对象: JLabel
之前的图形
and then simply transform the Graphics
object before I offload painting to the original JLabel
:
@Override
protected void paintComponent(Graphics g) {
Graphics2D gr = (Graphics2D) g.create();
switch (getDirection()) {
case VERTICAL_UP:
gr.translate(0, getPreferredSize().getHeight());
gr.transform(AffineTransform.getQuadrantRotateInstance(-1));
break;
case VERTICAL_DOWN:
// TODO
break;
default:
}
super.paintComponent(gr);
}
}
似乎工作 - 不知何故 - 在文本中现在垂直显示。但是,展示位置和尺寸已关闭:
It seems to work—somehow—in that the text is now displayed vertically. However, placement and size are off:
实际上,背景的宽度(在这种情况下为橙色)与周围的高度相同JFrame
这不是我的想法。
Actually, the width of the background (orange in this case) is identical with the height of the surrounding JFrame
which is ... not quite what I had in mind.
任何想法如何以正确的方式解决这个问题?是否鼓励将渲染委托给超类?
Any ideas how to solve that in a proper way? Is delegating rendering to superclasses even encouraged?
推荐答案
我现在在同事的帮助下完成了它的工作。基本上我现在有一个字段,指示是否交换高度/宽度,该高度/宽度仅在原始 JLabel
进行绘制时才有效。
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;
}
这篇关于旋转Swing JLabel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!