Find the index of a Java JButton Array

本小妞迷上赌 提交于 2019-12-31 03:08:09

问题


I am writing a Java program in which I have an array of buttons (not a calculator!) and I'm looking for an efficient way to know which JButton was clicked. From what I know of Java so far, the only way to do it is to have them all in the same ActionListener and then loop through looking for a match.

Another solution I just thought of would be to extend JButton to include a unique ID number variable in the constructor. It seems that should work when the event object is cast to JButton after an instanceof check. Kind of like using VB's Tag property which is assigned to the index number.

Is there a better/more elegant way?


回答1:


Is there a better/more elegant way?

  • yes to use (for almost JComponents) the put/getClientProperty, there you can to set endless number of properties, can be multiplied in contrast with setName / setActionCommand / etc

  • getClientProperty can be used as unique identificator for Swing Action or EventHandler (rather than to use ActionListener)

Links to the Javadocs: putClientProperty(), getClientProperty()




回答2:


Here is an example from programm I writing last few months. I have an enum called Position

public enum Position {
    BB, SB, BU, CO, MP3, MP2, MP1, EP3, EP2, EP1;
}

and have some JToggleButtons each of them holding ist own Position.

public class PositionButton extends JToggleButton {
    private final Position p;

    public PositionButton(Position p) {
        this.p = p;
        setText(p.toString());
        setActionCommand(p.toString());
    }

    public Position getPosition() {
        return p;
    }
}

This allows you to create Buttons in a Loop and get value direct from button without comparing:

ActionListener positionListener = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        PositionButton b = (PositionButton )e.getSource();
        Position p = b.getPosition();
        //do something with Position
    }
}

for (Position p : Position.values()) {
    PositionButton b = new PositionButton (p);
    b.addActionListener(positionListener);
}



回答3:


The way I've done it before was using actionPerformed for different buttons. I like it more compared to some other ways I've seen.

public void actionPerformed(ActionEvent clicking)
{
    if (clicking.getSource() == button[0])
        // Do this
    if (clicking.getSource() == button[1])
        // Do something different
}

Since you built an array, you can throw the ID right where that 0 is and that's your unique ID.




回答4:


Add a separate action listener for each button.



来源:https://stackoverflow.com/questions/31193084/find-the-index-of-a-java-jbutton-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!