首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将图标从jbutton移动到jbutton

将图标从jbutton移动到jbutton
EN

Stack Overflow用户
提问于 2014-04-24 12:12:15
回答 2查看 1K关注 0票数 0

我设置了一个网格布局,中心有16个按钮。我在第一个按钮上放了一个图标。

我如何循环,当用户选择网格上的next按钮时,它会将图标从旧位置移动到新位置?

代码语言:javascript
复制
private ArrayList<JButton> grid = new ArrayList<JButton>(); 

JPanel gridBtnPanel = new JPanel();
gridBtnPanel.setLayout(new GridLayout(4, 4));
for(int i = 0; i <= 16; i++){
    JButton innerButton = new JButton();
    gridBtnPanel.add(innerButton);
    grid.add(innerButton);
}

ImageIcon player= new ImageIcon("player.JPG");

//starting position     
grid.get(0).setIcon(player);

//wanting to move to next button when I select the near by button       
for(int i = 0; i < grid.lastIndexOf(theifPerson); i++){
    grid.get(i).setIcon(null);
}

任何帮助都是最好的。

谢谢。

EN

回答 2

Stack Overflow用户

发布于 2014-04-24 12:21:41

您可以向按钮添加actionlistener,一旦按钮被按下,它就会搜索所有按钮以找到具有非空图标的按钮,并将按下的按钮的图标切换为非空图标

票数 1
EN

Stack Overflow用户

发布于 2014-04-24 12:23:26

假设您在每个JButton上都附加了某种类型的ActionListener,这样您就可以知道用户何时单击某个JButton,如果您没有单击,请查看How to Use Buttons, Check Boxes, and Radio ButtonsHow to Write an Action Listener

当用户单击按钮时,将调用actionPerformed方法。在这里,您希望确定单击了哪个按钮,将最后一个按钮的图标属性设置为null,并设置所单击按钮的图标...

这将要求您知道最后一个“活动”按钮

代码语言:javascript
复制
private int activeButton;
private ImageIcon player;
//...
grid.get(0).setIcon(player);
activeButton = 0;

然后,您只需更新当前状态...

代码语言:javascript
复制
public void actionPerformed(ActionEvent evt) {
    Object source = evt.getSource();
    if (source instanceof JButton) {
        JButton clicked = (JButton)source;
        grid.get(activeButton).setIcon(null);
        clicked.setIcon(player);
        activeButton = grid.indexOf(clicked);
    }
}

例如..。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23259662

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档