This site requires JavaScript, please enable it in your browser!
Greenfoot back
tonyreks
tonyreks wrote ...

2018/12/11

Problems converting between greenfoot.Font and java.awt.Font

tonyreks tonyreks

2018/12/11

#
Hi, I am trying to update some really old code that still uses the old java.awt.Color and java.awt.Font libraries. The automatic converter did 90% (I think?) but I was left having to comment out every import line in every file. Anyways, it's come down to a few key lines where the old code is still expecting a java.awt.Color object. For instance:
1
2
3
4
5
6
7
8
9
10
11
/**
 * Gets a graphics context for this component from this Actor's image.
 *
 * @return a graphics context for this component.
 */
public Graphics getGraphics() {
    Graphics g = getImage().getAwtImage().getGraphics();
    if (getFont() != null) g.setFont(getFont());
    if (getForeground() != null) g.setColor(getForeground());
    return g;
}
The main problem is that these external libraries still expect a java.awt.Font object. This line in particular:
1
if (getFont() != null) g.setFont(getFont());
Is there a way to convert the greenfoot.Font object into a java.awt.Font object? Is there a better way to address this?
danpost danpost

2018/12/11

#
I came up with the following test class code which seems to work:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import greenfoot.*;
 
public class FontTester extends Actor
{
    Font font;
    Color foreground;
     
    public FontTester()
    {
        font = getImage().getFont();
        foreground = Color.GREEN;
    }
     
    public java.awt.Graphics getGraphics()
    {
        java.awt.Graphics g = getImage().getAwtImage().getGraphics();
        if (getFont() != null) g.setFont(getAwtFont(getFont()));
        if (getForeground() != null) g.setColor(getAwtColor(getForeground()));
        return g;
    }
     
    public Font getFont() { return font; }
     
    public Color getForeground() { return foreground; }
     
    public java.awt.Font getAwtFont(Font f)
    {
        String name = f.getName();
        int style = (f.isBold() ? 2 : 0)+(f.isItalic() ? 1 : 0);
        int size = f.getSize();
        return new java.awt.Font(name, style, size);
    }
     
    public java.awt.Color getAwtColor(Color c)
    {
        int r = c.getRed();
        int g = c.getGreen();
        int b = c.getBlue();
        int a = c.getAlpha();
        return new java.awt.Color(r, g, b, a);
    }
}
You need to login to post a reply.