Другим подходом будет использование класса SwingUtils Даррила Бёрка и поиск всех кнопок J в контейнере Panel, а затем выполнение с ними всего, что вы хотите.Это имеет более высокую сложность (но не обязательно «сохранять» все j-кнопки где-нибудь) наверняка, и здесь это не обязательно, но вы можете найти это полезным однажды в будущем.Например, для итерации кнопок 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);
});
}
}