Scala Swing Date Picker

You are looking to convert Java Swing DatePicker to Scala, but run into difficulties in one area of ​​code. How can I probably translate the if (x> 6) part to 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
source share
2 answers

What is wrong with your translation? Doesn't that work? The only thing I can see right away is that you are not listening on the button:

button(x) listenTo button(x)

But I'm not sure how wise the button is listening to itself, or there are any unpleasant consequences. You do not need to add reactions to the button itself, you could probably add them to the date creator itself.

, - zipWithIndex , :

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

if(x < 7) else, .

:

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

Source: https://habr.com/ru/post/1763939/


All Articles