Note: All text in bold will be either names of files, commands to type, code segments, or references to the code. Larger code segments will be separated from the main text by a line or two and will not be denoted in bold. Everything should be clear, but if anything is confusing, feel free to contact me and let me know (you can find my email on the main page).
Open up a new file in your favorite text editor (mine is Vim, in case anyone was wondering) and call this file Main.scala. Place the following code inside of this file:
package MyFirstApplet import scala.swing._ import java.awt.Color class MainApplet extends Applet { object ui extends UI { preferredSize = new Dimension(500,600) val frame = new BorderPanel() { layout += (Button("North Button"){} -> BorderPanel.Position.North) layout += (Button("South Button"){} -> BorderPanel.Position.South) background = Color.GREEN } contents = frame def init(): Unit = {} } }
Before moving on, lets figure out what this code does. I am not going to go in depth into the Scala code (as this tutorial assumes knowledge of the language), but I will explain the aspects that relate to making a web applet. First we declare a package statement for our code, then we import the Scala Swing library. This library contains many swing components, but important for our purpose is the Applet class. The main class for our applet is the MainApplet class, which extends Applet. There are two main things to understand within the MainApplet class. The first thing is the ui object, which extends UI. The ui is the main GUI component in which other components are placed (more on that in a moment). Next, we set the preferredSize of the ui. This will be the dimensions for our applet, and we will need to use these number again in the HTML file (see section 3). The simplest design for the ui is to make a frame within the ui which will become the main frame for your applet. By doing this, you can design your applet in the same way that you would design any swing application. Simply build all of your components within the frame, then set the content of the ui equal to the frame (as shown in the code above). The last thing we need in our ui is the init method. This method is abstract in the ui, so we must implement it. Just leave the body of the method blank, as shown. (To be honest, I am not exactly sure what this method does. The Scala API is a bit lacking, especially when it comes to the swing library. If anyone has more information about this method, please send me an email).
And that's it! That is all of the Scala code we need to make our first web applet. Ensure that the code compiles by using the scalac command or the fsc command. Type fsc Main.scala. If there are any compilation issues, resolve them and compile again. Next, we will create an HTML document that will render our applet.