Пример Swing UI

  1. import scala.swing.Swing._
  2. import scala.swing._
  3. import scala.swing.event._
  4. import java.awt.{Color, Graphics2D, geom}
  5.  
  6. object PaintApp {
  7.   def main(args: Array[String]) = PaintAppSwing.main(args)
  8.  
  9.   object PaintAppSwing extends SimpleSwingApplication with Runnable {
  10.     val SIZE = 500
  11.  
  12.     val path = new geom.GeneralPath
  13.     val at = new geom.AffineTransform
  14.     at.rotate(Math.toRadians(10), SIZE / 2d, SIZE / 2d)
  15.     var rotate = true
  16.     var sleep = 40
  17.  
  18.     lazy val ui = new Panel {
  19.       background = Color.WHITE
  20.       preferredSize = (SIZE, SIZE)
  21.  
  22.       focusable = true
  23.       listenTo(mouse.clicks, mouse.moves, mouse.wheel, keys)
  24.       reactions += {
  25.         case e: MousePressed => path.moveTo(e.point.x, e.point.y)
  26.         case e: MouseDragged => path.lineTo(e.point.x, e.point.y)
  27.         case e: MouseWheelMoved =>
  28.           sleep += e.rotation
  29.           if (sleep < 1) sleep = 1
  30.           else if (sleep > 300) sleep = 300
  31.         case KeyTyped(_,'r',_,_) => rotate = !rotate
  32.         case KeyTyped(_,'c',_,_) => path.reset
  33.       }
  34.  
  35.       override def paintComponent(g: Graphics2D) = {
  36.         super.paintComponent(g)
  37.         g.drawString(s"Wheel - Change speed [$sleep], C - Clear, R - Rotate [$rotate]", 10, size.height-10)
  38.         g.setColor(Color.BLACK)
  39.         g.draw(path)
  40.       }
  41.     }
  42.  
  43.     def top = new MainFrame {
  44.       title = "Rotate Paint"
  45.       contents = ui
  46.     }
  47.  
  48.     def run() {
  49.       while (true) {
  50.         if (rotate) path.transform(at)
  51.         ui.repaint
  52.         Thread.sleep(sleep)
  53.       }
  54.     }
  55.     new Thread(this).start
  56.   }
  57. }
Позволяет рисовать такие штуки:
https://i.imgur.com/UHl9nyB.gif https://i.imgur.com/q3mysMs.png

Реклама

Мы в соцсетях

tw tg yt gt