Java 将图标从jbutton移动到jbutton
我设置了一个gridlayout,中间有16个按钮。我在第一个按钮上放置了一个图标 我将如何循环,当用户选择网格上的下一个按钮时,它将图标从旧位置移动到新位置Java 将图标从jbutton移动到jbutton,java,swing,user-interface,jbutton,move,Java,Swing,User Interface,Jbutton,Move,我设置了一个gridlayout,中间有16个按钮。我在第一个按钮上放置了一个图标 我将如何循环,当用户选择网格上的下一个按钮时,它将图标从旧位置移动到新位置 private ArrayList<JButton> grid = new ArrayList<JButton>(); JPanel gridBtnPanel = new JPanel(); gridBtnPanel.setLayout(new GridLayout(4, 4)); for(int i = 0;
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);
}
private ArrayList grid=new ArrayList();
JPanel gridBtnPanel=新的JPanel();
setLayout(新的GridLayout(4,4));
对于(int i=0;i您可以将ActionListener添加到按钮中,一旦按下一个按钮,它将搜索所有按钮,找到一个具有非空图标的按钮,并将按下按钮的图标切换为非空图标,假定每个JButton
都附加了某种ActionListener
,这样您就可以知道用户点击一个,如果你不点击,请查看
当用户单击按钮时,将调用actionPerformed
方法。要确定单击了哪个按钮,请将最后一个按钮的图标属性设置为null
,并设置单击按钮的图标
这需要您知道最后一个“活动”按钮
然后你只需要更新当前状态
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);
}
}
例如…从上一个按钮(i-1)中删除图标,然后将其设置为新的图标(当前i)如何。
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);
}
}