[英]How do i change the font size of JPanel
I am trying to create a JPanel
with varying font sizes, without using JLabels
. 我正在尝试使用
JLabels
创建具有不同字体大小的JPanel
。
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 将其添加到void paint()方法中
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.
要在使用java.awt.Graphics对象进行绘制时更改字体大小,需要更改当前字体。
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. 理想情况下,应该在每次调用paint时将字体对象声明为实例变量,而不是创建新字体。
You can call the method setFont()
from you JPanel
and give it a Font
as parameter. 您可以从
JPanel
调用方法setFont()
并将其指定为Font
。 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. 第一个参数是字体名称,第二个参数是样式,最后一个参数是字号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.