简体   繁体   English

如何更改 Java 中 JMenu 的字体大小?

[英]How do I change the font size of a JMenu in Java?

I have been trying to change the font size of a JMenu in a Java program of mine because it automatically is displayed incredibly tiny (I am running Windows 10).我一直在尝试在我的 Java 程序中更改 JMenu 的字体大小,因为它会自动显示得非常小(我正在运行 Windows 10)。

Here is my code:这是我的代码:

 import javax.swing.*;
    import java.awt.*;

...
        public static void runGUI()
        {
            //setup
            JFrame frame = new JFrame("Resistor Identifier");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(1000,1000);

            //define content
            Font font1 = new Font("SansSerif", Font.BOLD, 30);
            JMenuBar menu = new JMenuBar();
            JMenu menu1 = new JMenu("Settings");
            menu.setFont(font1);
            menu.add(menu1);
            JButton button1 = new JButton("Button 1");
            button1.setFont(font1);
            JTextArea text = new JTextArea();
            UIManager.put("Menu.font", font1);

            //show content
            frame.getContentPane().add(BorderLayout.CENTER, button1);
            frame.getContentPane().add(BorderLayout.NORTH, menu);
            frame.setVisible(true);
        }

I have tried using both of the following statements to change the font size, but neither has done anything to the font size (the bold option did not work either in the statements I tried).我尝试使用以下两个语句来更改字体大小,但都没有对字体大小做任何事情(粗体选项在我尝试的语句中也不起作用)。

Font font1 = new Font("SansSerif", Font.BOLD, 30);
 menu.setFont(font1);

and

 UIManager.put("Menu.font", font1);

Please let me know if you have a solution to this problem.如果您有解决此问题的方法,请告诉我。 Thank you.谢谢你。

After typing this out, I realized my mistake.写完之后,我意识到我的错误。 I had defined the method I used to display the GUI as a static method.我已将用于显示 GUI 的方法定义为 static 方法。 After redefining the method simply as将方法重新定义为

public void runGUI() {}

and running the program, the font of the JMenu became both bolded and 30 pt.运行程序,JMenu 的字体变为粗体和 30 pt。 I tested both of the methods I used as stated above with the method redefined as non-static, and both statements worked for me to adjust the font size and boldness of the JMenu.我用重新定义为非静态的方法测试了上述两种方法,这两种方法都对我有用,可以调整 JMenu 的字体大小和粗体。

I decided to answer my own question in case anyone else had a similar problem.我决定回答我自己的问题,以防其他人有类似的问题。 I just have one more question for anyone who would like to answer: why does this work only when the method is not static?对于任何想回答的人,我还有一个问题:为什么只有当方法不是 static 时这才有效?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM