首页 > 解决方案 > 如何为多个 JButton 运行代码?

问题描述

我想为我想要的 JButtons 运行代码。

我在 Internet 上搜索此内容,但找不到 Swing 应用程序的解决方案。

b1.setFont(new Font("Arial", Font.PLAIN, (h / 25)));
b2.setFont(new Font("Arial", Font.PLAIN, (h / 25)));
b3.setFont(new Font("Arial", Font.PLAIN, (h / 25)));
b4.setFont(new Font("Arial", Font.PLAIN, (h / 25)));
b5.setFont(new Font("Arial", Font.PLAIN, (h / 25)));
b6.setFont(new Font("Arial", Font.PLAIN, (h / 25)));
b7.setFont(new Font("Arial", Font.PLAIN, (h / 25)));
b8.setFont(new Font("Arial", Font.PLAIN, (h / 25)));
b9.setFont(new Font("Arial", Font.PLAIN, (h / 25)));

我尝试了下面的代码,但我无法使用 JButton 属性

JButton[] buttons = new JButton[];

我声明

buttons[0] = b1;
buttons[1] = b2;
buttons[2] = b3;
buttons[3] = b4;
buttons[4] = b5;
buttons[5] = b6;
buttons[6] = b7;
buttons[7] = b8;
buttons[8] = b9;

但这不起作用:

buttons.setFont(new Font("Arial", Font.PLAIN, (h / 25)));

标签: javaswingjbuttonjcomponent

解决方案


第 1 步:创建一个数组,并用按钮填充它。

JButton[] buttons = {b1,b2,b3,b4,b5,b6,b7,b8,b9};

注意:这已经用按钮填充了数组,所以语句如下:

buttons[0] = b1;
buttons[1] = b2;
buttons[2] = b3;

是多余的。

第 2 步:遍历数组

for ( JButton button : buttons ) {
  // here you are to call the setFont
}

第三步:设置字体

for ( JButton button : buttons ) {
  button.setFont(new Font("Arial", Font.PLAIN, (h / 25)));
}

推荐阅读