How to code Java #7 – Coding GUI apps

So far in our Learn to Code series, all of the apps we’ve built have used keyboard-only input and displayed their wares via the system console (DOS prompt). The console is a great option for building simple apps, no question, and it’s allowed us to get to know the coding basics quite quickly.

But in this article, we start playing with the grown-up toys and begin looking at how to build genuine graphical user interface or GUI-based apps.

GUI Basics

guiGraphical user interfaces are the stuff all productivity apps are made from, and while good interface design is a science in itself (university subjects can cover this topic alone), the actual components are easy to learn.

Every interface is made from a series of components, all of which are accessible to the Java programming language. In fact, Java actually has two component sets or ‘frameworks’. It originally shipped with the Abstract Windows Toolkit (AWT), but later included the alternative called Swing Components.

The difference is that while AWT essentially hooks into the operating system’s application programming interface (API) to create some components, Swing draws its own, making it more independent of the OS and delivering a more consistent interface across the different platforms. However, Java still relies on both, using AWT for the basic stuff and Swing for the rest.

Your first GUI app

firstJust about any general-purpose programming language can create a GUI application and you can do a very basic app in Java with around half-a-dozen lines of code.

Grab hold of our source code pack from our website. Unzip it, unzip the FirstGuiApp file archive and load the FirstGuiApp.java source code into the NetBeans IDE. (Don’t have NetBeans? Get it here, but make sure you install the latest Java Development Kit or JDK first.)

The very first thing you need to create a GUI app is what’s called a ‘JFrame’, a window on which you’ll draw everything else to do with your app. All of the code that matters for our app appears inside the ‘main’ method. The first line creates the JFrame object imaginatively called ‘frame’ and gives it the title ‘Hello World! – from APC Magazine’.

Next up, we set the size of the JFrame using the ‘setSize’ method, giving the width and height of the frame in pixels. We’ve made ours 600 pixels wide by 400 high for no particular reason.

The following line then tells Java how to set the location of the new frame – by setting the location relative to nothing (null), we’re just saying ‘create the frame and plonk it in the middle of the screen’. You don’t have to tell Java where the centre of the screen is, either – it’s clever enough to figure that out for itself.

The fourth line in the main method tells Java what to do with the app when we close the frame – that is, when you hit the top-right Windows close button. In this case, we’re telling Java we want to close the app when the window closes (EXIT_ON_CLOSE).

Without this line, closing the frame would keep the app alive but hidden – this can be useful depending on the context of your app, but for a simple app like this, closing the frame should also close the app.

Responsible coding means you release system resource like memory when you’re finished with them, so they’re available for other apps.

And finally, the last line tells Java to make the frame visible, so it can be seen on the screen. Putting this codeline last when creating your interface is a good habit to get into because it ensures the frame isn’t shown until drawing of all components is completed.

In extreme cases, make the frame visible first can reveal the other components being drawn one-by-one – it mostly happens in a flash, but it’s just good coding etiquette to set up the frame first before you make it visible.

Run the app and you’ll see it does nothing other than draw a frame with a title. Think of it as the blank canvas on which you’ll build your app masterpieces!

Adding GUI components

Now we get to the fun bit – adding components and building up the user interface. Rather than get too technical this time, we’re just going to introduce a whole range of components into a second app you’ll find in the zipped folder called ‘GuiComponents’ to show you how they’re defined and called.

These components aren’t specifically coded to do anything in the app, but you’ll find some (like the JTextArea) have plenty of built-in functionality ready to go. Here’s just a few of what you’ll find:

JButton

This is the standard command button in Java and few apps will get by without at least one of these somewhere.

JButtons can be operated by a mouse left-click or you can tap them if using a touch-screen device. You can add text to the button and even give it an icon if you wish. There’s nothing you need to do to enable touch-screen operation – it all happens automatically, courtesy of the operating system.

JCheckBox

The JCheckBox allows you to add on-off style custom feature switching to your apps without the user having to dive into a menu (you’ll probably see them in printer driver software, for example).

Again, its left-click or tap operation and they’re a toggle mechanism – click-on, click-off.

JTextField & JPasswordField

TextFields are a single-line text input component you implement to allow a user to type in their name or address or whatever. You can preload it with text and set the default visible length of the field. You can even set the font type, style and size.

JPasswordField, on the other hand, is the component you use when asking the user to enter a password and want to keep that text hidden. You can load it up with default (hidden) text and again, set the default visible length.

JRadioButtons

radioJRadioButtons perform a similar function to JCheckBoxes but with one important addition – you can link multiple radiobuttons together and have them function in a mutually-exclusive fashion.

In other words, you can choose any one but only one of the buttons at a time. This is optional and the way you do it is to add the JRadioButtons to a ButtonGroup, which we do with the codelines:

radiogroup.add(radio1);
radiogroup.add(radio2);
radiogroup.add(radio3);

We’ll talk about adding components to the JFrame in a second, but the important thing here is you don’t add the ButtonGroup to the JFrame – it’s not a GUI component, rather an abstract class.

Instead, you add the JRadioButtons directly to your display panel. Just make them items of the same ButtonGroup to get mutually-exclusive operation.

JTextArea

twWant to make your own text editor? JTextArea is the component for you.

It provides large-area text input panel, to which, you can add cool extras like line-wrap and word-wrap, even change the font and colour of the text. Java also has a JScrollPane component we haven’t added here that provides the ability to scroll the text beyond the visible area, both horizontally and vertically.

Even with no extra code, you can already copy/paste/delete/move text, so it’s full of beans right from the get-go.

JLabel

labelJLabels are really useful components – you can use them to provide simple text labels to things, but you can also use them to display images, like we’ve done here.

The text ‘APC Magazine’ underneath the cover image is part of the JLabel and here, is added the same time as the image. There are extra methods (setVerticalTextPosition and setHorizontalTextPosition) that determine the text location relative to the image.

If you’re thinking about doing extra-cool stuff like image manipulation (rotation, changing geometry and the like), JLabel isn’t the way to do it – JPanel is much better for this. Still, JLabel is a convenient option for simple image display.

ImageIcon

To display an image in a JLabel, JButton or other component that supports images or ‘icons’, you first load it into an instance of the ImageIcon class, which supports JPEG, GIF and PNG images straight off the bat.

You’ll notice in the codeline the filename is ‘\resources\magcover.jpg’. The ‘\resources’ folder is a subfolder of the GuiComponent project folder – you make that folder yourself, but it’s a way of adding extra files or ‘assets’ to your apps in an app-friendly way.

Take a look at the GuiComponent app source code folder and see the magcover.jpg image inside that resources folder.

JSlider

To scale something or adjust audio volume for example, JSlider is your go-to component. You can set the major (longer) and minor (shorter) ‘ticks’ along the slider control or just do without them.

It’s another commonly-used component and the perfect way to perform this type of task.

JList

listEveryone loves lists and JList is a really versatile component with lots of tricks. It can handle multiple selections at once and you can set how much of the list (how many rows) are visible.

However, to do that (and get the automatic scrollbars), you need to use the ‘JOptionPane’ component, Java’s scrollable content box. You add the JList to the JOptionPane, and then add the JOptionPane to your display area. It’s a little clunky, but only because you’ve got ultimate control over how the content is displayed.

The items in the JList come from a String array that you can add anonymously when you create the JList. It’ll also automatically set the list width to the longest word.

JComboBox

comboComboboxes are great GUI components, they let you create a tight little compact control of fixed options the user can select from. They’re also known as drop-down boxes.

The one thing I’m disappointed about Java’s implementation is that it doesn’t allow you to also type in your own option like a textfield. Other languages incorporate the drop-down menu with the textfield to make it a truly ‘combo’ box.

Still, the JComboBox is incredibly useful and you’ll likely use these in your apps by the bushel.

 

Adding to the frame

simpleSo far, all we’ve done is create all of these GUI components. In order for them to be seen, we need to add them to our display panel, which in our case is straight onto the JFrame called ‘frame’.

You do this with the simple ‘add’ method. Given the way we’ve set up the JFrame, the order in which you add the components is the order in which they’re displayed. Another thing, if you now launch the app and click-and-drag a corner or edge of the app window, you’ll see that JFrame automatically realigns the components depending on the shape and size of the frame.

Now, true, the whole thing looks like a dog’s breakfast at the moment, but Java has far more competent ways of arranging components, using its LayoutManager class. If you go back to the top of the main method, you’ll see the codeline:

frame.setLayout(new FlowLayout());

The Layout Manager provides three basic ways of laying out your components – flow, grid and border. We’re using ‘flow’ here and as it sounds, it simply flows on one GUI component after another. GridLayout, however, lets you break up your display window into a grid pattern, while BorderLayout divides the window into a series of compass-like regions.

Java’s Layout Manager provides you far more control over the placement of components than we’re using here (you can mix layout managers together, for example), to give your app a look and feel that’s easy to use, especially if you resize the app window.

This is a crucial feature, particularly when building Android apps for mobile devices with varying screen resolutions and sizes – having your apps correctly fill the display area is what a good layout manager does automatically for you. We’ll look more in-depth at layout managers shortly.

Have a play!

In the meantime, have a play around with the source code for this project. See what happens if you comment out that ‘setLayout’ codeline. Try changing the order of the ‘frame.add’ codelines to see what effect it has.

Hopefully, you can see there is a basic pattern to how Java creates and allows you to modify GUI components – you create them, modify them with ‘set’ methods and add them to your display area.

Next time, we’ll look at ‘Listeners’ – classes that monitor GUI components to fire up our code functions.