2014-04-10 99 views
-1

我想制作一个java GUI程序“游戏”。切换按钮标题游戏

有五个按钮,每个按钮都有一个字符作为按钮标题。当点击一个按钮时,该按钮的标题与右边的邻居交换。如果最右边的按钮被点击,那么最左边的按钮有这个标题,所以它们都会切换(它包裹着)。

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

我想不出一个直观的方式来让字符切换而不必制作五个按钮。

String str = "abcde"; // DEBUG ARGUMENT STRING 
setCaptions(str); 

方法来获取字符串,创建一个字符数组了他们,并创建按钮...

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

回答

2

你应该有一个JButton的数组或列表,ArrayList<JButton>并把你的按钮放到这个列表中。

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