3

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);
    }
}
nick zoum
  • 7,216
  • 7
  • 36
  • 80
  • 2
    well you shoud change a font of component like JLabel put jLabel on your frame and change its font.There is method on it .setFont(..) – Tomas Bisciak Dec 24 '13 at 22:17
  • Please check other SO posts before: http://stackoverflow.com/questions/7434845/setting-the-default-font-of-swing-program-in-java – pogopaule Dec 24 '13 at 22:18
  • 1
    And you shouldn't override a JPanel's paint method either. – Hovercraft Full Of Eels Dec 24 '13 at 22:18
  • 1) For better help sooner, post an [SSCCE](http://sscce.org/). 2) That `paint (Graphics g)` should almost certainly be `paintComponent (Graphics g)` 3) But agree with @HovercraftFullOfEels that custom painting is not the way to go about this. 4) Please don't forget to add a '?' to questions! Some people do a search in the page for '?' and if none exists in the 'question' go directly to the next (actual) question in line. – Andrew Thompson Dec 25 '13 at 05:42

3 Answers3

4

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...

3

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.

andreban
  • 4,621
  • 1
  • 20
  • 49
1

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.

La VloZ
  • 102
  • 10