我通过覆盖paintComponent()方法创建了自定义标签,如下所示。 但是,当我在这个组件上调用setBackground()方法。它绘制整个矩形。 我希望它只绘制自定义形状。请帮助。对于自定义JLabel(形状已更改)setbackground方法绘制矩形而不是新形状
自定义标签的代码:
public class CustomLabel extends JLabel {
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Rectangle rect = g.getClipBounds();
Polygon shape3 = new Polygon();
shape3.addPoint(rect.x, rect.y + rect.height - 1);
shape3.addPoint(rect.x + rect.width - 10, rect.y + rect.height - 1);
shape3.addPoint(rect.x + rect.width - 1, rect.y + rect.height/2);
shape3.addPoint(rect.x + rect.width - 10, rect.y);
shape3.addPoint(rect.x, rect.y);
g.setColor(Color.LIGHT_GRAY);
g.drawPolygon(shape3);
}
}
编辑:
改性如下面的代码。
我希望默认背景是白色所以当第一次创建标签时背景是白色的。现在屏幕上显示了几个标签。点击事件时,我改变背景颜色,例如我打电话给setbackground(Color.red),以便点击标签的颜色得到更新。
现在,当我滚动屏幕时,repaint()方法被调用,并重新绘制所有自定义标签并将所有标签的背景更改为红色。
编辑2: 代码添加标签:
for (int i = 0; i < noOfLabels; i++)
{
String labelkey = "Label" +i;
CustomLabel label = new CustomLabel();
label.addMouseListener(this);
myLayeredPane.add(label, new Integer(3));
}
代码自定义标签:
public class CustomLabel extends JLabel
{
private Color background = Color.WHITE;
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Rectangle rect = g.getClipBounds();
Polygon shape3 = new Polygon();
shape3.addPoint(rect.x, rect.y + rect.height - 1);
shape3.addPoint(rect.x + rect.width - 10, rect.y + rect.height - 1);
shape3.addPoint(rect.x + rect.width - 1, rect.y + rect.height/2);
shape3.addPoint(rect.x + rect.width - 10, rect.y);
shape3.addPoint(rect.x, rect.y);
g.setColor(background);
g.fillPolygon(shape3);
g.setColor(Color.LIGHT_GRAY);
g.drawPolygon(shape3);
}
@Override
public void setBackground(Color arg0)
{
background = arg0;
System.out.println("Setting bg color to : "+background);
}
}
非常感谢。但现在的问题是,现在每当调用repaint()方法。总是使用设置的新背景颜色绘制面板。如果有添加自定义面板的列表,则所有面板都会涂上新的bg颜色。 :( –
举个例子,我听不懂你的意思 – alex2410
编辑了我的问题上面 –