Swing part 2 - PowerPoint PPT Presentation

1 / 34
About This Presentation
Title:

Swing part 2

Description:

The text can be set relatively to the icon. Horizontal text position ... All of these share similar behavior and props. Swing buttons. Making buttons ... – PowerPoint PPT presentation

Number of Views:28
Avg rating:3.0/5.0
Slides: 35
Provided by: csBg
Category:
Tags: part | props | swing

less

Transcript and Presenter's Notes

Title: Swing part 2


1
Swing part 2
  • Basic widgets and features

2
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

3
Code for JLabel
  • ImageIcon icon createImageIcon("images/middle.gi
    f")
  • label1 new JLabel("Image and Text", icon,
    JLabel.CENTER)
  • //Set the position of the text, relative to the
    icon label1.setVerticalTextPosition(JLabel.BOTTOM
    ) label1.setHorizontalTextPosition(JLabel.CENTER)
    label2 new JLabel("Text-Only Label")
  • label3 new JLabel(icon)

4
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

5
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.

6
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

7
actionPerformed example
  • b1 new JButton("Disable middle button")
  • b2 new JButton("Middle button)
  • b3 new JButton("Enable middle button)
  • b3.setActionCommand("enable")
  • b1.setActionCommand("disable")

8
actionPerformed code
  • public void actionPerformed(ActionEvent e)
  • if ("disable".equals(e.getActionCommand()))
  • b2.setEnabled(false)
  • b1.setEnabled(false)
  • b3.setEnabled(true)
  • else b2.setEnabled(true)
  • b1.setEnabled(true)
  • b3.setEnabled(false)

9
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

10
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

11
ItemEvent
  • public void itemStateChanged(ItemEvent e)
  • Object source e.getItemSelectable()
  • if (source chinButton) //...make a note of
    it...
  • else if (source glassesButton) //...make a
    note of it...
  • else if (source hairButton) //...make a note
    of it...
  • else if (source teethButton) //...make a note
    of it...
  • if (e.getStateChange() ItemEvent.DESELECTED)
    //...make a note of it... ...
  • updatePicture()

12
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

13
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)
  • The combination of the event info and the sources
    properties allows getting all the needed
    information on the users actions

14
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

15
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

16
Menu code
  • //Where the GUI is created
  • JMenuBar menuBar
  • JMenu menu, submenu
  • JMenuItem menuItem
  • JRadioButtonMenuItem rbMenuItem
    JCheckBoxMenuItem cbMenuItem
  • //Create the menu bar.
  • menuBar new JMenuBar()
  • //Build the first menu.
  • menu new JMenu("A Menu")

17
Menu code cont.
  • menuBar.add(menu)
  • menuItem new JMenuItem("Both text and icon",
    new ImageIcon("images/middle.gif"))
  • menu.add(menuItem)
  • menu.addSeparator()
  • submenu new JMenu("A submenu")
  • menu.add(submenu)
  • frame.setJMenuBar(theJMenuBar)

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
JList code
  • list new JList(data)
  • //data has type Object
  • list.setSelectionMode(ListSelectionModel.SINGLE_IN
    TERVAL_SELECTION) list.setLayoutOrientation(JList
    .HORIZONTAL_WRAP)
  • list.setVisibleRowCount(-1)
  • JScrollPane listScroller new JScrollPane(list)
  • listScroller.setPreferredSize(new Dimension(250,
    80))

21
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

22
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 can display rich text format,
    pictures and even HTML
  • Based on a document model

23
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
  • Better handling can be to get the text when
    needed (OK pressed, dialog closed)
  • The JTextArea is very similar, but with rows also

24
Code example
  • A Swing calculator!

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

26
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")

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

28
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())

29
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
30
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"))

31
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

32
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
33
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!

34
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