1 / 145

Lecture 9 Java GUI

Lecture 9 Java GUI. Cheng-Chia Chen. Contents. java GUI evolution Swing Components and Containing Hierarchy Layout Management Java Event Model and Event Handling javaBeans Reference: The Java Tutorial on the trail: Creating a GUI with JFC/Swing. Evolution of Java GUI.

signa
Download Presentation

Lecture 9 Java GUI

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Lecture 9 Java GUI Cheng-Chia Chen

  2. Contents • java GUI evolution • Swing Components and Containing Hierarchy • Layout Management • Java Event Model and Event Handling • javaBeans Reference: • The Java Tutorial on the trail: Creating a GUI with JFC/Swing

  3. Evolution of Java GUI • Java 1.0 AWT built in 30 days, and it shows • Java 1.1 AWT significantly improved, but GUI not finished yet • Java 2 Swing: very different, vastly improved • This lecture cover Swing only.

  4. Swing/JFC is very powerful • Start with the simple approach so you can create basic applications • Most of the time this will satisfy your needs • If you want to modify the standard elements, you can, but... • You’ll have to work harder and learn more • A number of big, thick books are available

  5. Swing/JFC • Very easy to add keyboard accelerators, tooltips, graphics • Pluggable look and feel • Provides ways to change just about everything, but you must work to understand how

  6. Borders Buttons Checkboxes ComboBoxes Image Icons Labels Layered Panes and Internal Frames (MDI) Lists and List Boxes Menus Popup Menus Radio Buttons Progress Bars Scrolling Support Scrollbars Splitter Control Tabbed Panes Swing Components and the containment hierarchy

  7. Swing features and Conecpts • Components and the containment hierarchy • Swing Components and the Containment Hierarchy • Layout Management • Event Handling • Painting • Threads and Swing • More Swing Features and Concepts • The Anatomy of a Swing-Based Program

  8. Swing Components and the Containment Hierarchy • An example: • Four components in this GUI: • a frame, or main window (JFrame) --- top-level container • a panel, sometimes called a pane (JPanel) --- intermediate container • a button (JButton) --- atomic components • a label (JLabel) --- atomic components

  9. the containment hierarchy for the gui:

  10. The code that adds the button and label to the panel, and the panel to the content pane: frame = new JFrame(...); button = new JButton(...); label = new JLabel(...); pane = new JPanel(); pane.add(button); pane.add(label); frame.getContentPane().add(pane, BorderLayout.CENTER);

  11. Classification of swing components • Top-Level Containers • The components at the top of any Swing containment hierarchy. • General-Purpose Containers • Intermediate containers that can be used under many different circumstances. • Special-Purpose Containers • Intermediate containers that play specific roles in the UI. • Basic Controls • Atomic components that exist primarily to get input from the user; • they generally also show simple state. • Uneditable Information Displays • Atomic components that exist solely to give the user information. • Editable Displays of Formatted Information • Atomic components that display highly formatted information that (if you choose) can be edited by the user.

  12. top-level containers Frame ( and JFrame) Applet (and JApplet) Dialog ( and JDialog)

  13. General-Purpose Containers Panel ( and JPanel) JScrollPane JToolBar JTabbedPane JSplitPane

  14. Special-Purpose Containers Root Pane JInternalFrames JLayeredPane

  15. Basic Controls JMenu JMenuItem JCheckBox JRadioButton JButton List ( and JList)

  16. Basic Controls JTextField Choice ( and JComboBox) JSlider

  17. Uneditable Information Displays JProgressBar Label ( and JLabel) JToolTip

  18. Editable Displays of Formatted Information JText JTable JTree FileDialog ( and JFileChooser) JColorChooser

  19. ImageObserver -parent Container Component -peer {abstract} {abstract} ComponentPeer TextComponent Color -layoutMgr Font LayoutManager TextArea TextField Button Canvas Checkbox Choice Label List Scrollbar Structure of the java.awt (AWT) package.

  20. Layout Management • the GUIs of five programs, each of which displays five buttons.

  21. Common layout tasks • Identical Buttons, almost identical codes. why do they look so different? • use different layout managers to control the size and position of the buttons. • the common layout tasks: • Setting the layout manager : • JPanel pane = new JPanel(); • pane.setLayout(new BorderLayout()); • Providing hints about a component : • privide size Hints : setMinimumSize(Dimension), setPreferredSize(..), setMaximumSize(..) • provide alignmentHints: setAllignmentX(float), setAlignmentY(float) • Putting space between components : • the layout manager : can specify hgap and vgap. • putting invisible component: • empty border : best for components that have no default border, eg: JPanel, Jlabel

  22. Event Handling • Every time the user types a character (KeyEvent) or pushes a mouse button( MouseEvent), an event occurs. • Any object can be notified of the event. • implement the appropriate interface and • be registered as an event listener on the appropriate event source. • Swing components can generate many kinds of events.

  23. Example GUI Events • Act that results in the event Listener type • User clicks a button, presses Return while typing in a ActionListener text field, or chooses a menu item • User closes a frame (main window) WindowListener • User presses a mouse button while the cursor is over a component MouseListener • User moves the mouse over a component MouseMotionListener • Component becomes visible ComponentListener • Component gets the keyboard focus FocusListener • Table or list selection changes ListSelectionListener

  24. system: Java Event Model • delegation ( or forwarding ) model l = new EventListener(…) l:EventListner b=new EventSource(…) b:EventSource addXXXListener(l) Event e1 occurs doXXXAction(e1) Event e2 occurs doXXXAction(e2) ….

  25. How to Implement an Event Handler • Implement and instantiate an event Listener : • public class MyClass implements XXXListener { …} • XXXListener l = (XXXListener) new MyClass(…); • Register the eventListener as an listener on event source: • aEventSource.addXXXListener( l ) ; • From now on, every time an event e occurs, the event source object will call the appropriate doXXXAction(e) from l. • Threads and Event Handling : • Event-handling code executes in a single thread, the event-dispatching thread. • => Event handlers should execute very quickly, Otherwise, the program's perceived performance will be poor. If needing lengthy operation, starting up another thread

  26. How Painting Works 1. background 2. custom painting 3. border 4. children

  27. More Swing Features and Concepts • Features that JComponent provides • the ability to have borders, • tool tips, and • a configurable look and feel. • Icons • Many Swing components -- notably buttons and labels -- can display images. You specify these images as Icon objects. • Actions • provide support for sharing data and state between two or more components that can generate action events. • Pluggable Look & Feel support • A single program can have any one of several looks and feels. • can let the user determine the look and feel, or • can specify the look and feel programatically. • Support for assistive technologies • Separate data and state models

  28. Using Swing Components • The JComponent Class • Using Top-Level Containers • Using Intermediate Swing Containers • Using Atomic Components

  29. The JComponent Class • JComponent  Container  Component • Tool tips: • setToolTipText(String) • Borders • The setBorder method allows you to specify the border that a component displays around its edges. • Keyboard-generated actions • Using the registerKeyboardAction method, you can enable the user to use the keyboard, instead of the mouse, to operate the GUI. • Application-wide pluggable look and feel • UIManager.setLookAndFeel(…) • Properties • can associate one or more properties (name/object pairs) with any JComponent. • putClientProperty(…), getClientProperty(…)

  30. Support for layout • get/set minimum/preferred/maximum Size(..). • get/set alignmentX/Y(…) • Support for accessibility • Double buffering • Methods to increase efficiency • getX(), getY(), getWidth(), getHeight(),…

  31. The JComponent API • Customizing Component Appearance : • get/set for properties: border, forground, background, font, opaque • eg: setBorder(Border) / Border getBorder(), … • Setting Component State • void setToolTipText(String) • void setEnabled(boolean b) , boolean isEnabled() • void setLocale(Locale l) , Locale getLocale() • void setCursor(Cursor), Cursor getCursor() // mouse curser Icon • void setVisible(boolean) , boolean isVisible() • Handling Events : • add/remove (component, mouse, mouseMotion, key, container, focus) Listenser • get/set nextFocusComponent property • requestFocus(), hasFocus() • boolean contains(int x, int y), contains(Point) • Component getComponentAt(int, int)

  32. Painting Components • void repaint() , repaint(int, int, int, int), repaint(Rectangle) • void revalidate() : ReLay out the component and its affected containers. • void paintComponent(Graphics) • Dealing with the Containment Hierarchy • Component add(Component[,int index | Object constraint]) • void remove(int) , void remove(Component comp) , void removeAll() • JRootPane getRootPane() • Container getParent() • int getComponentCount() • Component getComponent(int) • Component[] getComponents()

  33. Laying Out Components • get/set LayoutManager property: layout • get/set Dimension properties: minimumSize, preferredSize, • maximumSize • get/set float property: allignmentX, allignmentY • Getting Size and Position Information • int getWidth(), getHeight(), getX(), getY() • Dimension getSize(), Dimension getSize(Dimension) • Rectangle getBounds() , Rectangle getBounds(Rectangle) • Point getLocation() , getLocation(Point), getLocationOnScreen(); • Insets getInsets() • Specifying Absolute Size and Position • setLocation(int,int) setLocation(Point), setSize(int,int), setSize(Dimension), setBounds(int x,y,w,h), setBounds(Rectangle)

  34. Using Top-Level Containers • three generally useful top-level container classes: • JFrame, JDialog, and JApplet. • Each has a content pane that contains the visible components in the GUI. • Can optionally add a menu bar to a top-level container. • positioned within the top-level container, but outside the content pane.

  35. Adding Components to the Content Pane : • frame.getContentPane().add(yellowLabel, BorderLayout.CENTER); • Adding a Menu Bar : • frame.setJMenuBar(cyanMenuBar); • The Root Pane :

  36. How to Make Frames (Main Windows) • code creates and • sets up the frame

  37. the code public static void main(String s[]) { JFrame frame = new JFrame("FrameDemo"); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) {System.exit(0);} }); //...create a blank label, set its preferred size... frame.getContentPane().add(emptyLabel, BorderLayout.CENTER); frame.pack(); frame.setVisible(true); }

  38. JFrame APIs • Constructors: JFrame(), JFrame(String) • void setDefaultCloseOperation(int), int getDefaultCloseOperation() • Possible choices: DO_NOTHING_ON_CLOSE, HIDE_ON_CLOSE (the default) , DISPOSE_ON_CLOSE • void setContentPane(Container) , Container getContentPane() • void setJMenuBar(JMenuBar) , JMenuBar getJMenuBar() • …

  39. Using Intermediate Swing Containers • Panel • The most flexible, frequently used intermediate container. • Scroll Pane • Provides scroll bars around a large or growable component. • Split Pane • Displays two components in a fixed amount of space, letting the user adjust the amount of space devoted to each component. • Tabbed Pane • Contains multiple components but shows only one at a time. The user can easily switch between components. • Tool Bar • Holds a group of components (usually buttons) in a row or column, optionally allowing the user to drag the tool bar into different locations.

  40. special intermediate containers • Internal Frame • Looks like a frame and has much the same API, but must appear within another window. • Layered Pane • Provides a third dimension, depth, for positioning components. You specify the position and size of each component. One type of layered pane, a desktop pane, is designed primarily to contain and manage internal frames. • Root Pane : • Provides behind-the-scenes support to top-level containers.

  41. How to Use Panels

  42. Setting the Layout Manager : • JPanel aPanel = new JPanel(); • aPanel.setLayout(new BorderLayout()); • Adding Components • aFlowPanel.add(aComponent); • aFlowPanel.add(anotherComponent); • aBorderPanel.add(aComponent, BorderLayout.CENTER); • aBorderPanel.add(anotherComponent, BorderLayout.SOUTH);

  43. The JPanel API • Constructors: JPanel() , JPanel(LayoutManager) • void add(Component [, Object ] [, int ]), • void add(String, Component) • int getComponentCount() • Component getComponent(int) • Component[] getComponents() • Component getComponentAt( [int, int | Point] ) • void remove(Component), void remove(int) , void removeAll() • void setLayout(LayoutManager), LayoutManager getLayout()

  44. How to Use Scroll Panes textArea = new JTextArea(5, 30); JScrollPane scrollPane = new JScrollPane(textArea); ... contentPane.setPreferredSize(new Dimension(400, 100)); ... contentPane.add(scrollPane, BorderLayout.CENTER);

  45. How to use Split Pane

  46. the code //Create a split pane with the two scroll panes in it. splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, listScrollPane, pictureScrollPane); splitPane.setOneTouchExpandable(true); splitPane.setDividerLocation(150); //Provide minimum sizes for the two components in the split pane Dimension minimumSize = new Dimension(100, 50); listScrollPane.setMinimumSize(minimumSize); pictureScrollPane.setMinimumSize(minimumSize);

  47. How to Use Tool Bars

  48. public ToolBarDemo() { ... JToolBar toolBar = new JToolBar(); addButtons(toolBar); ... JPanel contentPane = new JPanel(); contentPane.setLayout(new BorderLayout()); ... contentPane.add(toolBar, BorderLayout.NORTH); contentPane.add(scrollPane, BorderLayout.CENTER); ... }

  49. protected void addButtons(JToolBar toolBar) { JButton button = null; //first button button = new JButton(new ImageIcon("images/left.gif")); ... toolBar.add(button); //second button button = new JButton(new ImageIcon("images/middle.gif")); ... toolBar.add(button); //third button button = new JButton(new ImageIcon("images/right.gif")); ... toolBar.add(button); } • Other methods: • isFloatable(), setFloatable(boolean) • addSeparator()

  50. Using Atomic Components • The following atomic components exist primarily to get input from the user: • Button, Check Box, Radio Button • Provides easy-to-use, easy-to-customize button implementations. • Combo Box • Provides both uneditable and editable combo boxes -- buttons that bring up menus of choices. • List • Displays a group of items that the user can choose. • Menu • Includes menu bar, menu, and menu item implementations, including specialized menu items such as check box menu items. • Slider • Lets the user choose one of a continuous range of values. • Text Field • Lets the user enter a single line of text data.

More Related