How do i change the font size of JPanel
Solution 1
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.
Solution 2
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...
Solution 3
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.
nick zoum
The only programmer that doesn't drink coffee. JS Enthusiast (Browser, Node, Electron and whatever else you may find) Some of my most voted questions: Add custom typings file in a JavaScript VSCode project Proxy substitue for ES5 Some of my most useful answers (primarily opinion based): Add custom typings file to a JavaScript VSCode project Parsing and running a mathematical equation in JavaScript Running asynchronous operations in JavaScript The UMD Design Pattern in JavaScript Removing all instances of a class using Vanilla JS Creating and using a JFrame in Java Implementing the Singleton design pattern in Java Why do both [] == true and ![] == true evaluate to false? Why “this” is undefined in function called via logical operator?
Updated on June 04, 2022Comments
-
nick zoum almost 2 years
I am trying to create a
JPanel
with varying font sizes, without usingJLabels
.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); } }