UI Components - PowerPoint PPT Presentation

1 / 39
About This Presentation
Title:

UI Components

Description:

The view, which displays the contents ... Model-View-Controller. The controller reacts to various events and decides what to do with them. ... – PowerPoint PPT presentation

Number of Views:83
Avg rating:3.0/5.0
Slides: 40
Provided by: chrisf2
Category:
Tags: components | the | view

less

Transcript and Presenter's Notes

Title: UI Components


1
UI Components
  • Java has a built in Graphical libraries which you
    can (and should) use to build GUIs with.
  • While not nearly as rich as some others
    (Microsofts MFC has a ton of stuff), Javas GUI
    library tried to include most, if not all, of
    what is needed, without confusing programmers by
    offering too much.
  • Java actually has two libraries the original
    AWT library and the Swing library. Swing
    components are designated by the capital J in
    front of them (JButton instead of Button, etc.)

2
UI Components
  • Use the Swing components using the AWT
    components isnt necessary. Many Swing
    components are subclasses of the AWT equivalents.

3
Model-View-Controller
  • Before I go on and show you everything Java can
    do, Ill go and explain how Java Library
    programmers built a lot of these components.
  • The nice part about pre-made libraries is that
    you dont have to worry about how something
    works, (you dont care how a JTextField stores
    its data, as long as you can access it), but it
    is useful to understand how things were done,
    especially when something goes wrong.

4
Model-View-Controller
  • A Design Pattern is a re-usable pattern which can
    model different behavior in a system.
  • Just like architects dont draw up (rarely,
    anyways) new blueprints for every house they
    build, neither do Software Engineers.
  • We can use a pre-designed way of solving a common
    problem, and these are called Design Patterns.
    These are very big in professional Software
    Engineering. (youre going to see these again in
    CISC475).

5
Model-View-Controller
  • Most Swing components are build using the
    Model-Controller-Viewer design Pattern.
  • This Design Pattern follows the general principal
    of Dont make one object responsible for too
    much. - Dont make one class implement
    everything and the kitchen sink.

6
Model-View-Controller
  • The Model-View-Controller Pattern splits the
    implementation up into 3 different classes to
    accomplish its goal
  • The model, which stores the contents
  • The view, which displays the contents
  • The controller, which handles the user input and
    controls what goes on

7
Model-View-Controller
  • The model is what stores the information about
    the class. For a button or a checkbox, it would
    store the text that is on the button/next to the
    checkbox, as well as some flags about whether the
    button/box was pressed or checked, etc. For a
    TextField, it would stores the current writing,
    where the cursor is, etc.
  • The view is how the information in the model is
    shown to the user. For a button, you could
    potentially have two different views using the
    same model. One view might show the standard
    button, another may make the button appear as a
    circle.

8
Model-View-Controller
  • The controller reacts to various events and
    decides what to do with them. If a user presses
    a key in a JTextField, the controller stores the
    character and then has the model update itself.
  • Java GUI elements all come with wrapper classes
    that abstract us from these 3 different
    components. When you want to know if a JCheckBox
    is selected, you call the wrapper classes
    isSelected() method, which asks the model and
    returns you the answer.

9
GUI components
  • Im going to go over a number of different GUI
    elements that are commonly used and how to use
    them.
  • This list is not going to be an exhaustive list
    nor should it be, for three reasons
  • Im going to make the naïve assumption that
    youve used a computer a few times in your life
    and can figure out what you need, then look up
    the API on how to use
  • There are entire books devoted to Swing and GUI
    development, so we dont have time to cover
    everything
  • Youll probably fall asleep.

10
Text Input
  • Java provides two Swing components for inputting
    Text input,
  • JTextField single row text input
  • JTextArea multiple row text input
  • Both of these derive from the same base class of
    JTextComponent
  • Both share a lot of common methods

11
JTextFields
  • Allow a single line of text input
  • JTextField tf new JTextField(20) // of
    columns
  • JTextField tf2 new JTextField(A
    textfield,20) // initial text, columns
  • To set the text in the field, call
    .setText(String)
  • To get text in the field, call .getText().trim()
    (the trim removes the whitespace from the field)
  • There are also is also a setColumns method, which
    can resize it. Note After doing this, you must
    call .validate() on whatever container it is in
    the recompute the size.
  • JPanel somePanelnew JPanel()
  • JTextField tfnew JTextField(Some input,20)
  • somePanel.add(tf)
  • tf.setColumns(50)
  • somePanel.validate() //This will make the
    panel notice the change and redraw

12
Password Fields
  • Java also provides a class called JPasswordField,
    which echos an echo character, usually a ,
    instead of the actually character being typed.
  • Uses a method called getPassword(), which returns
    a char array. This is done for security
    reasons.
  • Example of the Model-View-Controller at work!
    Same model as regular text input, different view.

13
Formatted Input
  • Again, be happy we now have Java 1.4
  • There used to be no good way to do on-the-fly
    input validation (only type numbers, etc.)
  • Now there is a class, JFormattedTextField, that
    will do this, and it comes with some predefined
    formatting tools ones for Numbers, Currency,
    Date/Time, IP Addresses, etc.
  • Pages 364-370 of your book has an excellent
    example of all of these at work.

14
Formatted Input
  • JFormattedTextField intField
  • new JFormattedTextField(NumberFormat.getIn
    tegerInstance())
  • To supply a default value, it takes an Object
    variable, so use a wrapper class to send it an
    numeric value
  • intField.setValue(new Integer(100))
  • This class returns the original integer back if
    the user did not change the input, or a long back
    if it did. So you need to cast it to use it.
  • Number value(Number)intField.getValue()
  • int myInt value.intValue()

15
Formatted Input
  • When an formatted text field loses focus, it can
    have different behaviors. The default is called
    commit or revert. If the input is valid, it is
    commited, or else it was changed back to what it
    was before the user entered input.
  • You can also attach a Verifier to a field, which
    will give focus back to that field if the input
    was invalid (note these dont work perfectly. )
  • You can also make your own Custom Formatters, by
    extending the DefaultFormatted class.

16
JTextArea
  • Just like JTextFields, except they are
    multi-row.
  • JTextArea theAreanew JTextArea(4,50)
    //rows,columns
  • Has methods for line wrapping
  • setLineWrap(boolean) wrap lines or not
  • setWrapStyleWord(boolean) wrap at word
    boundries or not.

17
JLabels
  • Probably the most simple GUI components, they
    just provide an unclickable text label.
  • As of Java 1.3, You can use HTML in all
    JComponents. These arent recommended for
    buttons, but they can be used effectively in
    labels. Just start the label with and end
    it with
  • JLabel htmlDemo
  • new JLabel(HI
    THERE
    )

18
JCheckBoxs
  • Used for when you want to collect a yes or no
    input for a user.
  • Often used with ActionListeners to change
    something when something is changed
  • JCheckBox italicBoxnew JCheckBox(Italic)
  • italicBox.addActionListener(new ActionListener()
  • public void actionPerformed(ActionEvent e)
  • if (italicBox.isSelected())
  • someLabel.setFont(new
    Font(Serif, Font.ITALIC, 14)
  • )

19
RadioButtons
  • Sometimes we want to present a bunch of choice to
    a user for this, we can use Radio Buttons.
  • Just adding RadioButtons to a panel will give a
    behavior other then what you may expect. They
    will behave very similarly to checkboxes. This
    is usally not what we want.

20
RadioButtons
  • We usually want the standard behavior, which is
    that a selection is always forced, and when a
    different one is selected, the previous selection
    is automatically deselected.
  • Such a grouping is called a radio button group.
  • You create a ButtonGroup object, and then add the
    Radio Button to both the ButtonGroup AND to the
    GUI then the ButtonGroup object will take care
    of deselecting a previous button when another
    inside the group is selected.

21
RadioButtons
  • ButtonGroup group1 new ButtonGroup()
  • JPanel buttonPanel new JPanel()
  • JRadioButton noneButton new JRadioButton(Norma
    l, true) //selected
  • JRadioButton boldButton new JRadioButton(Bold
    , false)
  • group1.add(noneButton)
  • group1.add(boldButton)
  • buttonPanel.add(noneButton)
  • buttonPanel.add(boldButton)
  • Then we can add actionListener to the buttons if
    we want, or wait until some other event to happen
    (a user hitting another button maybe) and query
    all the buttons to see which one is selected

22
RadioButtons
  • By default, one Radio Button in a group is
    selected by default. If you dont selected one,
    or select more than 1, ButtonGroup will pick for
    you.
  • A trick to force the user to select one is to
    make another RadioButton, and only add it to the
    group but NOT to the GUI. Then choose this one
    as the default selection. It will force the user
    to choose.

23
Making a border
  • If you have more than one group of radio buttons
    near each other, things can get confusing.
  • A common solution is to place all the radio
    buttons in one group on a panel. Then, add a
    border to that panel.
  • You can apply a border to any component that
    extends JComponent.
  • To do so, use static methods of a class called
    BorderFactory.

24
Making a border
  • Creating a border is easy
  • Call a static method of the BorderFactory class.
    You can choose among lowered level, raised
    level, etched, line, matte, or empty.
  • You can add a title to your border by passing
    your border to BorderFactory.createTitleBorder().
  • You can combine several borders using
    BorderFactory.createCompoundBorder().
  • Add the resulting border to your component by
    calling the setBorder() method of the JComponent
    class.

25
Making a border
  • To create a compound etched and matte border with
    a title and place that border around a panel
  • Border etched BorderFactory.createEtchedBorder(
    )
  • Border matte BorderFactory.createMatteBorder()
  • Border combo BorderFactory.createCompoundBorde
    r(
  • etched, matte)
  • Border titled BorderFactoy.createTitledBorder(
  • combo, The Panels Title)
  • panel1.setBorder(titled)

26
Combo Boxes
  • When there are a lot of different choices (Fonts,
    for example) using Radio Buttons is clunky, so
    wed like to use a Combo Box. This is the
    drop-down list that most of you are familiar with
    in Word Processors with selected Font names and
    Font sizes.
  • These are, by default, editable. You can type in
    the box itself (you can disable this by calling
    setEditable(false)) Note, this only changes the
    selection, it doesnt modify the list.

27
Combo Box
  • To make a combo box, construct an object of class
    JComboBox, make it editable or not, and then add
    choices/items to it, using the addItem() method.
  • You can add items at specific places in the list
    by using the insertItemAt() method.
  • You can remove items using the removeItem()
    method (removes the last item) or the
    removeItemAt() method.

28
Combo Box
  • There is also a removeAllItems() method.
  • The combo box generates an action event whenever
    the user selects an item.
  • The listener can call the combo boxs
    getSelectedItem() retrieve the currently selected
    item. Note you need to cast this object to its
    correct type (normally a String).

29
Menus
  • One of the most common things to do with a GUI is
    have a menu bar.
  • A Menu is placed on top of a window, and contains
    the names of the different pull down menus.
  • Each pull down can have either menu items, or
    submenus.
  • When the user clicks on a menu item, all menus
    are closed and a message/event is sent to the
    program.

30
Menus
  • Building menus is relatively simple. First,
    construct a menu bar and then add it as the menu
    bar of a frame
  • JMenuBar menuBar new JMenuBar()
  • frame1.setJMenuBar(menuBar)
  • For each menu on the menu bar, create a JMenu
    class object. For all top-level menus, add them
    to the menu bar
  • JMenu editMenu new JMenu(Edit)
  • menuBar.addMenu(editMenu)

31
Menus
  • You can then add the menu items, sub menus, or
    seperators
  • // create two menu item objects
  • JMenuItem cutItem new JMenuItem(Cut)
  • JMenuItem pasteItem new JMenuItem(Paste)
  • // add them a separator to the edit menu
  • editMenu.add(cutItem)
  • editMenu.add(pasteItem)
  • editMenu.addSeparator()
  • // make an options submenu and add to the edit
    menu
  • JMenu optionsMenu new JMenu(Options)
  • editMenu.add(optionsMenu)
  • Then we can add Action Listeners to each
    JMenuItem to do what we want when that selection
    is chosen.

32
Key Mnemonics
  • Menu can have key Mnemonics, where typing
    alt- will active them. For a menu item,
    use
  • JMenu helpMenu new JMenu(Help)
  • helpMenu.setMnemonic(H)
  • For menu items, we just add it to the JMenuItem
    constructor.
  • JMenuItem cutItem new JMenuItem(Cut,C)

33
Tool Tips
  • Any component can have a ToolTip
  • These are those little pop up messages that
    appear if you hold the mouse cursor over a
    component for some predefined amount of time
  • Just use the .setToolTipText method
  • JButton someButton new JButton(Do
    something)
  • someButton.setToolTipText(This will be the
    tooltip)

34
Dialog Boxes
  • Sometimes we want to stop the user immediately
    and request input.
  • Generally, this is done with a Dialog Box.
  • In Java, there are two flavors of Dialog Boxes.
  • Modal- Will not let user deselected it forces
    input
  • Modeless- this type of dialog box can coexist
    with other windows. An example is a toolbar,
    detached from its frame. The user can freely
    interact with this dialog box and the other boxes
    in the application.

35
Dialog Boxes
  • Simple Dialog boxes can be show with the
    JOptionPane class. There are several you can
    choose from
  • showMessageDialog() show a message and wait for
    the user to click OK
  • showConfirmDialog() show a message a get
    confirmation (OK or Cancel)
  • showOptionDialog() show a message and get a
    user option from a set of options
  • showInputDialog() show a message and get one
    line of user input.

36
Dialog Boxes
  • Dialog Boxes should have parent frames (the frame
    to layer it on top of)
  • The contents of a JOptionPane dialog box include
    an icon, a message, and one or more option
    buttons.
  • The InputDialog accepts user input. This can be
    from a text field or a combo box.
  • The exact layout of the dialogs and the icons
    displayed for the message types is dependent of
    the underlying windowing system (the
    look-and-feel of the application/system).

37
Dialog Boxes
  • Depending on what you want to do, you have a
    choice of which Dialog to show
  • When calling showMessageDialog() and
    showInputDialog(), you get only a standard set of
    buttons (OK and OK/Cancel), respectively.
  • When calling showConfirmDialog(), you choose from
    four types DEFAULT_OPTION, YES_NO_OPTION,
    YES_NO_CANCEL_OPTION, and OK_CANCEL_OPTION.

38
Dialog Boxes
  • Dialog Boxes return a value after they are used.
  • Once you call one of these show methods, your
    program waits until the user deals with the
    dialog box. Then
  • showMessageDialog() returns nothing.
  • showConfirmDialog() returns an integer
    representing the chosen option.
  • showOptionDialog() returns an integer
    representing the chosen option.
  • showInputDialog() returns a string that the user
    supplier or chose.

39
Other Components
  • Javas component library doesnt end here. It
    also contains JSliders (sliding value bars),
    JSpinners (Input boxes with arrows to choose
    value), etc.
  • The purpose of this lecture was to cover the most
    commonly used ones.
  • In practice, if you want to use one of these,
    look up the API page. Most of these expose a
    large amount of methods.
Write a Comment
User Comments (0)
About PowerShow.com