1

I am currently in the process of turning a sudoku solving program into a GUI with scala.swing and running into some trouble with the use of different functions. That is to say, I have a function for completely solving the puzzle, another for offering a hint entry, and another that will reset the grid. The interface consists of 81 individual ComboBox'es (see: https://i.stack.imgur.com/JcT7p.png) and three buttons that perform said functions. My problem is that, while the separate reactions/cases involved reference specifically which buttons/functions to listen to, any button will incite all of the functions. My code for each of the listeners/buttons looks something like the following

listenTo(solve,comb11,comb12,comb13,comb14,comb15,comb16,comb17,comb18,comb19,comb21,comb22,comb23,comb24,comb25,comb26,comb27,comb28,comb29,comb31,comb32,comb33,comb34,comb35,comb36,comb37,comb38,comb39,comb41,comb42,comb43,comb44,comb45,comb46,comb47,comb48,comb49,comb51,comb52,comb53,comb54,comb55,comb56,comb57,comb58,comb59,comb61,comb62,comb63,comb64,comb65,comb66,comb67,comb68,comb69,comb71,comb72,comb73,comb74,comb75,comb76,comb77,comb78,comb79,comb81,comb82,comb83,comb84,comb85,comb86,comb87,comb88,comb89,comb91,comb92,comb93,comb94,comb95,comb96,comb97,comb98,comb99)
  reactions += {
    case ButtonClicked(solve) =>
    ...[working code for solve function]...
  }

(The 'comb##'s are the exhaustive 81 ComboBoxes and the 'solve' is the button that solves the whole puzzle.) If I get rid of all but one of the listener/reaction blocks of code, clicking the remaining button works perfectly. If I try to include two or all of the listener/reaction code blocks, then every button causes ALL functions to be performed, which is clearly confusing and undesirable.

2 Answers2

2

Not sure I understand your problem. But if you use lower case names in pattern matching extraction, these are fresh variables, and have nothing to do with values of the same name defined elsewhere. So to react to the solve button, you need to match against the value solve which you can do by putting it in back ticks:

listenTo(allMyButtons: _*)
reactions += {
  case ButtonClicked(`solve`) =>  // note the back ticks!
  ...[working code for solve function]...
}

Otherwise, why don't you just keep each reaction with each combo box?

val combos = Vector.tabulate(81) { i =>
  new ComboBox(1 to 9) {
    listenTo(this)
    reactions += {
      case ButtonClicked(_) =>
        ... // not important to check the button - we only listen to one!
    }
  }
}
Community
  • 1
  • 1
0__
  • 66,707
  • 21
  • 171
  • 266
0

There is also a shorter way of defining the reaction to a pressed button.

import swing.{MainFrame, FlowPanel, Button}

val frame = new MainFrame {
  contents = new FlowPanel {
    contents += Button("solve")(println("solve"))
  }
  visible = true
}
Tesseract
  • 8,049
  • 2
  • 20
  • 37