Make a Window
Interactive development is fun.Â Fire up a Clojure REPL, and type this:
(import 'javax.swing.JFrame) (def frame (JFrame. "Hello Frame")) (.setSize frame 200 200) (.setVisible frame true)
Hey Presto, there’s a window!Â (It might not pop to the front, so check your task bar.)
JFrame is Swing’s all-purpose window class.Â This example created a frame, set its dimensions to 200×200 pixels, and “turned it on” by calling setVisible.
Containers and Frames
Our new frame doesn’t look like much; let’s give it some content.Â More specifically, let’s give it a container.Â Swing GUIs are laid out as a nested hierarchy of containers.Â All containers — except the top-level window — are sub-classes of JComponent.Â This is called the containment hierarchy.
Although it’s technically possible to add GUI elements directly to a top-level container like JFrame, it’s more correct to use a content pane.Â We’ll use JPanel, a general-purpose container:
(import 'javax.swing.JPanel) (def panel (JPanel.)) (.setContentPane frame panel)
A panel by itself doesn’t show anything, so lets make a button and add it to the panel.
(import 'javax.swing.JButton) (def button (JButton. "Click Me!")) (.add panel button)
Hey, it’s not there!Â That’s because Swing wasn’t designed with interactive development in mind.Â To make your button visible, call:
The revalidate method is not something you’ll read about in most Swing tutorials, because in pre-compiled Java it’s rarely necessary.Â Basically, it tells Swing, “I just changed the layout, you need to redraw stuff.”Â Starting at our JButton, Swing searches up the containment hierarchy to the top-level container, and redraws it.
Next step: Action!Â My next post will talk about enabling GUI events with ActionListener.