Swing part 1 - PowerPoint PPT Presentation

1 / 33
About This Presentation
Title:

Swing part 1

Description:

Mouse and key events. Widget's state properties. Visible or not ... Can be edited as a text field if set as editable. Therefore has a slightly different model ... – PowerPoint PPT presentation

Number of Views:51
Avg rating:3.0/5.0
Slides: 34
Provided by: csBg
Category:
Tags: part | swing

less

Transcript and Presenter's Notes

Title: Swing part 1


1
Swing part 1
  • Basic widgets and features

2
How to learn new a widget
  • How does it looks?
  • The Swing tutorial has a visual index
  • What does it do?
  • What properties does it have?
  • What meaningful events does if fire?
  • What data does is supplies?
  • Data properties, like value or text
  • Alternatively, get the model itself by getModel()

3
The JComponent class
  • Root class for Swings widgets (except top-level)
  • Based on AWT container
  • A simple Swing widget is a composite AWT widget
  • But it doesnt mean you should exploit this!
  • Supports basic properties and events
  • Widgets state
  • Basic appearance
  • Layout properties
  • Mouse and key events

4
Widgets state properties
  • Visible or not
  • Enabled / disabled
  • Disabled widgets do not respond and are grayed
    out
  • Tool tip text
  • Important for helping the user
  • Name
  • Each widget has a name which identifies it within
    the containing widget

5
Basic appearance properties
  • Foreground and background color
  • Mostly handled by the look feel
  • Opaque or transparent
  • Font (for text)
  • Border
  • Borders can surrounds all widgets
  • Useful mainly for panels
  • To be mentioned in details later

6
Basic layout properties
  • Usually the laying out will be done by the layout
    manager of the containing widget
  • The programmer can supply tips for the layout
  • Minimum and maximum size
  • Preferred size
  • X and Y alignment
  • Most widgets (buttons, labels, toolbars...) will
    handle size automatically

7
Common events
  • All widgets support mouse and key events
  • Mouse event occurs in respond to mouse pointer
    actions
  • Motions
  • Clicks
  • But usually the widget will handle those
  • Key events respond to key pressing
  • Used for key accelerators

8
JLabel class
  • A very basic doesnt do anything but show
  • Can include the properties
  • Text
  • Icon
  • The text can be set relatively to the icon
  • Horizontal text position
  • LEFT, CENTER, RIGHT, LEADING or TRAILING
  • Vertical text position
  • TOP, CENTER or BUTTOM

9
The Icon interface
  • A common interface for icons in labels, buttons,
    and so on
  • Most commonly used implementation is the
    ImageIcon, which reads the icon from GIF or JPEG
    files
  • Need to be available to the application!
  • Other implementations are usually specific to
    special look feels

10
Swing buttons
  • Swing has a family of buttons which derives from
    the AbstractButton class
  • Simple buttons (JButton)
  • Toggle buttons
  • Simple toggle buttons (on/off)
  • Check boxes
  • Radio buttons
  • Menu buttons like regular buttons but in a menu
  • All of these share similar behavior and props.

11
Making buttons
  • Buttons are constructed similarly to labels, with
    text and/or an icon
  • To make them work, it is needed also to add and
    action listener
  • Alternatively you can use the action interface
    and the DefaultAction implementation
  • Default action is also made with text and icon
  • And also has abstract actionPerformed() method
  • Useful to make a single action to different
    buttons
  • Can be enabled or disabled for all usage

12
The JButton class
  • Simplest button class
  • Used for buttons on panels or toolbars
  • Uses ActionEvent and takes ActionEventListener as
    listener
  • Resized by icon and text
  • Very simple

13
Selectable buttons
  • Toggle buttons, check boxes and radio buttons can
    be selected or not
  • All buttons has a selected property with
    isSelected() and setSelected() methods
  • Makes sense only for selectable buttons, though
  • When selected, they fire
  • actionEvent
  • ItemEvent
  • ChangeEvent
  • You can always get the state from the source
    itself

14
Handling buttons events
  • Need to
  • Identify what to do which button was pressed
  • Get the value selected or not
  • You can
  • Set a different listener to each button
  • Can be an anonymous one
  • Use the same listener to several buttons and
  • Get the source from the event
  • Use the action command string of action event

15
On event objects
  • Event objects are the parameters to the event
    listener methods, which are called when the event
    is fired
  • Usually contains
  • A pointer to the firing widget (the source)
  • Information on the event (indexes, keys pressed)
  • A marker isValueAdjusting()
  • The combination of the event info and the sources
    properties allows getting all the needed
    information on the users actions

16
Radio buttons
  • Radio buttons are selectable buttons which comes
    in groups
  • In a group only one radio button can be selected
  • To force this, add the buttons to a ButtonGroup
    which forces this policy
  • The button group works with the abstract button
    class, so actually it can work with any sort of
    button

17
Menu buttons
  • Menus are contained in a menu bar (JMenuBar)
  • The frame has a JMenuBar property
  • The menu bar contains menus
  • The menus can contain
  • Menu buttons, like menu items, menu check boxes
    and menu radio buttons
  • Sub-menus, recursively (which extends menu item)
  • Menu buttons acts just like normal buttons

18
Selection widgets
  • A common role for a widget is selecting one (or
    several) items out of a group
  • Radio buttons and check boxes can serve somehow
    to do that
  • More specialized widgets for that purpose
  • Lists
  • Combo boxes
  • The items are objects, and can be anything,
    although rendered as strings by default

19
JList class
  • Can be initialized with an array or vector of
    items, or with a given list model (interface)
  • Selection models single selection, single
    interval or multiple intervals
  • Fires ListSelectionEvent which holds the first
    and last index selected
  • can get selected items from list itself
  • Can use DefaultListModel as model to add and
    remove items dynamically

20
JComboBox class
  • Very much like a single-selection list
  • Can be edited as a text field if set as editable
  • Therefore has a slightly different model
  • Fires an ActionEvent when
  • Selection changes
  • Edited and user presses enter
  • Can use actions

21
Text widgets
  • Swing has a set of widgets for handling text,
    from very simple to elaborated editors
  • Simple text field and Password text field
  • Plain text area
  • Styled text area editor pane and text pane
  • All can display and edit text conveniently
  • The styled widgets ca display rich text format,
    pictures and even HTML
  • Based on a document model

22
JTextField class
  • Has a text property which can be used to display
    text and read the entered text
  • Size can be set by number of columns
  • Events
  • ActionEvent fired on enter
  • Document model fires events on every character
  • Better handling can be to get the text when
    needed (OK pressed, dialog closed)
  • The JTextArea is very similar, but with rows also

23
Code example
  • A Swing calculator!

24
Class declaration
  • public class Calculator extends JFrame
  • private JTextField _arg1
  • private JTextField _arg2
  • private JTextField _result
  • private JComboBox _operands
  • private JButton _equals

25
Making the fields
  • public Calculator()
  • super("Swing calculator")
  • setSize(500, 100)
  • _arg1 new JTextField(10)
  • _arg2 new JTextField(10)
  • _result new JTextField(10)
  • _operands new JComboBox( new String "Add",
    "Subtract", "Multiply", "Divide")

26
Making a button using an action listener
  • _equals new JButton("")
  • _equals.addActionListener(
  • new ActionListener()
  • public void actionPerformed(ActionEvent e)
  • calculate()
  • )

27
Putting the widgets together
  • Container tPane getContentPane()
  • tPane.setLayout(new FlowLayout())
  • tPane.add(_arg1)
  • tPane.add(_operands)
  • tPane.add(_arg2)
  • tPane.add(_equals)
  • tPane.add(_result)
  • setJMenuBar(makeMenuBar())

28
Making an enabling action
  • private Action makeEnabler(final JComponent
    comp, String text)
  • return new AbstractAction(text, icon)
  • public void actionPerformed( ActionEvent e)
  • AbstractButton tBtn (AbstractButton)e
    .getSource()
  • comp.setEnabled(tBtn.isSelected())

Actually, could also be done with an action
listener, or just a button
29
Making the menu bar (1)
  • private JMenuBar makeMenuBar()
  • JMenu tMenu new JMenu("widgets")
  • JMenuItem tArg1Stat
  • new JCheckBoxMenuItem(
  • makeEnabler(_arg1, "enable arg 1"))
  • JMenuItem tArg2Stat
  • new JCheckBoxMenuItem(
  • makeEnabler(_arg2, "enable arg 2"))
  • JMenuItem tOpsStat
  • new JCheckBoxMenuItem(
  • makeEnabler(_operands, "enable operands"))

30
Making the menu bar (2)
  • tArg1Stat.setSelected(true)
  • tArg2Stat.setSelected(true)
  • tOpsStat.setSelected(true)
  • tMenu.add(tArg1Stat)
  • tMenu.add(tOpsStat)
  • tMenu.add(tArg2Stat)
  • JMenuBar tRet new JMenuBar()
  • tRet.add(tMenu)
  • return tRet

31
Calculating
  • private void calculate()
  • int tArg1 Integer.parseInt(_arg1.getText())
  • int tArg2 Integer.parseInt(_arg2.getText())
  • int tRes 0
  • String tOp (String)_operands.getSelectedItem()
  • if (tOp.equals("Add"))
  • tRes tArg1 tArg2
  • else if // and so on
  • _result.setText(""tRes)

There are better ways to do this
32
Running the calculator
  • public static void main(String args)
  • new Calculator().setVisible(true)
  • That wasnt too bad But notice that a more
    complex GUI might need to
  • Split into several classes (by panes or roles)
  • Separate event handlers (if cant handle by
    anonymous ones)
  • Separate the handled data (the model) from the
    display
  • GUI is not a reason to write oversized classes!

33
Using basic widgets - summary
  • Did not covered (yet)
  • Tables, trees and other heavily-modeled widgets
  • Spinners and sliders (widgets with int value)
  • Rich text editors
  • Dialogs and choosers
  • But covered enough to
  • Learn a new widget from documentation
  • Write simple event handlers
  • Try it out!
Write a Comment
User Comments (0)
About PowerShow.com