【问题标题】:Java Changing Font For All ButtonsJava 更改所有按钮的字体
【发布时间】:2014-06-14 22:43:52
【问题描述】:

我的程序使用了大量的 JButton,我想知道如何更改特定面板中所有现有按钮的字体,而无需单独更改每个按钮的字体。

【问题讨论】:

  • @Arvind UIManager 值将更改其程序中所有JButtons 的字体。 OP 只想更改单个 JPanel 中的内容。

标签: java swing button fonts


【解决方案1】:

语法是

setFont(new Font("fontName", fontStyle, fontSize));

除非你有自定义字体,否则它会是

setFont(font);

【讨论】:

  • 对不起我的电话。自动更正有一个使用自动大写的现场日。
【解决方案2】:

您可以创建自己的扩展JButton 的类并设置该类的字体,然后将其用于JPanel 中的所有按钮:

class MyJButton extends JButton {

    MyJButton() {

        super();
        setFont(new Font("Arial", Font.BOLD, 40));
   }
}

您可以覆盖您正在使用的任何构造函数。

【讨论】:

  • setFont 函数的语法是什么样子的? setFont(Font,"Arial",Font.BOLD, 40);
【解决方案3】:

我想知道如何更改所有现有的字体 特定面板中的按钮,无需单独更改 每个按钮的字体

从技术上讲,您不能,您需要能够迭代容器并单独更改每个按钮...

假设所有按钮都在一个容器上(并且不包含在多个子容器中),您可以简单地遍历给定容器中的所有组件,测试它们是否是 JButton 并应用新的字体。

Font font = new Font("Arial", Font.BOLD, 48);
for (Component comp : getComponents()) {
    if (comp instanceof JButton) {
        ((JButton)comp).setFont(font);
    }
}

例如...

【讨论】:

  • UIManager.put("Button.font", new Font(...)); - 更简单。
  • @IvanBabanin 1- 这将改变整个应用程序中所有按钮的字体,OP 特别声明“特定面板中的现有按钮”。 2- 如果 UI 已经创建并可见,您还需要调用 updateUI,这并不总是很好:P
  • 啊,好的。谢谢你的澄清:)
  • @IvanBabanin 不用担心,这是我脑子里想的第一件事
  • @MadProgrammer 我尝试通过执行 Font font = new Font("Arial", Font.BOLD, 48); 来实现它for (Component numbersP : getComponents()) { if (comp instanceof JButton) { ((JButton)numbersP).setFont(font);其中 numbersP 是按钮所在的面板,但我收到符号未找到错误
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-05
相关资源
最近更新 更多