tags:

views:

76

answers:

2

Looking to convert Java Swing DatePicker into Scala but facing difficulty in one area of the code. How should I probably translate the if (x > 6) part into scala?

Original Java taken from 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]);
            }

Converted 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)
        }
+3  A: 

What is wrong with your translation? Is it not working? The only thing I can see at a glance is that you do not listen to the button:

button(x) listenTo button(x)

But I'm not sure how wise a button listening to itself is, or whether there are any nasty consequences. You don't need to add the reactions to the button itself, you could probably add them to the date picker itself.

Also, something like zipWithIndex is possibly preferable to the way you have done it:

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

The if(x < 7) could be replaced by else, that would be clearer.

You could use a match statement as well:

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