© Adam L. Davis 2020
A. L. DavisModern Programming Made Easyhttps://doi.org/10.1007/978-1-4842-5569-8_18

18. Swinging Graphics

Adam L. Davis1 
(1)
Oviedo, FL, USA
 

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.
../images/435475_2_En_18_Chapter/435475_2_En_18_Fig1_HTML.jpg
Figure 18-1

The Hello Window

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.
../images/435475_2_En_18_Chapter/435475_2_En_18_Fig2_HTML.jpg
Figure 18-2

A window with a JFrame

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:

../images/435475_2_En_18_Chapter/435475_2_En_18_Figa_HTML.jpg The showMessageDialog method of JOptionPane is similar to JavaScript’s alert method, in that it shows a pop-up window.
1   button.addActionListener(e -> JOptionPane.showMessageDialog(this, "Hello!"));

This uses a Java lambda expression since ActionListener has one abstract method and thus is a functional interface as we learned earlier.

The Groovy syntax is slightly different (it only requires a { and }).
1   button.addActionListener({e -> JOptionPane.showMessageDialog(this, "Hello!")})
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.
../images/435475_2_En_18_Chapter/435475_2_En_18_Fig3_HTML.jpg
Figure 18-3

Running the fake browser

Griffon

Griffon 1 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:
bintrayRepositories = [
    "griffon/griffon-lazybones-templates",
    "pledbrook/lazybones-templates"
]
To begin a new project type, use the following:
$  lazybones create griffon-swing-groovy griffon-example

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:

Java 2D
  • JavaFX3

  • JFreeChart4

  • Piccolo2D5

  • JMagick6

Java 3D
  • JOGL7

  • JMonkeyEngine8

JavaScript 2D
  • D3.js9

  • Highcharts10

JavaScript 3D
  • three.js11

Graphics Glossary

  • Component: Any graphical element defined in the Java graphics API.

  • Double buffering: A technique used in graphics in which elements are drawn in memory before being sent to the computer screen. This avoids flicker.

  • Frame: In Swing, the frame (JFrame) is used to represent what we typically call a “window” in the GUI.

  • GUI: Graphical user interface.

  • Layout: Strategy used by Swing for arranging components within a panel or other component.

  • Menu: There are two kinds of menus: a windows built-in menu (JMenu) and a pop-up menu (JPopupMenu).

  • Menu item: In Swing, the JMenuItem represents one line of a menu that can have an action associated with it.

  • Panel: In Swing, JPanel is used to contain other components.

  • Pixel: Smallest unit of the screen that is drawable. A typical screen has millions of pixels that are arranged in a grid.

  • Window: Rectangular section of the screen. In Swing, the Window object has no border, so it can be used for a splash image, for example.

Summary

You just learned the following:
  • Creating a cross-platform GUI in Java and Groovy

  • How to make a web browser worse than IE

  • Some of the available graphics libraries

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset