Java – gui graphical User Interface ine2720 Web Application Software Development



Yüklə 475 b.
tarix21.03.2017
ölçüsü475 b.
#12149


Java – GUI Graphical User Interface

  • INE2720

  • Web Application Software Development

  • Essential Materials


Outline

  • Basic AWT windows

    • Canvas, Panel, Frame, Dialog
  • Basic AWT user interface controls

    • Button, checkbox, radio button, list box
  • Processing events in GUI controls

  • Swing - New features

  • Summary of Swing components

    • Swing equivalent of AWT components
      • JApplet, JLabel, JButton, JPanel, JSlider
    • New Swing components
      • JColorChooser, JInternalFrame, JOptionPane, JToolBar, JEditorPane
    • Other simple components
      • JCheckBox, JRadioButton, JTextField, JTextArea, JFileChooser


Windows and Layout Management

  • Containers

    • Most windows are a Container that can hold other windows or GUI components. Canvas is the major exception.
  • Layout Managers

    • Containers have a LayoutManager that automatically sizes and positions components that are in the window. You can change the behavior of the layout manager or disable it completely.
  • Events

    • Windows and components can receive events.
  • Popup Windows

    • Some windows (Frame and Dialog) have their own title bar and border and can be placed at arbitrary locations on the screen
    • Other windows (Canvas an Panel) are embedded into existing windows only


Canvas Class

  • Major Purposes

    • A drawing area
    • A custom Component that does not need to contain any other Component (e.g. an image button)
  • Default Layout Manager - None

    • Canvas cannot contain any other Components
  • Creating and Using

    • Create the Canvas Canvas canvas = new Canvas();
    • Or, since you typically create a subclass of Canvas that has customized drawing via its paint method:
    • SpecializedCanvas canvas = new SpecializedCanvas();


Canvas (Continued)

  • Creating and Using, cont.

    • Size the Canvas
      • canvas.setSize(width, height);
    • Add the Canvas to the current Window
      • add(canvas);
    • or depending on the layout manager you can position the Canvas
    • add(canvas, BorderLayout.Region_Name);
    • If you first create a separate window (e.g. a Panel), then put the Canvas in the window using something like
    • someWindow.add(canvas);


Canvas Example

  • import java.awt.*;

  • /** A Circle component built using a Canvas. */

  • public class Circle extends Canvas {

  • private int width, height;

  • public Circle(Color foreground, int radius) {

  • setForeground(foreground);

  • width = 2*radius;

  • height = 2*radius;

  • setSize(width, height);

  • }

  • public void paint(Graphics g) {

  • g.fillOval(0, 0, width, height);

  • }

  • public void setCenter(int x, int y) {

  • setLocation(x - width/2, y - height/2);

  • }

  • }



Component Class

  • Direct Parent Class of Canvas

  • Ancestor of all Window Types

  • Useful Methods

    • getBackground/setBackground
    • getForeground/setForeground
      • Change/lookup the default foreground color
      • Color is inherited by the Graphics object of the component
    • getFont/setFont
      • Returns/sets the current font
      • Inherited by the Graphics object of the component
    • paint
      • Called whenever the user call repaint or when the component is obscured and reexposed


Component Class (Continued)

  • Useful Methods

    • setVisible
      • Exposes (true) or hides (false) the component
      • Especially useful for frames and dialogs
    • setSize/setBounds/setLocation
    • getSize/getBounds/getLocation
      • Physical aspects (size and position) of the component
    • list
      • Prints out info on this component and any components it contains; useful for debugging
    • invalidate/validate
      • Tell layout manager to redo the layout
    • getParent
      • Returns enclosing window (or null if there is none)


Panel Class

  • Major Purposes

    • To group/organize components
    • A custom component that requires embedded components
  • Default Layout Manager - FlowLayout

    • Shrinks components to their preferred size
    • Places them left to right in centered rows
  • Creating and Using

    • Create the Panel
          • Panel panel = new Panel();
    • Add Components to Panel
          • panel.add(someComponent);
          • panel.add(someOtherComponent); ...


Panel (Continued)

  • Creating and Using, continued

    • Add Panel to Container
      • To an external container
          • container.add(panel);
      • From within a container
          • add(panel);
  • Note the lack of an explicit setSize

    • The components inside determine the size of a panel; the panel is no larger then necessary to hold the components
    • A panel holding no components has a size of zero
  • Note: Applet is a subclass of Panel



Without / With Panels

  • import java.applet.Applet;

  • import java.awt.*;

  • public class ButtonTest1 extends Applet {

  • public void init() {

  • String[] labelPrefixes = { "Start", "Stop", "Pause", "Resume" };

  • for (int i=0; i<4; i++) {

  • add(new Button(labelPrefixes[i] + " Thread1"));

  • }

  • for (int i=0; i<4; i++) {

  • add(new Button(labelPrefixes[i] + " Thread2"));

  • }

  • }

  • }





Frame and Dialog Class

  • Frame

    • A stand-alone window with its own title and menu bar, border, cursor and icon image
    • Can contain other GUI components
  • Dialog

    • A simplified Frame (no cursor, menu, icon image).
    • A modal Dialog that freezes interaction with other AWT components until it is closed.


AWT GUI Controls

  • Automatically drawn

  • Positioned by layout manager

  • Controls adopt look and feel of underlying window system

  • GUI Controls

    • Button, checkbox,
    • radio button, list box, scrollbars


Buttons

  • Constructors

    • Button(), Button(String buttonLabel)
      • The button size (preferred size) is based on the height and width of the label in the current font, plus some extra space determined by the OS
  • Useful Methods

    • getLabel/setLabel
      • Retrieves or sets the current label
      • If the button is already displayed, setting the label does not automatically reorganize its Container
        • The containing window should be invalidated and validated to force a fresh layout
  • someButton.setLabel("A New Label");

  • someButton.getParent().invalidate();

  • someButton.getParent().validate();



Buttons (Continued)

  • Event Processing Methods

    • addActionListener/removeActionListener
      • Add/remove an ActionListener that processes ActionEvents in actionPerformed
    • processActionEvent
      • Low-level event handling
  • General Methods Inherited from Component

    • getForeground/setForeground
    • getBackground/setBackground
    • getFont/setFont


Button: Example

  • public class Buttons extends Applet {

  • private Button button1, button2, button3;

  • public void init() {

  • button1 = new Button("Button One");

  • button2 = new Button("Button Two");

  • button3 = new Button("Button Three");

  • add(button1);

  • add(button2);

  • add(button3);

  • }

  • }



Handling Button Events

  • Attach an ActionListener to the Button and handle the event in actionPerformed

  • public class MyActionListener

  • implements ActionListener {

  • public void actionPerformed(ActionEvent event) {

  • ...

  • }

  • }

  • public class SomeClassThatUsesButtons {

  • ...

  • MyActionListener listener = new MyActionListener();

  • Button b1 = new Button("...");

  • b1.addActionListener(listener);

  • ...

  • }



Centralized Event Processing

  • import java.awt.*;

  • import java.awt.event.*;

  • public class ActionExample2 extends CloseableFrame implements ActionListener {

  • public static void main(String[] args) {

  • new ActionExample2();

  • }

  • private Button button1, button2, button3;

  • public ActionExample2() {

  • super("Handling Events in Other Object");

  • setLayout(new FlowLayout());

  • setFont(new Font("Serif", Font.BOLD, 18));

  • button1 = new Button("Resize to 300x200");

  • button1.addActionListener(this);

  • add(button1);

  • ….



Checkboxes

  • Constructors

    • These three constructors apply to checkboxes that operate independently of each other (i.e., not radio buttons)
    • Checkbox()
      • Creates an initially unchecked checkbox with no label
    • Checkbox(String checkboxLabel)
      • Creates a checkbox (initially unchecked) with the specified label; see setState for changing it
    • Checkbox(String checkboxLabel, boolean state)
      • Creates a checkbox with the specified label
        • The initial state is determined by the boolean value provided
        • A value of true means it is checked


Checkbox, Example

  • public class Checkboxes extends CloseableFrame {

  • public Checkboxes() {

  • super("Checkboxes");

  • setFont(new Font("SansSerif", Font.BOLD, 18));

  • setLayout(new GridLayout(0, 2));

  • Checkbox box;

  • for(int i=0; i<12; i++) {

  • box = new Checkbox("Checkbox " + i);

  • if (i%2 == 0) {

  • box.setState(true);

  • }

  • add(box);

  • }

  • pack();

  • setVisible(true);

  • }

  • }



Other Checkbox Methods

  • getState/setState

    • Retrieves or sets the state of the checkbox: checked (true) or unchecked (false)
  • getLabel/setLabel

    • Retrieves or sets the label of the checkbox
    • After changing the label invalidate and validate the window to force a new layout (same as button).
  • addItemListener/removeItemListener

    • Add or remove an ItemListener to process ItemEvents in itemStateChanged


Checkbox Groups (Radio Buttons)

  • CheckboxGroup Constructors

    • CheckboxGroup()
      • Creates a non-graphical object used as a “tag” to group checkboxes logically together
      • Only one checkbox associated with a particular tag can be selected at any given time
  • Checkbox Constructors

    • Checkbox(String label, CheckboxGroup group, boolean state)
      • Creates a radio button associated with the specified group, with the given label and initial state


CheckboxGroup: Example

  • import java.applet.Applet;

  • import java.awt.*;

  • public class CheckboxGroups extends Applet {

  • public void init() {

  • setLayout(new GridLayout(4, 2));

  • setBackground(Color.lightGray);

  • setFont(new Font("Serif", Font.BOLD, 16));

  • add(new Label("Flavor", Label.CENTER));

  • add(new Label("Toppings", Label.CENTER));

  • CheckboxGroup flavorGroup = new CheckboxGroup();

  • add(new Checkbox("Vanilla", flavorGroup, true));

  • add(new Checkbox("Colored Sprinkles"));

  • add(new Checkbox("Chocolate", flavorGroup, false));

  • add(new Checkbox("Cashews"));

  • add(new Checkbox("Strawberry", flavorGroup, false));

  • add(new Checkbox("Kiwi"));

  • }

  • }



List Boxes

  • Constructors

    • List(int rows, boolean multiSelectable)
      • Creates a listbox with the specified number of visible rows
      • Depending on the number of item in the list (addItem or add), a scrollbar is automatically created
      • The second argument determines if the List is multiselectable
    • List()
      • Creates a single-selectable list box with a platform-dependent number of rows and a platform-dependent width
    • List(int rows)
      • Creates a single-selectable list box with the specified number of rows and a platform-dependent width


List Boxes: Example

  • import java.awt.*;

  • public class Lists extends CloseableFrame {

  • public Lists() {

  • super("Lists");

  • setLayout(new FlowLayout());

  • setBackground(Color.lightGray);

  • setFont(new Font("SansSerif", Font.BOLD, 18));

  • List list1 = new List(3, false);

  • list1.add("Vanilla");

  • list1.add("Chocolate");

  • list1.add("Strawberry");

  • add(list1);

  • List list2 = new List(3, true);

  • list2.add("Colored Sprinkles");

  • list2.add("Cashews");

  • list2.add("Kiwi");

  • add(list2);

  • pack();

  • setVisible(true);

  • }}



Other GUI Controls

  • Choice Lists (Combo Boxes)

  • Textfields

  • Text Areas

  • Labels



Swing - New Features

  • Many more built-in controls

    • Image buttons, tabbed panes, sliders, toolbars, color choosers, HTML text areas, lists, trees, and tables.
  • Increased customization of components

    • Border styles, text alignments, and basic drawing features. Images can be added to almost any control.
  • A pluggable “look and feel”

  • Many miscellaneous small features



Whirlwind Tour of Basic Components

  • Starting points

    • JApplet
  • Swing equivalent of AWT components

    • JLabel, JButton, JPanel, JSlider
  • New Swing components

    • JColorChooser, JInternalFrame, JOptionPane
  • Other simple components

    • JCheckBox, JRadioButton, JTextField, JTextArea, JFileChooser


SwingSet – Java Web Start



Starting Point: JApplet

  • Content pane

    • A JApplet contains a content pane in which to add components. Changing other properties like the layout manager, background color, etc., also applies to the content pane. Access the content pane through getContentPane.
  • Layout manager

    • The default layout manager is BorderLayout (as with Frame and JFrame), not FlowLayout (as with Applet). BorderLayout is really layout manager of content pane.
  • Look and feel

    • The default look and feel is Java (Metal), so you have to explicitly switch the look and feel if you want the native look.


JApplet: Example Code

  • import java.awt.*;

  • import javax.swing.*;

  • public class JAppletExample extends JApplet {

  • public void init() {

  • WindowUtilities.setNativeLookAndFeel();

  • Container content = getContentPane();

  • content.setBackground(Color.white);

  • content.setLayout(new FlowLayout());

  • content.add(new JButton("Button 1"));

  • content.add(new JButton("Button 2"));

  • content.add(new JButton("Button 3"));

  • }

  • }



Swing Equivalents of AWT Components

  • JLabel

    • New features: HTML content images, borders
  • JButton

    • New features: icons, alignment, mnemonics
  • JPanel

    • New feature: borders
  • JSlider

    • New features: tick marks and labels


JButton

  • Main new feature: icons

    • Create an ImageIcon by passing the ImageIcon constructor a String representing a GIF or JPG file (animated GIFs!).
    • Pass the ImageIcon to the JButton constructor.
  • Other features

    • HTML content as with JLabel
    • Alignment: location of image with respect to text
    • Mnemonics: keyboard accelerators that let you use Alt-someChar to trigger the button.


JButton: Example Code

  • import java.awt.*;

  • import javax.swing.*;

  • public class JButtons extends JFrame {

  • public static void main(String[] args) {

  • new JButtons();

  • }

  • public JButtons() {

  • super("Using JButton");

  • WindowUtilities.setNativeLookAndFeel();

  • addWindowListener(new ExitListener());

  • Container content = getContentPane();

  • content.setBackground(Color.white);

  • content.setLayout(new FlowLayout());



JButton: Example Code (Continued)

  • JButton button1 = new JButton("Java");

  • content.add(button1);

  • ImageIcon cup = new ImageIcon("images/cup.gif");

  • JButton button2 = new JButton(cup);

  • content.add(button2);

  • JButton button3 = new JButton("Java", cup);

  • content.add(button3);

  • JButton button4 = new JButton("Java", cup);

  • button4.setHorizontalTextPosition(SwingConstants.LEFT);

  • content.add(button4);

  • pack();

  • setVisible(true);

  • }

  • }



JOptionPane

  • Very rich class with many options for different types of dialog boxes.

  • Five main static methods

    • JOptionPane.showMessageDialog
      • Icon, message, OK button
    • JOptionPane.showConfirmDialog
      • Icon, message, and buttons: OK, OK/Cancel, Yes/No, or Yes/No/Cancel
    • JOptionPane.showInputDialog (2 versions)
      • Icon, message, textfield or combo box, buttons
    • JOptionPane.showOptionDialog
      • Icon, message, array of buttons or other components


JOptionPane Message Dialogs (Windows LAF)



JOptionPane Confirmation Dialogs (Java LAF)



Other Simple Swing Components

  • JCheckBox

    • Note uppercase B (vs. Checkbox in AWT)
  • JRadioButton

    • Use a ButtonGroup to link radio buttons
  • JTextField

    • Just like AWT TextField except that it does not act as a password field (use JPasswordField for that)
  • JTextArea

    • Place in JScrollPane if you want scrolling
  • JFileChooser



Summary

  • Canvas: drawing area or custom component

  • Panel: grouping other components

  • Frame: popup window

  • Button: handle events with ActionListener

  • Checkbox, radio button: handle events with ItemListener

  • List box: handle single click with ItemListener, double click with ActionListener

  • Port simple AWT components by adding J to front of class name

  • JFrame and JApplet use content pane, not window



References

  • CWP: Chapter 12-15

  • http://java.sun.com/docs/books/tutorial/uiswing/

  • The End.

  • Thank you for patience!



Yüklə 475 b.

Dostları ilə paylaş:




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©azkurs.org 2024
rəhbərliyinə müraciət

gir | qeydiyyatdan keç
    Ana səhifə


yükləyin