Swing Help

Course Home Page

To begin your Swing program, lay out the program using stepwise refinement, draw a picture of your GUI design, and list the components you want to use. You'll then need to create an instance of a window or frame object – the preferable way to do so at this point is to extend JFrame and add elements for your own class. You will also need to include the ability for your program to know when the user clicks the close box on the frame, to end the program. For the present, use the method setDefaultCloseOperation(), inherited from JFrame, with the JFrame final variables:

   class SomeFrame extends JFrame
   {
	 public SomeFrame()
	 {
	      // set the title, size, location, etc.
              // add more stuff here...
              setDefaultCloseOperation( EXIT_ON_CLOSE );
              setVisible(true);
         }
   }

Our suggestion is to start small – begin by only writing the constructor to set the size and location of the frame object, and to make the program end. Then write main, and create an instance of the frame. Compile and run the program, to make sure the frame will show up on screen, and that it will close when the user clicks the close box. Once you've got that structure down, you can go back to the line above that says "add more stuff..." and start to do so. If you add elements one at a time, then compile and check them, you can find/figure out errors much more easily than if you write large blocks of code and don't know where the problem might lie. Get your GUI created and working, remember to add the listener(s) you need for buttons, etc., and afterwards write the methods you need to use to respond to the listener(s) and to process any input or print results.

 
LAYOUT MANAGERS

These are the more common options for layout managers, although they are not the only ones available (the others tend to be somewhat more complicated to implement):  

BorderLayout: This layout manager is the default layout manager for JFrames. It divides the area into five sections; each section can hold one item (although that item can be a JPanel with multiple items on it).

There are two options to specify the area where you want the element placed: by including a String in the add() method, or by using the predefined constants from the class, BorderLayout.SOUTH, BorderLayout.NORTH, BorderLayout.EAST, BorderLayout.WEST in the add() method. I encourage you to do the latter - misspellings will be caught at compile time, whereas with Strings they will not be discovered until runtime.

If items are only added in some of the areas, the CENTER (if used) will expand to fill all available remaining space. If items are added without specifying a location, the CENTER is the first location filled.
FlowLayout:

This layout manager is the default layout for JPanels. As you add components, they are placed on the panel or frame in the sequence added, and will simply be put in the next location to the right of the previous item, or, if there is not enough space, on the next row below it.

The rows and columns do NOT need to be of uniform size; however, if the user resizes your window, the components will realign across the new row and column sizes.
GridLayout: This layout manager is created with the number of rows and columns specified in the constructor. Whichever is more important to you - rows or columns - should have a value, and the other parameter should be 0, e.g.

GridLayout gl = new GridLayout(5, 0);
setLayout(gl);


All locations are of uniform size, and there is no way to combine two locations to form a larger one. It is particularly useful for including several buttons (as in a calculator program) or labels and fields that are the same size.
 
USEFUL CLASSES AND METHODS

In the tables below, I've pulled out several classes and methods that you may find useful. There are many more than I've listed – all objects have no-argument constructors as well as those below, and I've only put the constructors with arguments which you may wish to use. The first column contains the return type for the method, if it returns an object or value. The second column is the name of the method and its parameters, and the third column is a brief description. You can find additional information in either the lecture notes, the textbook chapters, or any Java reference book that includes Swing. I've included brief info on superclasses, since there are many methods in the superclasses which are not listed below nor in the separate class listings. Remember that these are only a few of the available Swing methods and classes. For more details and documentation, go to the Java API's at http://download.oracle.com/javase/6/docs/api/index.html

JFrame (extends java.awt.frame; it is a Container)
    JFrame(String name) A constructor which will use the String argument to set the JFrame's title as it creates the object.
void setTitle(String name) Sets the text for the frame title.
void setSize(int a, int b) Sets the size for the frame; the default is 0, 0. The value is in pixels (a common monitor screen size is 1024 x 768 pixels).
void setLocation(int x, int y) Sets the location on screen for the frame; the default is (0, 0), in the upper left corner. The ints given add pixels across and down from 0, 0.
Container getContentPane() Gets the content pane for the frame to be able to add elements; be sure you create a Container reference to locate and access it. Use the content pane to add items to the JFrame object, e.g.,
Container cp = getContentPane();

cp.add(someComponent);
void setLayout(LayoutManager mgr) Sets the layout pattern for the frame. The default layout manager is BorderLayout.
void setBackground (Color c) Sets the background color of the object - this can also be used for any of the objects below. Default final colors are defined in java.awt.Color.
void setVisible(boolean b) Makes the frame visible when the program runs. DON'T forget to do this, or your frame won't show up!!

JPanel (extends JComponent; it is a Container)
    JPanel(LayoutManager mgr) A constructor that will take a layout manager as an argument.
  void setLayout(LayoutManager mgr) Sets the new layout manager for the frame. The default layout manager is FlowLayout.
  void add(Component c) Adds the component to the JPanel.
  void add(Component c, layoutPosition) Adds the component to the JPanel in the specified position - NOTE, this will generally mean you are using the BorderLayout manager which has pre-defined final locations, e.g. BorderLayout.WEST.

JLabel (extends JComponent)
    JLabel(String text) A constructor that sets the text of the label.
  JLabel(String text, int alignment) A second constructor that sets the text of the label, and also positions it on the label. There are final ints defined for horizontal alignment: LEFT, CENTER, RIGHT.
String getText() Retrieves the text of the label - this can be done while the program is running (true for all Components).
void setText(String text) Sets the text of the label. This can be changed while the program is running (true for all Components).

JButton (extends AbstractButton, which extends JComponent)
    JButton(String text) A constructor that sets the text of the button.
  void addActionListener(ActionListener al) Adds an ActionListener to the button so that click can be registered by the program.
  void setActionCommand(String value) Sets the actionCommand value which the ActionEvent returns in response to its getActionCommand() method.
  void setText(String text) Sets the text of the button.
  String getText() Gets the text of the button.

JTextField (extends JTextComponent, which extends JComponent)
    JTextField(int columns) A constructor that will set the number of columns.
  JTextField(String text) A constructor that will set the text in the field.
  JTextField(String t, int c) A constructor that does both of the above things.
String getText() Retrieves the text from the textfield.
void setText() Sets the text in the textfield.
void setEditable(boolean b) Sets whether the user may type into the field or not.

JTextArea (extends JTextComponent)
    JTextArea(int rows, int cols) A constructor that sets the number of rows and columns.
  JTextArea(String text) A constructor which sets the text in the textarea.
  JTextArea(String t, int r, int c) A constructor that does all of the above.
void setEditable(boolean b) Sets whether the user may type into the field or not.
String getText() Gets the text in the textarea.
void setText(String text) Sets the text in the textarea.
void append(String text2) Adds text to the String currently shown in the textarea and displays it on screen.
void insert(String text2, int pos) Inserts text into the String shown at the position indicated by the integer.
 
For each component you wish to use, remember to give it a variable name and create an instance of it as an object (using the keyword new) - then you can use that name and the 'dot' operator to access the above methods. You will need to add() each component to your panel, or use the content pane to add() it to the JFrame (or subclass object). If you want to access components outside the constructor (such as in actionPerformed() ), remember to make them private instance variables in the class.

If you use JButtons, make sure you create and add the listener objects to them, and write actionPerformed() to handle the events when the user clicks the button. You will need to either write an inner class which extends ActionListener and which defines actionPerformed(), or you may set up your class to extend JFrame AND to implement ActionListener, in which case you can simply write actionPerformed() as another method in the class. You will then pass the instance being created to the method as its own listener, using "this". More on this technique in section...
 
ActionListeners
When you use a JButton, you will need to set up an ActionListener to be able to respond to user events. Sometimes you may have more than one button, and need to determine which one the user clicked. In order to do so, you must have a class that implements the ActionListener interface and defines its required method,
public void actionPerformed(ActionEvent ae). The secret to doing this is the ActionEvent object which comes in as a parameter, created by the JVM when the listener is notified of the event. The ActionEvent object has a few useful methods that you may call to get information about what has occurred.

Among other things, the ActionEvent knows the source object which caused the event, as well as a value named actionCommand which is associated with that source. The first of these can be accessed using the ActionEvent parameter's name with
getSource(), and it returns the reference (memory address) of the object producing the event. This allows for comparison of references with the JButtons in your program. This is generally the preferred approach.

The actionCommand for a Button object is accessed through the method
getActionCommand(), and returns (by default) the text value set on the object as a String. In other words, if your JButton's text says "Press me!", that is what will be returned by the method. However, when your button's text is more lengthy, you can also set the JButton's actionCommand when you create it using the JButton method setActionCommand(String value), and if it is set, that String will be returned instead of the actual JButton text. Either of these can be compared to your various buttons' text (or setActionCommand values) using String methods.

When you write your listener class and define actionPerformed(), you will need to use these methods to find out about the event, so that you can make an appropriate response. If your response is very simple, you may write it within the actionPerformed() method; if it is more detailed or complicated, feel free to write and call other methods in the class to keep your code readable.

Top
| Home Page


© 2013 The President and Fellows of Harvard College
Please send comments to The Webmaster
Last modified: Tuesday, 26-Mar-2013 14:21:35 EDT
URL: http://www.fas.harvard.edu/~libe50b/swing.html