Одно действие на многие кнопки jButton - PullRequest
0 голосов
/ 11 июня 2018

Я хотел бы использовать одну функцию на 50 jButtons, она должна быть числовой игрой в маджонг, я хотел бы поместить случайные числа во все 50 jButtons одним методом.

int r = randInt(1,50);
        jButton1.setText(Integer.toString(r));

Это один, но я понятия не имею, как сделать его таким же для 50 других.Все, что я могу понять, это скопировать вставить 50 раз и изменить номер кнопки.

Ответы [ 2 ]

0 голосов
/ 11 июня 2018

Другим подходом будет использование класса 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);
        });
    }
}
0 голосов
/ 11 июня 2018

Вы можете сохранить эти кнопки в массиве, а затем использовать простой цикл 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));
}
...