【发布时间】:2021-05-03 02:32:47
【问题描述】:
我正在渲染一堆包含图标的 JLabel。我想通过在它们的顶部绘制某种线条或符号来有条件地注释这些图标。是否可以在摇摆的图标上绘制?我的 JLabel 如下所示的示例:
我用来封装包含我的 JLabels 的 waypoint 组件的类:
/**
* Waypoint to be drawn on the map
*/
public class Waypoint extends DefaultWaypoint {
protected JLabel label;
private final long id;
private final EntityType type;
public Waypoint( long id ) {
this.id = id;
this.type = null;
this.label = null;
}
public Waypoint( long id, EntityType type, Location coord ) {
super( locToGeoPos(coord) );
this.id = id;
this.type = type;
this.label = new JLabel();
}
public void setIcon( ImageIcon icon ) {
label = new JLabel( icon, JLabel.CENTER );
label.setBorder( new LineBorder(Color.BLACK) );
}
public void setBackgroundColor( Color bgrColor ) {
label.setOpaque( true );
label.setBackground( bgrColor );
}
public void setToolTipText( String tooltipText ) {
label.setToolTipText( "<html>" + tooltipText + "</html>" );
}
public JLabel getLabel() {
return label;
}
public void annotateIcon() {
// TODO
}
任何帮助将不胜感激,谢谢!
【问题讨论】:
-
是的,可以创建一个扩展 JLabel 的类,然后覆盖 paintComponent 方法。这里是“官方”教程:docs.oracle.com/javase/tutorial/uiswing/painting/index.html
-
JLabel是一个复杂的组件,它处理文本、图像和各种对齐选项,尝试扩展它以提供自定义“覆盖”可能不是您可用的最佳解决方案。就个人而言,我会考虑创建一个新图像,使用基本图像和您想要覆盖的任何其他内容,并将其分配给标签,它会为您提供更高级别的自定义,并且通常会更容易 -
是否可以在 swing 中的图标上绘图? - 您可以使用Compound Icon。它将允许您在原始图标之上绘制第二个图标。
标签: java swing paintcomponent