Posts tagged ‘Java Interface’
Beginners Java Tutorial – Building a User Interface
We also have some excellent Beginners Programming Java tutorials that use high quality narrated videos and practical working files to teach the fundamentals of programming in Java Beginners Java Tutorial Videos
Beginners Java Tutorial – Building User Interfaces
The Java language features a range of resources for building user interfaces. In this tutorial, we will use Swing and AWT to build a simple Graphical User Interface. The Swing libraries provide the graphical elements and AWT allows you to respond to user interaction.
Open your chosen IDE and create a new project. Create a Main Class (with your main method in it, but leave it empty for now) and a second Class, called MyGUI. In this Class, enter the following (don’t be alarmed if some of the syntax is unfamiliar, explanation follows):
/** * MyGUI User Interface Class */ //imports for graphics and user interaction import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * MyGUI class represents a graphical user interface * @author Your Name */ public class MyGUI extends JFrame implements ActionListener { /** * Constructor function creates and displays * the basic elements in the GUI */ public MyGUI() { //constructor code ... } /** * actionPerformed will determine how the program * responds to user interaction */ public void actionPerformed(ActionEvent e) { //event code ... } }
Let’s look at the individual code elements:
- The import statements allow us to use the Swing and AWT libraries for building our interface
- In the line:
- ‘extends JFrame’ relies on the notion of Inheritance, but don’t worry if you haven’t come across it before, at this stage you can simply treat the line as a formula that you use for any user interface Class.
The Class inherits from the Class JFrame, meaning JFrame is its superclass. - ‘implements ActionListener’ has to do with Java Interface declarations – again, if this is unfamiliar to you don’t worry, just use this code whenever you need to respond to user interaction.
The Class implements the ActionListener interface, meaning that it must provide the methods outlined in that Interface declaration.
- ‘extends JFrame’ relies on the notion of Inheritance, but don’t worry if you haven’t come across it before, at this stage you can simply treat the line as a formula that you use for any user interface Class.
public class MyGUI extends JFrame implements ActionListener
Now we will add some ‘widgets’ to our GUI, to do this we need to create an instance variable for each, and constructor code to display them.
The first thing to do within the constructor is specify the window properties, such as size, location etc. Then, we need to create Panels to hold our widgets. The default layout for a JFrame GUI is called ‘Border Layout’; this means that items can bee added in positions North, South, East, West and Center. However, you can change the layout, as we will in one section below, in this case to Grid Layout, in which you can have a specified number of rows and columns. When you do this, items are given consecutive positions left to right/ top to bottom as you add them to the GUI (first being leftmost/topmost). The widgets themselves need to be instantiated within the constructor also, as you can see below. Our GUI will have a button, a checkbox and two radio buttons – enter the code:
/** * MyGUI User Interface Class */ //imports for graphics and user interaction import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * MyGUI class represents a graphical user interface * @author Your Name */ public class MyGUI extends JFrame implements ActionListener { //instance variables - elements in the GUI private JButton myButton; private JRadioButton firstRadio, secondRadio; private JCheckBox myCheck; /** * Constructor function creates and displays * the basic elements in the GUI */ public MyGUI() { //set the window properties setTitle("My GUI"); setSize(200, 200); setLocation(100, 100); //create Panels JPanel northPanel = new JPanel(); JPanel centerPanel = new JPanel(); JPanel southPanel = new JPanel(); add(northPanel, "North"); add(centerPanel, "Center"); add(southPanel, "South"); //create widgets myButton = new JButton("a button"); firstRadio = new JRadioButton("pick me"); secondRadio = new JRadioButton("or me"); myCheck = new JCheckBox("check me"); //add widgets to the GUI - button northPanel.add(myButton); //create grid layout for centre (radio buttons) GridLayout myGrid = new GridLayout(1, 2);//1 row, 2 cols centerPanel.setLayout(myGrid); centerPanel.add(firstRadio); centerPanel.add(secondRadio); //create button group - only one may be selected ButtonGroup myGroup = new ButtonGroup(); myGroup.add(firstRadio); myGroup.add(secondRadio); //add checkbox southPanel.add(myCheck); //make the GUI visible setVisible(true); } /** * actionPerformed will determine how the program * responds to user interaction */ public void actionPerformed(ActionEvent e) { //event code ... } }
Try not to be intimidated by the amount of code, creating user interfaces can be long-winded but really is simple to program. Now, return to your main method and enter the following:
//create an instance of the MyGUI class MyGUI myGui = new MyGUI();
Run your program, it should look something like this:
You’ll notice that although you can interact with the buttons etc, nothing actually happens when you do so – let’s add code to detect this interaction. At the end of your MyGUI constructor code (before setVisible) add the following:
//listen for user interaction myButton.addActionListener(this); firstRadio.addActionListener(this); secondRadio.addActionListener(this); myCheck.addActionListener(this);
Now, whenever someone interacts with your buttons, the actionPerformed method will be called, passing information about the ‘event’ in the ActionEvent parameter. In the actionPerformed method, we therefore need to decide how to respond:
/** * actionPerformed will determine how the program * responds to user interaction */ public void actionPerformed(ActionEvent e) { //which component had an event? if(e.getSource()==myButton) { //the button System.out.println("Someone pressed the button!"); } else if(e.getSource()==firstRadio) { //first radio button System.out.println("first"); } else if(e.getSource()==secondRadio) { //second radio System.out.println("second"); } else { //must be checkbox boolean selected = myCheck.isSelected(); System.out.println((selected ? "checked" : "unchecked")); } }
Run the program and see what happens when you interact with the buttons now, you should see results printed to the output console.
You never call the actionPerformed method explicitly in your own code, it is called automatically when events are detected on any component you have added and ActionListener to. Obviously your real applications will have more sophisticated ways of responding to events, but this overview should indicate the basic pattern that you can adopt to create user interfaces in Java. The Swing library contains numerous resources you can experiment with such as TextAreas/Fields, ComboBoxes and more.