문제

I'm trying to embed a TTF font and then use draw it with Grapics2D. I've been able to create the font, but I'm not exactly sure how to pass the font to setFont. I make a new font here, which throws no exceptions:

private Font pixel = Font.createFont(Font.TRUETYPE_FONT, this.getClass().getResourceAsStream("font/amora.ttf"));

But I can't figure out how to draw it with setFont();

Here's my code:

private static final long serialVersionUID = 1L;
private Timer timer;
private Char Char;
private Font pixel = Font.createFont(Font.TRUETYPE_FONT, this.getClass().getResourceAsStream("font/amora.ttf")); <<<--------

public Board() throws FontFormatException, IOException {

    addKeyListener(new TAdapter());
    setFocusable(true);
    setBackground(Color.BLACK);
    setDoubleBuffered(true);

    Char = new Char();

    timer = new Timer(5, this);
    timer.start();
}


public void paint(Graphics g) {
    super.paint(g);

    Graphics2D g2d = (Graphics2D)g;
    g2d.drawImage(Char.getImage(), Char.getX(), Char.getY(), this);
    g.setColor(Color.white);
    g.setFont( What goes here? );  // <------------
    g.drawString("Amora Engine rev25 (acetech09)", 10, 20);
    g.drawString(Char.getDebugStats(0), 10, 40);
    g.drawString(Char.getDebugStats(1), 10, 60);
    Toolkit.getDefaultToolkit().sync();
    g.dispose();
}


public void actionPerformed(ActionEvent e) {
    Char.move();
    repaint();  
}
}

Any help would be greatly appreciated. Thanks.

도움이 되었습니까?

해결책

You could just do...

g.setFont(pixel);

But you might have better sucess with

g.setFont(pixel.deriveFont(Font.BOLD, 36f));

Are variations of....

Also, don't dispose of a Graphics context you did not create...

Graphics2D g2d = (Graphics2D)g;
/*...*/
// g.dispose();

Or

Graphics2D g2d = (Graphics2D)g.create();
/*...*/
g.dispose();

I'd also be loathed to override the paint method. Assuming you're using something like JComponent or JPanel, you should use paintComponent. If you're rendering directly yo a top level container (like JFrame), then I wouldn't. There are issues with double buffering and frame borders that won't make your life fun...

I'm also concerned about new Timer(5, this) - 5 milliseconds is close enough to 0 to make little difference. You'd be better of with something like 40, which should give you something like 25fps or 17 which will give you roughly 60fps...

다른 팁

It should be

g.setFont( this.pixel );

If this is not working, try:

  1. Commenting out the setFont instruction.
  2. Replacing Font.createFont with a reference to a Java standard font.

to rule out possible issues.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top