java - 如何为多个 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)));
解决方案
第 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)));
}
推荐阅读
- android - Xamarin Android:Google Pay 集成和 Play 服务 16.0.0.0
- c++ - 具体的构造函数和其中字段的初始化
- sql - PATINDEX 的意外结果
- python - 如何在熊猫数据框中将两列合并为一列
- flutter - Flutter 上的 PlatformView 能否帮助构建用于 Flutter 的 AdMob BannerAd 小部件?
- json - Staxon - 去掉 JSON 标记名称中的 $ 和 @
- javascript - 画
- python - requests.exceptions.ConnectionError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response',))
- c++ - 特征 vect 犰狳 c++
- javascript - 有关 json 更改的状态更新信息失败