希望将 Java Swing DatePicker 转换为 Scala,但在代码的一个方面遇到困难。我应该如何将 if (x > 6) 部分翻译成 scala?
取自 http://www.roseindia.net/tutorial/java/swing/datePicker.html 的原始 Java
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]);
}
转换后的 Scala
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)
}
最佳答案
你的翻译有什么问题?它不起作用吗?我唯一能一目了然的是你没有听按钮:
button(x) listenTo button(x)
但我不确定监听自己的按钮有多明智,或者是否会产生任何不良后果。您不需要将 react 添加到按钮本身,您可以将它们添加到日期选择器本身。
另外,zipWithIndex
之类的东西可能比您完成它的方式更可取:
buttons.zipWithIndex foreach { case (button, x) =>
//no need to use buttons(x)
}
关于Scala Swing 日期选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3673834/