切换按钮字幕游戏



我正在尝试制作一个java GUI程序"游戏"。

有五个按钮,每个按钮都有一个字符作为按钮标题。当单击某个按钮时,该按钮的标题将与右手边的邻居交换。如果单击最右边的按钮,那么最左边的按钮就会有标题,所以它们都会切换(它会环绕)。

目标是让他们按字母顺序排列,从而结束游戏。

如果不制作五个按钮,我想不出一种直观的方式来切换角色。

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...
    }
}

您应该有一个JButton、ArrayList<JButton>的数组或ArrayList,并将您的按钮放入该列表中。

ActionListener将需要对原始类的引用,这样它才能获得ArrayList。然后,它可以遍历数组列表,找出按下了哪个按钮,哪个是它的邻居,并进行交换。因此,通过构造函数参数传入该引用,然后在actionPerformed方法中,调用getList()或类似的"getter"方法来获取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.
  }
}

最新更新