许多jButton上的一个动作

时间:2018-06-10 23:10:25

标签: java swing random jbutton

我想在50 jButtons上使用一个函数,它假设是数字麻将游戏,我想用一种方法将随机数放入所有50个jbuttons中。

literal_eval

这是一个,但我不知道,如何使其他50个相同。我只能复制粘贴50次并更改按钮的数量。

2 个答案:

答案 0 :(得分:1)

您可以将这些按钮存储在一个数组中,然后您可以使用一个简单的for循环来对每个元素执行该方法。

例如:

IOptionsMonitor

答案 1 :(得分:0)

另一种方法是使用Darryl Burke's SwingUtils class并在Panel-Container中查找所有JButton,然后随意执行任何操作。这具有更高的复杂性(但它不需要“保存”某处的所有jbuttons),并且这不是必需的,但您可能会发现它在将来的某一天有用。例如,迭代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);
        });
    }
}