Java 我如何更改 JPanel 的字体大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20767290/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 04:11:38  来源:igfitidea点击:

How do i change the font size of JPanel

javaswingfontssizejpanel

提问by nick zoum

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

我正在尝试创建一个JPanel具有不同字体大小的文件,而不使用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);
    }
}

采纳答案by andreban

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 时都创建一个新字体。

回答by Aniruddha Sarkar

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

完毕...

回答by La VloZ

You can call the method setFont()from you JPaneland give it a Fontas parameter. Example :

您可以setFont()从您那里调用该方法JPanel并将其Font作为参数。例子 :

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.

第一个参数是字体名称,第二个参数是样式,最后一个参数是大小。