我在构建一个类似具有投票按钮的论坛应用程序时遇到了困难。
对于自动生成的每个内容,我都有投票赞成和反对按钮。我希望此按钮仅显示向上和向下箭头,而不显示任何文本或标签。我如何找出按下了哪个按钮?
自动化内容..
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/