Reputation: 7285
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);
}
}
Upvotes: 3
Views: 18614
Reputation: 4976
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.
Upvotes: 3
Reputation: 112
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.
Upvotes: 1
Reputation: 485
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...
Upvotes: 4