Swing is the Java API for building cross-platform GUIs (graphical user interfaces).
If you ever want to write a graphical program (a computer game, for example), you will have to use Swing, or JavaFX, or something similar.
There are many other libraries for doing graphics in Java, but Swing is built in.
Hello Window
The most basic concept of graphics is getting stuff onto the screen.
The easiest way to do this in Swing is to use JWindow, for example:
1 import javax.swing.*; import java.awt.Graphics;
2
3 public class HelloWindow extends JWindow {
4
5 public HelloWindow() {
6 setSize(500, 500); //width, height
7 setAlwaysOnTop(true);
8 setVisible(true);
9 }
10
11 @Override
12 public void paint(Graphics g) {
13 g.setFont(g.getFont().deriveFont(20f));
14 g.drawString("Hello Window", 10, 20); //x,y
15 }
16
17 public static void main(String[] args) {
18 new HelloWindow();
19 }
20
21 }
Running this code will create a window at the top left of your screen, with the words “Hello Window” printed on it. It should look like Figure 18-1.
In the constructor, the following occurs:
The width and height of the window are both set to 500 pixels.
The window is set to always be displayed (above all other windows) with the setAlwaysOnTop method.
Finally, setVisible(true) is called to make the window visible.
The paint method gets called every time the window is drawn on the screen. This method simply does the following:
Sets the font size to 20
Draws the string “Hello World” at coordinates x=10, y=20 (coordinates are always in pixels)
You might notice that the “window” doesn’t have any edges, header, menu, or minimize/maximize icons that you’re used to (to close it, you need to press Ctrl+C). To get these things, you use a JFrame. Here’s a very simple example:
1 import javax.swing.*;
2
3 public class HelloFrame extends JFrame {
4
5 public HelloFrame() {
6 super("Hello");
7 setSize(500, 500); //width, height
8 setAlwaysOnTop(true);
9 setVisible(true);
10 setDefaultCloseOperation(EXIT_ON_CLOSE);
11 }
12
13 public static void main(String[] args) {
14 new HelloFrame();
15 }
16
17 }
Running this code creates a 500×500 “window with frame” with the name “Hello” (Figure 18-2), and closing the window would exit the application.
Push My Buttons
Buttons are one of the ways that users can interact with your program. To cause something to happen when a button is pressed, you use an ActionListener, for example:
The showMessageDialog method of JOptionPane is similar to JavaScript’s alert method, in that it shows a pop-up window.
Swing has many interfaces that end with the word Listener, such as
KeyListener
MouseListener
WindowListener
The Listener pattern is very similar to the Observer design pattern.
Fake Browser
Let’s make a web browser!
Let’s begin by adding the imports necessary:
1 import java.awt.*;
2 import java.awt.event.*;
3 import java.io.*;
4 import java.net.*;
5 import javax.swing.*;
Then let’s continue by creating the fields and constructor for the class, as follows:
1 public class Browser extends JFrame {
2
3 JTextField urlField = new JTextField();
4 JEditorPane viewer = new JEditorPane();
5 JScrollPane pane = new JScrollPane();
6
7 public Browser() {
8 super("Browser");
9 setSize(800,600);
10 setAlwaysOnTop(true);
11 setDefaultCloseOperation(EXIT_ON_CLOSE);
12 init();
13 }
JTextField will be used to input the URL. JEditorPane is used to show the HTML, and the JScrollPane allows the page to be scrollable.
Next, we define the init() method to put everything together.
1 private void init() {
2 viewer.setContentType("text/html");
3 pane.setViewportView(viewer);
4 JPanel panel = new JPanel();
5 panel.setLayout(new BorderLayout(2,2));
6 panel.add(pane, BorderLayout.CENTER);
7 panel.add(urlField, BorderLayout.NORTH);
8 setContentPane(panel);
9 urlField.addKeyListener(new KeyAdapter() {
10 @Override
11 public void keyReleased(KeyEvent e) {
12 handleKeyPress(e);
13 }
14 });
15 }
The viewer is set as the viewport view of the JScrollPane, so it can be scrolled.
JPanel is created with a BorderLayout. This allows us to arrange urlField on top of the scroll pane, much as in a real browser. KeyListener is used to call handleKeyPress whenever a key is pressed inside urlField.
Next, we fill out the handleKeyPress method.
1 private void handleKeyPress(KeyEvent e) {
2 if (e.getKeyCode() == KeyEvent.VK_ENTER) {
3 try {
4 viewer.setPage(new URL(urlField.getText()));
5 } catch (MalformedURLException ex) {
6 ex.printStackTrace();
7 } catch (IOException ex) {
8 ex.printStackTrace();
9 }
10 }
11 }
This method simply sets the page of JEditorPane to the URL from urlField whenever the Enter key is pressed.
Finally, we define the main method.
1 public static void main(String[] args) {
2 new Browser().setVisible(true);
3 }
Run your app from Chapter 17. Open your fake browser, and point it to the app at http://localhost:8000/. It should look like Figure 18-3.
Griffon
Griffon1 is a desktop application platform inspired by Grails. It’s written in Java, so it can be used from pure Java, but using Groovy adds additional capabilities.
To get started, first install Lazybones2 and Gradle. You can install them using the following commands:
$ curl -s http://get.sdkman.io | bash
$ sdk install lazybones
$ sdk install gradle
Next edit the lazybones config file to add the griffon-lazybones-templates repository. Edit $USER_HOME/.lazybones/config.groovy and put the following:
This will create a project using Groovy and Swing and named griffon-example. Fill in appropriate responses to each prompt (it will ask you to supply a package, version, class name, and other values). Use the lazybones list command to see what other types of projects are possible.
Griffon uses the MVC design pattern and Groovy DSL to make it much easier to build Swing applications.
Advanced Graphics
Although far beyond the scope of this book, there are several libraries that can be used for 2D or 3D graphics. Here are some of them: