Java如何为按钮分配id并检索它们?

标签 java swing jbutton

我在构建一个类似具有投票按钮的论坛应用程序时遇到了困难。

对于自动生成的每个内容,我都有投票赞成和反对按钮。我希望此按钮仅显示向上和向下箭头,而不显示任何文本或标签。我如何找出按下了哪个按钮?

自动化内容..

ImageIcon upvote = new ImageIcon(getClass().getResource("vote_up.png"));
ImageIcon downvote = new ImageIcon(getClass().getResource("vote_down.png"));
JButton vote_up = new JButton(upvote);
JButton vote_down = new JButton(downvote);
vote_up.addActionListener(voting);
vote_down.addActionListener(voting);

Action voting = new AbstractAction(){
    @Override
    public void actionPerformed(ActionEvent e){
        //What to do here to find out which button is pressed?
    }
};

感谢任何帮助。

public void a(){
    int crt_cnt = 0;
    for(ClassA temp : listofClassA)
    {                    
        b(crt_cnt);
        crt_cnt++;
    }

}
public void b(crt_cnt){
     //draw button
}

如上所述,我有多个由 b 函数创建的 vote_up 和 vote_down 按钮,我如何区分该按钮来自哪个 crt_cnt?

最佳答案

有多种方法可以实现这一目标

你可以...

只需使用 ActionEvent

Action voting = new AbstractAction(){
    @Override
    public void actionPerformed(ActionEvent e){
        if (e.getSource() == vote_up) {
            //...
        } else if (...) {
            //...
        }
    }
};

如果您有对原始按钮的引用,这可能没问题

你可以...

为每个按钮分配一个actionCommand

JButton vote_up = new JButton(upvote);
vote_up.setActionCommand("vote.up");
JButton vote_down = new JButton(downvote);
vote_down .setActionCommand("vote.down");
//...
Action voting = new AbstractAction(){
    @Override
    public void actionPerformed(ActionEvent e){
        if ("vote.up".equals(e.getActionCommand())) {
            //...
        } else if (...) {
            //...
        }
    }
};

你可以...

充分利用Action API,为每个按钮创建独立的、独立的操作...

public class VoteUpAction extends AbstractAction {

    public VoteUpAction() {
        putValue(SMALL_ICON, new ImageIcon(getClass().getResource("vote_up.png")));
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        // Specific action for up vote
    }

}

然后你可以简单地使用

JButton vote_up = new JButton(new VoteUpAction());
//...

它将根据 Action 的属性配置按钮,并在触发按钮时触发其 actionPerformed 方法。这样,您就可以 100% 知道调用 actionPerformed 方法时应该/需要做什么,毫无疑问。

仔细看看How to Use Actions了解更多详情

关于Java如何为按钮分配id并检索它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32579427/

相关文章:

java - slf4j + log4j2 不写入文件

java - 简单多线程程序中的对象共享

JAVA时间动画

java - 最右边的 JButton 在 JPanel 中必须始终可见

java - 制作一个按钮 - java

c# - 哪个更好更便宜 : class matching vs exception?

java - 如何清除面板?

java - 如何在java中按下按钮时更改按钮的颜色

java - JButton 数组 ActionListener

java - 如何从 ContainerRequestContext JERSEY 2.1 获取 IP?