I'm making a program in which you can click on a JLabel which holds an image and circles will appear on the JLabel. This works flawless on my macintosh/java6 but when I'm using windows/java7 all sorts of weird things happens. On some parts of the image you can't draw a circle. It's like an invisible square in the middle of the picture. And sometimes the circles disappear and come back at different times. Everytime i draw a new circle all the circles are getting redrawn on top of the label.
public void paint(JComponent label) {
Graphics g = label.getGraphics();
for (T node : nodes.keySet()) {
Point p = nodes.get(node);
Color color;
if (p.selected) {
color = Color.RED;
} else {
color = Color.BLUE;
}
g.setColor(color);
g.fillOval(p.x, p.y, circleRadius*2, circleRadius*2);
g.setColor(Color.BLACK);
g.setFont(new Font("Helvetica", 20, 20));
g.drawString((String) node, p.x, p.y);
}
}
Does anyone know what might cause this?
Never use getGraphics(), it can return null and at best is a snap shot of the last paint cycle
As soon as a repaint occurs anything painted to it will be removed
Instead, as Legend has already suggested, create yourself a custom label and override paintComponent and perform your painting here
Remember, painting is stateless, this means that on each repaint, you'll have to reconstruct your state
Take a look at Custom painting
Remove your paint(JComponent j); method and try using the following JLabel. Tweak as necessary to suit your needs.
final JLabel jLabel = new JLabel("!X!") {
@Override
public void paintComponent(final Graphics g) {
super.paintComponent(g);
for (T node : nodes.keySet()) {
Point p = nodes.get(node);
Color color;
if (p.selected) {
color = Color.RED;
} else {
color = Color.BLUE;
}
g.setColor(color);
g.fillOval(p.x, p.y, circleRadius*2, circleRadius*2);
g.setColor(Color.BLACK);
g.setFont(new Font("Helvetica", 20, 20));
g.drawString((String) node, p.x, p.y);
}
}
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.