
Graphical User Interfaces
Containers and Components
• Frame - OS-managed container used to
display GUI-based java apps
• Panel - Container used to organized other
GUI components (buttons, labels, etc)
• Label - Component used to display text
//Similar to Authority.java from Lewis/Loftus
import java.awt.*;
import javax.swing.*;
public class GUI {
public static void main(String[] args) {
JFrame frame = new JFrame("First GUI"); //takes title for window
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel( );
panel.setBackground(Color.red);
panel.setPreferredSize(new Dimension(250, 75));
JLabel label = new JLabel("My first GUI");
panel.add(label); //add label to panel
frame.getContentPane().add(panel); //add panel to content pane of frame
frame.pack(); //size to the preferred size
frame.setVisible(true); //make v isible
}
}
Exercises
1. Experiment with class GUI
1. Change t he color of the panel
2. Change t he size of the panel
3. See what happens if you do not “ pack”
4. See wha t happens if you do not make visible
5. Add a se cond label of a different color
More Components
• Buttons - Component that can be “pushed”
– must invoke addActionListener in order to
enable the program to respond to a button
push
– program waits for an event and the p erforms
the appropriate action
public class GUIWButton {
public GUIWButton() {
JFrame frame = new JFrame("First GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setBackground(Color.red);
panel.setPreferredSize(new Dimension(250, 75));
JLabel label = new JLabel("Count is 0");
JButton button = new JButton("Push Me!");
button.addActionListener(new ButtonListener(label));
panel.add(label);
panel.add(button);
frame.getContentPane().add(panel);
frame.pack(); //size to the preferred size
frame.setVisible(true);
}