Is Swing dead? I don’t know. I’ve written several Swing apps that I use every day, but I can’t speak for the rest of the world.
What I can say is that I really like Scala Swing. How I wish it was available ten years ago ... you’ll never know.
But getting to the point, after working with Scala Swing a little bit, I decided to see if I could write a web browser with it. The short answer is that here’s what the browser looks like:
And here’s what the Scala Swing source code looks like:
object ScalaBrowser extends SwingApplication { NativeInterface.open val browser = new DJBrowser def top = new MainFrame { title = "Scala Browser" peer.add(browser) size = desiredInitialSize reactions += { case WindowClosing(_) => quit } } override def main(args: Array[String]) { SwingUtilities.invokeLater(new Runnable { def run { val f = top f.peer.setLocationRelativeTo(null) f.peer.setVisible(true) } }) NativeInterface.runEventPump } def desiredInitialSize = { val screenSize = Toolkit.getDefaultToolkit.getScreenSize val w = (screenSize.getWidth * 0.625f).toInt val h = (screenSize.getHeight * 0.625f).toInt new Dimension(w, h) } override def startup(args: Array[String]) {} } class DJBrowser extends JPanel { import java.awt.BorderLayout import javax.swing.JPanel setLayout(new BorderLayout) val webBrowserPanel = new JPanel(new BorderLayout) val webBrowser = new JWebBrowser webBrowserPanel.add(webBrowser, BorderLayout.CENTER) add(webBrowserPanel, BorderLayout.CENTER) }
I’m really tired right now, and I’m sure that code can be improved, but even though I don’t take advantage of the coolest Scala Swing features yet -- such as reacting to events -- I hope you can see that this is a nice improvement over using the Java Swing API.
To see some more interesting Scala Swing code, check out this link at Artima.
It’s important to mention that this code works because of the DJ Native Swing library. Without it, I/we wouldn’t have a free Java/Scala web browser component at all.
If you’re interested in the code, just leave a comment below, and I can create this as a GitHub project. I left the ugly import statements out of the code above, and I also use the sbt-assembly plugin with SBT to build the project. Not a big deal, but not worth sharing here unless folks are interested.