[英]One action on many jButtons
我想在50个jButton上使用一个函数,假设是数字麻将游戏,我想用一种方法将随机数放入所有50个jbutton中。
int r = randInt(1,50);
jButton1.setText(Integer.toString(r));
这是一个,但我不知道如何使其他50个相同。 我所能想到的就是将其复制粘贴50次并更改按钮的编号。
您可以将这些按钮存储在数组中,然后可以使用简单的for循环在每个元素上执行该方法。
例如:
//JButtonArray is an array of JButton objects
for(int i=0; i < JButtonArray.length; i++) {
r = randInt(1,50);
JButtonArray[i].setText(Integer.toString(r));
}
另一种方法是使用Darryl Burke的SwingUtils类,并在“面板容器”中找到所有JButton,然后对它们进行任何操作。 当然,它具有更高的复杂度(但不需要将所有jbutton“保存”在某个地方),并且不一定要在这里进行,但是将来您可能会发现它很有用。 例如,要迭代JOptionPane
的按钮。
使用此方法的SSCCE:
package test;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.GridLayout;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
@SuppressWarnings("serial")
public class AllJButtons extends JFrame {
public AllJButtons() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 500);
getContentPane().setLayout(new GridLayout(10, 5));
//Let's say somehow, we add the buttons
for (int i = 0; i < 50; i++) {
JButton btn = new JButton("Button ID=" + i);
getContentPane().add(btn);
}
//Now iterate all buttons and add them red border.
for (JButton button : getDescendantsOfType(JButton.class, getContentPane(), false)) {
button.setBorder(BorderFactory.createLineBorder(Color.RED));
}
setLocationRelativeTo(null);
}
/**
* Convenience method for searching below <code>container</code> in the
* component hierarchy and return nested components that are instances of
* class <code>clazz</code> it finds. Returns an empty list if no such
* components exist in the container.
* <P>
* Invoking this method with a class parameter of JComponent.class
* will return all nested components.
*
* @param clazz the class of components whose instances are to be found.
* @param container the container at which to begin the search
* @param nested true to list components nested within another listed
* component, false otherwise
* @return the List of components
*/
public static <T extends JComponent> List<T> getDescendantsOfType(Class<T> clazz, Container container, boolean nested) {
List<T> tList = new ArrayList<T>();
for (Component component : container.getComponents()) {
if (clazz.isAssignableFrom(component.getClass())) {
tList.add(clazz.cast(component));
}
if (nested || !clazz.isAssignableFrom(component.getClass())) {
tList.addAll(AllJButtons.<T>getDescendantsOfType(clazz, (Container) component, nested));
}
}
return tList;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
new AllJButtons().setVisible(true);
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.