我正在尝试制作一个java GUI程序" game"。
有五个按钮,每个按钮都有一个字符作为按钮标题。单击按钮时,该按钮的标题将与右侧邻居交换。如果单击最右边的按钮,则最左边的按钮具有该标题,因此它们都会切换(包裹)。
目标是按字母顺序排列,从而结束游戏。
我无法想到一种直观的方式来切换角色而无需制作五个按钮。
String str = "abcde"; // DEBUG ARGUMENT STRING
setCaptions(str);
获取字符串,从中创建char数组并创建按钮的方法......
void setCaptions(String string){
char[] charArray = string.toCharArray();
ArrayList<Character> arrList = new ArrayList<Character>();
for (int x=0; x < charArray.length; x++) {
String str = Character.toString(charArray[x]);
btn = new JButton(str);
btn.setFont(myFont);
pane.add(btn, "LR");
btn.addActionListener(new SwitchAction());
arrList.add(str.charAt(0));
}
// check the order...
System.out.print(arrList);
if (arrList.get(0) < arrList.get(1)
&& arrList.get(1) < arrList.get(2)
&& arrList.get(2) < arrList.get(3)
&& arrList.get(3) < arrList.get(4)) {
lbl.setText("SOLVED");
}
}
ActionListener切换字幕,我无法弄清楚......
public class SwitchAction implements ActionListener {
public void actionPerformed(ActionEvent evt) {
String a = btn.getText();
System.out.println(evt.getActionCommand() + " pressed"); // debug
// something goes here...
}
}
答案 0 :(得分:2)
你应该有一个JButton的数组或ArrayList,ArrayList<JButton>
并将你的按钮放到这个列表中。
您的ActionListener将需要对原始类的引用,以便它可以获取ArrayList。然后它可以遍历数组列表找出按下哪个按钮,这是它的邻居,并进行交换。因此,通过构造函数参数传递该引用,然后在actionPerformed方法中,调用getList()
或类似的&#34; getter&#34;获取ArrayList并迭代它的方法。
即,
public class MyListener implements ActionListener {
private OriginalGui gui;
public MyListener(OriginalGui gui) {
this.gui = gui;
}
public void actionPerformed(ActionEvent e) {
JButton pressedButton = (JButton) e.getSource();
ArrayList<JButton> buttonList = gui.getButtonList();
// ... iterate through list and find button.
}
}