Create a Swing GUI in Java

This article explains how to create simple application that is shown in the figure on the right, giving its source code as well.

To place buttons, text labels and other components on the program window, you need to understand about JPanel. It is a kind of container for components, which occupies the rectangular piece on the screen and shows the components arranged in some simple way. How exactly the components are arranged depends on which layout have you set to that panel. For the manual programming you will likely need to know at least the BorderLayout which places four components at the sides and one large component into the middle, then the FlowLayout which usually arranges them side by side into horizontal row and finally the GridLayout which arranges components into arbitrary n * m table. There are more of them, but others seem too complex for beginners. The key idea here is that a "component" can be not just a button or check box - it can also be another JPanel. You can get a complex user interface by just putting panels one inside another and choosing the layouts for them.

Once you have an instance of JPanel, call the .setLayout method to set the layout and then the .add method to add the components to it. For the BorderLayout, you need to give the location as a second parameter. For instance, call myPanel.add(myButton, BorderLayout.North) to place your button at the top edge.

The top level container, which appears on the screen representing java application, is not a JPanel but JFrame. Call myJFrame.getContentPane().add(myJPanel, BorderLayout.Center) to add your main panel to the instance of JFrame.

To make your application to do more than just appear you also need to understand the ActionListener interface. Every non-abstract ActionListener has a single method, actionPerformed, which is called automatically when the user makes an "action" with the component on which the listener is registered (the action with button is, obviously, pressing it). To register action listener for the button or other component, call the method .addActionListener.

Steps

Making the Overall Frame

  1. Create a class that extends the JFrame class. This class will hold all of your GUI components, such as buttons and text fields.
  2. Plan the overall layout of your first application. A good start could be a central panel with BorderLayout with another panel at the bottom (BorderLayout.South). This second panel may have the FlowLayout and contain several buttons, check boxes and other similar controls. Finally, place the big JTextArea into the center of the central component. You will be able to use its getText() and setText() methods to do some text-based interaction with the user.
  3. Write constructor to your class. This constructor must create all panels and components you plan, place them properly into each other and add the final panel the "holds all" to you frame (myFrame.getContentPane().add(myLargePanel, BorderLayout.Center).
  4. Write the main method which will be the program's entry point. In this method, create an instance of your frame, set the initial size and location (use .setSize(x,y) and .setLocation(width, height) ) and make it to appear on the screen by calling .setVisible(true).

Programming responses to the user actions

  1. Make your frame implement the ActionListener interface. This will allow your class to listen to components' activities.
  2. For every button, check box or other control that you have created, invoke its method .addActionListener, passing your frame (this) as parameter.
  3. Override ActionListener's abstract method, actionPerformed(ActionEvent event). In this method, you should put if statements checking where does the action event come from. This if statement should have a condition that says something like "if (event.getSource() == button1)". This checks where the event came from and if it came from your button. Inside the if statement, do whatever needs to be done when your button is pressed.
  4. JTextArea has a method .setText("myText") which seems good as the way to program some visible response on your action.



Tips

  • It is not much more difficult to implement the MouseListener interface and use .addMouseListener to register it to any component.
  • If you need to ask some input string from the user, call the static method JOptionPane.showInputDialog(this, "My message"). The first parameter must be your application frame or some panel (the input box will appear in the center of the parent). The method returns the value that user enters into the dialog box.
  • It is possible to put all components into single panel using GridBagLayout, but this class is more difficult to master.
  • If you want to draw your own graphical objects (like chessboard), read about the Canvas component. It can be placed into your application like any other, but you need to write method .paint which is fully responsible for drawing it.
  • In many practical applications the most useful Swing component is JTable. After you master the basic, proceed directly to it.

Warnings

  • Some development environments offer the possibility to compose the Swing GUI in a "user friendly" way. However they are frequently unable to complete a panel with advanced features properly. Such features include trees, tables, lists and combo boxes that change they content while the program is running, also components with custom data models and so on. The code, composed in a "user friendly" way may become a real nightmare if you need later to finish it manually. Hence do not stick to any "user friendly GUI designer" too much as it will restrict your programming power to its limited capabilities.
  • Swing is a single thread application. If your action handling takes too much computing time, it will "freeze" until your .actionPerformed method returns. Learn and use java multithreading to keep the Swing "alive" while your time-consuming process is running.
  • The most of the methods of the Swing components can only be safely called from the event dispatching thread (the one that calls .actionPerformed and other similar listener methods). If you need to call them from some other thread (for instance, to update the progress bar or show results of some long-running process), read about the SwingUtils.invokeLater.

Related Articles

Sources and Citations

  • The Java API - Contains documentation on all predefined classes.

Source Code