2010-09-09 78 views
3

想要將Java Swing DatePicker轉換爲Scala,但在代碼的某個區域面臨困難。我應該如何將if(x> 6)部分翻譯成scala?Scala Swing Date Picker

最初的Java從http://www.roseindia.net/tutorial/java/swing/datePicker.html

for (int x = 0; x < button.length; x++) { 
        final int selection = x; 
        button[x] = new JButton(); 
        button[x].setFocusPainted(false); 
        button[x].setBackground(Color.white); 
        if (x > 6) 
          button[x].addActionListener(new ActionListener() { 
            public void actionPerformed(ActionEvent ae) { 
              day = button[selection].getActionCommand(); 
              d.dispose(); 
            } 
          }); 
        if (x < 7) { 
          button[x].setText(header[x]); 
          button[x].setForeground(Color.red); 
        } 
        p1.add(button[x]); 
      } 

轉換斯卡拉

for (x <- 0 until buttons.length) { 
      val selection = x 
      buttons(x) = new Button { 
       focusPainted = false 
       background = Color.white 
      } 
      if (x > 6) 
       buttons(x).reactions += { 
        case ButtonClicked(_) => { 
         day = buttons(selection).action 
         d.dispose() 
        } 
       } 
      if (x < 7) { 
       buttons(x).text = header(x) 
       buttons(x).foreground = Color.red 
      } 
      contents += buttons(x) 
     } 
+0

什麼似乎與所提出的翻譯問題?你越是幫助我們幫助你,你就越有可能得到很好的幫助。 – 2010-09-09 16:59:56

回答

4

有什麼不對您的翻譯採取?它不工作?我一眼就可以看到的唯一的事情是,你不聽按鈕:

button(x) listenTo button(x) 

但我不知道一個按鈕,聽自己多麼明智的,或者是否有任何令人討厭的後果。你不需要需要將反應添加到按鈕本身,你可以將它們添加到日期選擇器本身。

而且,像zipWithIndex可能是最好你做它的方式:

buttons.zipWithIndex foreach { case (button, x) => 
    //no need to use buttons(x) 
} 
0

if(x < 7)可以通過else替代,那將是更清晰。

你可以使用一個匹配語句,以及:

x match { 
    case xx if xx > 6 => ... 
    case _ => ... 
}