|
Java Tutorial |
SwingBasicsThese pages make up the course notes for my Java programming course (run at Dallam, Milnthorpe, Cumbria). Hopefully they also make a useful self-learning tutorial. What is Swing The creators of Java seem to like coming up with unusual names for things (starting with "Java") and Swing is the name that they gave to the set of packages and classes that are used for creating Graphical User Interfaces (GUIs). Graphical User Interface is the name given to the way of interacting with a computer that we are all used to; i.e. using Windows and a mouse (contrast this to the old days of using a monochrome screen and the keyboard, where only one thing could be done at once, there was no copy'n'paste and you had to remember a set of cammands that had to be typed in to get anything done). Graphical User Interfaces allow users to do things in any order that seems natural to them, rather than in an order set by the computer programmer. This makes the whole process more complicated. Consider adding two numbers together, in the old days we would prompt the user to input one number, then prompt for the second number and then add them together. In a GUI we display a form that has two input boxes and a button. The user can input the number and press the button, but they can also press the button without inputting a number, or close the window and do something else. The way most GUI systems are built, and Java is no exception, is by defining what we want to see on screen from a standard set of components (sometimes referred to as widgets). It is possible to build you own widgets, but normally the standard set is enough. We also have to handle events - such as a button being clicked. Let's have a go As a first example lets create a better user interface for our Bookmarks class that we created when looking at writing Files. If you look at that example, we had to prompt the user twice, because we did not have a form that allowed the URL and Title to be entered at the same time. EasyEclipse comes with a tool to allow us to build the GUI in a graphical way. This may seem like an obvious thing to do, but it wasn't always the case. To get to that tool we need to create a Visual Class. To get started choose File - New - Other. Then choose Java - Swing - JFrame Visual Class ![]() The normal Class dialog will appear, I suggest creating a new package - tutorial.swing - and call the class ![]() Click finish and you should see the Eclipse visual editor ![]() What we need is a form that allows the user to enter a URL and optionally a Title and then Click a button to save the new book mark. The first thing we need to consider is howwe would like these to be laid out on the form. Swing comes with a confusing array of things called "Layout Managers" which are aimed at laying out the components on the form whilst handling things like window resizing and different screen resolutions. We will look at these later. For now we will not use a layout manager, we will just position the elements on the form manually. So we need to set the layout manager to null, to do this click on the on the grey JFrame? in the top window, then choose the properties tab in the bottom window, click the value next to >layout and choose null from the drop down. ![]() By setting the layout to null we get what is known as XYLayout. This allows us to position the components manually. To the right hand edge of the top window is a Palette "Fly-Out" - hover over the word Palette and the Component Palette will appear. ![]() Select Swing Components and then click on JLabel; next click on the grey area in the JFrame. A dialog box will appear prompting you for a name. Name your label lblURL. Now select the properties tab in the bottom window and change the >text property value to "URL". Go back to the palette and select a JTextField from the Swing Components, and again click on the JFrame, name the text field txtURL. You can reposistion and resize the field so that it is in line with the URL Label. Repeat this process to add a label for the Title - called lblTitle and a field for the title called txtTitle. Finally add a JButton from the Swing Components on the Palette called btnSave. Set the button text to "Save". You may also want to change the title of the frame from JFrame to something like "Add Bookmark". To do this click on the frame and then Change the title property in the bottom window. ![]() Notice that as we add components Java code has been added to the middle window. If we didn't have a visual editor we would have to type all this in. Now we have to get the form to do something useful. Currently it just displays labels and input boxes, clicking the button does nothing. To make the button do something we need to assign an action to it. The Swing framework uses a concept of "Listeners" to implement actions. If something is a listener it can listen for events, to make something into a listener we need to implement the ActionListener interface. Firstly we need to add some import statements import java.awt.event.ActionListener; import java.awt.event.ActionEvent; at the top of the java source and then change the class signature from public class BookmarkUI extends JFrame to public class BookmarkUI extends JFrame implements ActionListener At this point you should get an error in the code becase the ActionListener interface requires us to implement an actionPerformed method. (Look back at ObjectOrientation for information on interfaces). Add the following empty method to your class and the errors should go away.
public void actionPerformed(ActionEvent e) {
}
Now we are in a position to associate the button's action with the BookmarkUI? class which is also an ActionListener? and can therfore receive events. To do this find the getBtnSave method in the Java code and add
private JButton getBtnSave() {
if (btnSave == null) {
btnSave = new JButton();
btnSave.setBounds(new Rectangle(357, 72, 63, 21));
btnSave.setText("Save");
//listen to our own events
btnSave.addActionListener(this);
}
return btnSave;
}
What that does is associate "this" Object with any Actions that are raised by the button - in other words when the button is clicked the method We have produced quite a lot of code, so before we go any further, let's check that we are heading the right direction. Find the
public void actionPerformed(ActionEvent e) {
System.out.println("Action Performed");
}
Now, right click in the code window and choose Run As - Java Application. Your form should pop-up and if you press the Save button you should see the "Action Performed" text appear in the Eclipse Console window. If you are having problems the complete source code for this example is at the end of this page, it may help you solve any problems. So we now have a working action, but it doesn't yet add a bookmark. If you have got that working, it could be improved - how about an Exit button, and a message that says something like "bookmark sucessfully added", how about listing all the bookmarks in the file? Here is the full code from my version
package tutorial.swing;
import javax.swing.SwingUtilities;
import java.awt.BorderLayout;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Rectangle;
import javax.swing.JTextField;
import java.awt.Dimension;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import tutorial.files.Bookmarks;
public class BookmarkUI extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JPanel jContentPane = null;
private JLabel lblURL = null;
private JTextField txtURL = null;
private JLabel lblTitle = null;
private JTextField txtTitle = null;
private JButton btnSave = null;
/**
* This method initializes txtURL
*
* @return javax.swing.JTextField
*/
private JTextField getTxtURL() {
if (txtURL == null) {
txtURL = new JTextField();
txtURL.setBounds(new Rectangle(60, 14, 362, 20));
}
return txtURL;
}
/**
* This method initializes txtTitle
*
* @return javax.swing.JTextField
*/
private JTextField getTxtTitle() {
if (txtTitle == null) {
txtTitle = new JTextField();
txtTitle.setBounds(new Rectangle(62, 44, 361, 20));
}
return txtTitle;
}
/**
* This method initializes btnSave
*
* @return javax.swing.JButton
*/
private JButton getBtnSave() {
if (btnSave == null) {
btnSave = new JButton();
btnSave.setBounds(new Rectangle(357, 72, 63, 21));
btnSave.setText("Save");
//listen to our own events
btnSave.addActionListener(this);
}
return btnSave;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SwingUtilities.invokeLater(new Runnable() {
public void run() {
BookmarkUI thisClass = new BookmarkUI();
thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
thisClass.setVisible(true);
}
});
}
/**
* This is the default constructor
*/
public BookmarkUI() {
super();
initialize();
}
/**
* This method initializes this
*
* @return void
*/
private void initialize() {
this.setSize(457, 200);
this.setContentPane(getJContentPane());
this.setTitle("Add Bookmark");
}
/**
* This method initializes jContentPane
*
* @return javax.swing.JPanel
*/
private JPanel getJContentPane() {
if (jContentPane == null) {
lblTitle = new JLabel();
lblTitle.setBounds(new Rectangle(15, 45, 38, 16));
lblTitle.setText("Title");
lblURL = new JLabel();
lblURL.setBounds(new Rectangle(14, 15, 38, 16));
lblURL.setText("URL");
jContentPane = new JPanel();
jContentPane.setLayout(null);
jContentPane.add(lblURL, null);
jContentPane.add(getTxtURL(), null);
jContentPane.add(lblTitle, null);
jContentPane.add(getTxtTitle(), null);
jContentPane.add(getBtnSave(), null);
}
return jContentPane;
}
public void actionPerformed(ActionEvent e) {
Bookmarks bookmarks = new Bookmarks(null);
bookmarks.title = this.txtTitle.getText();
bookmarks.url = this.txtURL.getText();
bookmarks.addBookMark();
}
} // @jve:decl-index=0:visual-constraint="10,10"
This work is Copyright Chris Hunter 2007, you may use it for non-commercial purposes |