Graphical User Interfaces
Total Page:16
File Type:pdf, Size:1020Kb
Interactive Programs input Introduction to ! “Classic” view of Graphical User computer programs: Interfaces (GUIs) transform inputs to outputs, stop output ! Event-driven programs: interactive, long-running user user " Servers interact with clients input output events Lecture 15 " Applications interact with user events CS2112 – Spring 2012 (s) " OS responds to kernel calls program 2 GUI Motivation Java Support for Building GUIs !Interacting with a program !Design...Which to pick? !Java Foundation Classes ! Our main focus: Swing " Program-Driven = Proactive " Program called by another program? " Classes for building GUIs " Building blocks of GUIs # Statements execute in sequential, " Program used at command line? predetermined order " Major components # Windows & components " Program interacts often with user? # # Typically use keyboard or file I/O, # java.awt and javax.swing User interactions " Program used in window environment? but program determines when # Pluggable look-and-feel support " Built upon the AWT (Abstract that happens # Accessibility API Window Toolkit) # Usually single-threaded !How does Java do GUIs? # Java 2D API # Java event model " Event-Driven = Reactive # Drag-and-drop support # Program waits for user input to # Internationalization activate certain statements # Typically uses a GUI (Graphical User Interface) # Often multi-threaded 3 4 Java Foundation Classes GUI Statics and GUI Dynamics !Pluggable Look-and-Feel Support " Controls look-and-feel for particular windowing environment !Statics: what’s drawn on !Dynamics: user interactions " E.g., Java, Windows, Mac the screen " Events !Accessibility API " Components # button-press, mouse-click, key-press, ... # buttons, labels, lists, sliders, " Listeners: an object that responds to an " Supports assistive technologies such as screen readers and Braille menus, ... event !Java 2D " Containers: components that " Helper classes " Drawing contain other components # Graphics, Color, Font, FontMetrics, Dimension, ... " Includes rectangles, lines, circles, images, ... # frames, panels, dialog boxes, ... " Layout managers: control !Drag-and-drop placement and sizing of " Support for drag and drop between Java application and a native components application !Internationalization " Support for other languages 5 6 Creating a Window Creating a Window Using a Constructor import javax.swing.*; import javax.swing.*; public class Basic1 { public class Basic2 extends JFrame { public static void main(String[] args) { //create the window public static void main(String[] args) { JFrame f = new JFrame("Basic Test!"); new Basic2(); //quit Java after closing the window } f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setSize(200, 200); //set size in pixels public Basic2() { f.setVisible(true); //show the window setTitle("Basic Test2!"); //set the title } //quit Java after closing the window } setDefaultCloseOperation(EXIT_ON_CLOSE); setSize(200, 200); //set size in pixels setVisible(true); //show the window } } 7 8 A More Extensive Example import javax.swing.*; import java.awt.*; GUI Statics import java.awt.event.*; public class Intro extends JFrame { private int count = 0; private JButton myButton = new JButton("Push Me!"); private JLabel label = new JLabel("Count: " + count); ! Determine which components you want public Intro() { setDefaultCloseOperation(EXIT_ON_CLOSE); ! Choose a top-level container in which to put the setLayout(new FlowLayout(FlowLayout.LEFT)); //set layout manager add(myButton); //add components components (JFrame is often a good choice) add(label); myButton.addActionListener(new ActionListener() { ! Choose a layout manager to determine how public void actionPerformed(ActionEvent e) { count++; components are arranged label.setText("Count: " + count); } }); ! Place the components pack(); setVisible(true); } public static void main(String[] args) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception exc) {} new Intro(); } } 9 10 Component Examples Components = What You See import javax.swing.*; import java.awt.*; public class ComponentExamples extends JFrame { public ComponentExamples() { ! Visual part of an interface setLayout(new FlowLayout(FlowLayout.LEFT)); add(new JButton("Button")); ! Represents something with position and size add(new JLabel("Label")); add(new JComboBox(new String[] { "A", "B", "C" })); add(new JCheckBox("JCheckBox")); ! Can be painted on screen and can receive events add(new JSlider(0, 100)); add(new JColorChooser()); ! Buttons, labels, lists, sliders, menus, ... setDefaultCloseOperation(EXIT_ON_CLOSE); pack(); setVisible(true); } public static void main(String[] args) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception exc) {} new ComponentExamples(); } } 11 12 Containers More Components ! A container is a component that ! There are three basic top-level containers ! JFileChooser: allows choosing a file " Can hold other components " Has a layout manager " JWindow: top-level window with no ! JLabel: a simple text label border " JFrame: top-level window with border ! JTextArea: editable text and (optional) menu bar : used for dialog windows : editable text (one line) ! Heavyweight vs. lightweight " JDialog ! JTextField " A heavyweight component interacts ! JScrollBar: a scrollbar directly with the host system ! Another important container " JWindow, JFrame, and JDialog " JPanel: used mostly to organize are heavyweight ! JPopupMenu: a pop-up menu objects within other containers " Except for these top-level ! JProgressBar: a progress bar containers, Swing components are almost all lightweight ! Lots more! # JPanel is lightweight 13 14 A Component Tree Layout Managers JFrame ! A layout manager controls ! General syntax placement and sizing of container.setLayout(new LayoutMan()); JPanel components in a container " If you do not specify a layout ! Examples: manager, the container will use a JPanel JPanel default: # JPanel default = FlowLayout JPanel p1 = new JPanel(new BorderLayout()); JPanel JPanel # JFrame default = BorderLayout JPanel p2 = new JPanel(); ! Five common layout managers: p2.setLayout(new BorderLayout()); JPanel JPanel JPanel JPanel BorderLayout, BoxLayout, FlowLayout, GridBagLayout, JComboBox (mi) JComboBox (km) GridLayout JTextField (3226) JTextField (2000) JSlider JSlider 15 16 Some Example Layout Managers FlowLayout Example import javax.swing.*; ! FlowLayout ! BorderLayout import java.awt.*; " Components placed from left to " Divides window into five areas: North, right in order added South, East, West, Center public class Statics1 { " When a row is filled, a new row is public static void main(String[] args) { started new S1GUI(); ! Adding components } " Lines can be centered, left-justified " FlowLayout and GridLayout use } or right-justified (see FlowLayout container.add(component) constructor) class S1GUI { " BorderLayout uses container.add " See also BoxLayout private JFrame f; (component, index) where index is one of public S1GUI() { ! GridLayout # BorderLayout.NORTH f = new JFrame("Statics1"); # BorderLayout.SOUTH f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); " Components are placed in grid f.setSize(500, 200); pattern # BorderLayout.EAST # BorderLayout.WEST f.setLayout(new FlowLayout(FlowLayout.LEFT)); " number of rows & columns for (int b = 1; b < 9; b++) # BorderLayout.CENTER specified in constructor f.add(new JButton("Button " + b)); " Grid is filled left-to-right, then top-to- f.setVisible(true); bottom } } 17 18 BorderLayout Example GridLayout Example import javax.swing.*; import javax.swing.*; import java.awt.*; import java.awt.*; public class Statics2 { public class Statics3 { public static void main(String[] args) { new S2GUI(); } public static void main(String[] args) { new S3GUI(); } } } class ColoredJPanel extends JPanel { class S3GUI extends JFrame { Color color; static final int DIM = 25; ColoredJPanel(Color color) { static final int SIZE = 12; this.color = color; static final int GAP = 1; } public void paintComponent(Graphics g) { public S3GUI() { g.setColor(color); setTitle("Statics3"); g.fillRect(0, 0, 400, 400); setDefaultCloseOperation(EXIT_ON_CLOSE); } setLayout(new GridLayout(DIM, DIM, GAP, GAP)); } for (int i = 0; i < DIM * DIM; i++) add(new MyPanel()); pack(); class S2GUI extends JFrame { setVisible(true); public S2GUI() { } setTitle("Statics2"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); class MyPanel extends JPanel { setSize(400, 400); MyPanel() { setPreferredSize(new Dimension(SIZE, SIZE)); } add(new ColoredJPanel(Color.RED), BorderLayout.NORTH); public void paintComponent(Graphics g) { add(new ColoredJPanel(Color.GREEN), BorderLayout.SOUTH); float gradient = add(new ColoredJPanel(Color.BLUE), BorderLayout.WEST); 1f - ((float)Math.abs(getX() - getY()))/(float)((SIZE + GAP) * DIM); add(new ColoredJPanel(Color.YELLOW), BorderLayout.EAST); g.setColor(new Color(0f, 0f, gradient)); add(new ColoredJPanel(Color.BLACK), BorderLayout.CENTER); g.fillRect(0, 0, getWidth(), getHeight()); setVisible(true); } } } } } 19 20 More Layout Managers AWT and Swing ! CardLayout ! Custom !AWT ! Swing " Can define your own layout " More recent (since Java 1.2) GUI " Tabbed index card look from " Initial GUI toolkit for Java manager toolkit Windows " Provided a “Java” look and feel " But best to try Java's layout " Added functionality (new managers first... " Basic API: java.awt.* components) ! GridBagLayout " Supports look and feel for various " Most versatile, but complicated ! Null platforms (Windows, Mac) Basic API: " No layout manager " javax.swing.* " Programmer must specify absolute locations ! Did Swing replaced AWT? " Provides great control, but can be " Not quite: both use the AWT event dangerous because of platform model dependency 21 22 Code Examples !Intro.java ! ComponentExamples.java " Button & counter " Sample components !Basic1.java ! Statics1.java " FlowLayout example " Create a window ! Statics2.java !Basic2.java " BorderLayout example " Create a window using a ! Statics3.java constructor " GridLayout example !Calculator.java ! LayoutDemo.java " Shows use of JOptionPane to " Multiple layouts produce standard dialogs 23.