简体   繁体   中英

How do i change the font size of JPanel

I am trying to create a JPanel with varying font sizes, without using JLabels .

Below is a representation of what the code looks like.

public class MyPanel extends JPanel{

    public MyPanel(string title){
        JFrame frame = new JFrame(title);
        frame.setExtendedState(Frame.MAXIMIZED_BOTH);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    public void paintComponent(Graphics graphics){
        graphics.drawString("Some Text",100,100);
        // Should decrease font size
        graphics.drawString("Some Smaller Text",200,200);
        // Should increase font size
        graphics.drawString("Some Bigger Text",300,300);
    }
}

add this in void paint() method

  float f=20.0f; // font size.
   g.setFont(g.getFont().deriveFont(f);
   g.drawString("whatever",150,f+10);// provides optimum gap for printing

Done...

It looks like you are drawing text directly to the Canvas. To change the font size when drawing with a java.awt.Graphics object, you need to change the current font.

For instance:

public  void paint(Graphics g){
   Font font = new Font("Verdana", Font.BOLD, 12);
   g.setFont(font);
   g.drawString("bla bla",150,10);
}

Ideally, you should declare the font object as an instance variable instead of creating a new font every time paint is called.

You can call the method setFont() from you JPanel and give it a Font as parameter. Example :

setFont(new java.awt.Font("Century Schoolbook L", 2, 24));

The first argument is the font name, the second is for the style and the last one is for the size.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM