Blood Brother
Blood Brother

Reputation: 103

Swing GUI: drawString - How to set the font size of the String being displayed?

We all know that the drawString method can be used this way:

import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JComponent;
import javax.swing.JFrame;

public class Driver {

    public static void main(String[] args) {
        JFrame frame = new JFrame("Frame Heading");
        frame.setSize(1000,500);
        myComponent comp = new myComponent();
        frame.add(comp);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

class myComponent extends JComponent {
    public void paintComponent(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        g2.drawString("Hello World", 300, 300);
    }
}

But, how do we adjust the font size of the string being displayed? I want to make it larger.

Upvotes: 1

Views: 13522

Answers (2)

camickr
camickr

Reputation: 324157

how do we adjust the font size of the string being displayed?

You can derive a new Font based on the current font:

public void paintComponent(Graphics g) 
{
    super.paintComponent(g); // don't forget this.
    g.fillRect(0, 0, getWidth(), getHeight()); // make sure the background is cleared

    Font font = g.getFont().deriveFont( 20.0f );
    g.setFont( font );
    g.drawString(...);
}

You don't need a Graphics2D object to draw a string.

Or instead of forcing the Font to be a specific size in the paintComponent() method you can customize your object by using:

MyComponent comp = new MyComponent();
comp.setFont( comp.getFont().deriveFont( 20.0f );

In this case you use your current painting code.

Also, class names should start with an upper case character you your class should be "MyComponent".

Upvotes: 4

user3900751
user3900751

Reputation: 115

class myComponent extends JComponent {
    public void paintComponent(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        int fontSize = 20;
        Font f = new Font("Comic Sans MS", Font.BOLD, fontSize);
        g2.setFont(f);
        g2.drawString("Hello World", 300, 300);
    }
}

You can change the style, size and Font because you probably don't want to use Comic Sans.

See also Graphics#setFont.

Upvotes: 4

Related Questions