简体   繁体   English

如何为多个 JButton 运行代码?

[英]How can I run a code for multiple JButtons?

I want run a code for JButtons I want.我想为我想要的 JButton 运行代码。

I search for this in Internet but I can't find a solution for swing applications.我在 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)));

I tried below code but I could not use JButton properties我尝试了以下代码,但无法使用 JButton 属性

JButton[] buttons = new JButton[];

I declare it我宣布

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;

But this didn't work:但这不起作用:

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

Step 1: You create an array, and fill it with the buttons.第 1 步:创建一个数组,并用按钮填充它。

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

Note: this already fills the array with the buttons, so statements like this:注意:这已经用按钮填充了数组,所以像这样的语句:

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

are redundant.是多余的。

Step 2: Iterate over the array第 2 步:遍历数组

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

Step 3: Set the font第三步:设置字体

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

If you do not want to keep the button as fields or in a structure AND the buttons are in one container (if they are in a different container, you will have to do more), another approach would be to use Darryl Burke's SwingUtils class .如果您不想将按钮保留为字段或结构并且按钮位于一个容器中(如果它们位于不同的容器中,您将不得不执行更多操作),另一种方法是使用Darryl Burke 的 SwingUtils 类

So let's see how easier it would be:那么让我们看看它会变得多么容易:

for (JButton b : SwingUtils.getDescendantsOfClass(JButton.class, panelWithButtons)) {
    b.setFont(new Font("Tahoma",Font.BOLD,14));
}

Voilà!瞧! All buttons in "panelWithButtons" JPanel has this font. "panelWithButtons" JPanel 中的所有按钮都有这种字体。 No fields kept, no array kept.不保留字段,不保留数组。

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

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