- Introduction to Interface Builder
- Java Code Example
- Objective-C Code Example
- Conclusion
Java Code Example
To emphasize the differences between building a GUI in JFC/Swing and Interface Builder, I will walk through a simple code example for both. In this example, I will produce an application with a single window, a single button, and a single label. When the button is pressed, the label will change its text to the infamous "Hello World".
package com.zarrastudios.example; import javax.swing.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.*; public class HelloFrame extends JFrame { private JButton btnAction; private JLabel lblDisplay; public HelloFrame() { super("Hello Frame"); initComponents(); initLayout(); initListeners(); pack(); } private void initComponents() { btnAction = new JButton("Action!"); lblDisplay = new JLabel("---------"); } private void initLayout() { JPanel p = new JPanel(new BorderLayout()); p.add(btnAction, BorderLayout.SOUTH); p.add(lblDisplay, BorderLayout.NORTH); setContentPane(p); } private void initListeners() { btnAction.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { lblDisplay.setText("Hello World!"); } }); } public static void main(String args[]) { HelloFrame hf = new HelloFrame(); hf.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent evt) { System.exit(0); } }); hf.setVisible(true); } }
This is a fairly simple GUI. I have broken the initialization of the GUI components away from the layout code and the listener code. Although not strictly needed in this example, it helps for future maintainability.