swing programming

Upload: hoang-tuan-khanh

Post on 05-Apr-2018

230 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/2/2019 Swing Programming

    1/28

  • 8/2/2019 Swing Programming

    2/28

    What's Swing?What's Swing?

    Swing is Suns alternate WindowingSwing is Suns alternate WindowingFrameworkFramework

    Part of the JFC (Java FoundationPart of the JFC (Java Foundation

    Classes)Classes)

    Standard part of Java 2Standard part of Java 2

    A full replacement/alternative to AWTA full replacement/alternative to AWT

    Found in packages starting withFound in packages starting with

    javax.swingjavax.swing

    Key Features of SwingKey Features of Swing

    Not based on windowing systemNot based on windowing system

    all Swing components are lightweightall Swing components are lightweight

    Pluggable Look and Feel (PLAF)Pluggable Look and Feel (PLAF)

    Richer component set than AWTRicher component set than AWT

    Doesnt take the least commonDoesnt take the least common

    denominator approachdenominator approachincludes components not found in *any*includes components not found in *any*

    windowing systemwindowing system

    adds functionality to components thatadds functionality to components that

    already have counterparts in the AWTalready have counterparts in the AWT

  • 8/2/2019 Swing Programming

    3/28

    Using SwingUsing Swing

    Swing should not be combined withSwing should not be combined withAWTAWT

    Each Window should be fully Swing orEach Window should be fully Swing or

    fully AWTfully AWT

    Since Swing matches the AWTsSince Swing matches the AWTs

    functionality, thats not hardfunctionality, thats not hard

    Most Swing components areMost Swing components are

    upwards-compatible with their AWTupwards-compatible with their AWT

    counterpartscounterpartseasy to change code from AWT to Swingeasy to change code from AWT to Swing

    Swing ArchitectureSwing ArchitectureSwing follows theSwing follows the

    MVC paradigmMVC paradigm

    for building userfor building user

    interfacesinterfaces

    Each UIEach UI

    Component has aComponent has a

    modelmodel

    We will oftenWe will often

    customize certaincustomize certain

    Swing modelsSwing models

    data changechange

    notificationdata access

    gesturesand

    events

    View Controller

    Model

  • 8/2/2019 Swing Programming

    4/28

    Basic Swing ProgrammingBasic Swing Programming

    As noted previously, Swing adds anAs noted previously, Swing adds anentirely new set of components to Javaentirely new set of components to Java

    Upward-compatible with their AWTUpward-compatible with their AWT

    counterpartscounterparts

    We wont deeply cover those similar toWe wont deeply cover those similar to

    their AWT counterpartstheir AWT counterparts

    We will start at the bottomWe will start at the bottom

    JFrameJFrame

    JappletJapplet

    Top-level hierarchyTop-level hierarchy

    Each top-levelEach top-level

    class adds newclass adds new

    behavior tobehavior to

    existing AWTexisting AWT

    componentscomponents

    Frame

    JFrame

    Dialog

    JDialog

    Applet

    JApplet

    Window

  • 8/2/2019 Swing Programming

    5/28

    Comparing Swing & AWTComparing Swing & AWT

    import java.awt.*;

    public class ExampleAWTFrame extends java.awt.Frame {

    public ExampleAWTFrame ( ) {

    super();

    Panel aPanel = new Panel();

    aPanel.setLayout(new BorderLayout());

    add(aPanel);

    Label hello = new Label("Hello World");

    aPanel.add(hello, BorderLayout.NORTH);

    }

    public static void main(String args[]) {

    ExampleAWTFrame aFrame = new ExampleAWTFrame();

    aFrame.setVisible(true);

    }}

    Comparing Swing & AWTComparing Swing & AWTimport java.awt.*;

    import com.sun.java.swing.*;

    public class ExampleSwingJFrame extends com.sun.java.swing.JFrame {

    public ExampleSwingJFrame() {

    super();

    JPanel aPanel = new JPanel();

    aPanel.setLayout(new BorderLayout());

    getContentPane().add(aPanel);

    JLabel hello = new JLabel("Hello World");

    aPanel.add(hello, BorderLayout.NORTH);

    }

    public static void main(String args[]) {

    ExampleSwingJFrame aFrame = new ExampleSwingJFrame();

    aFrame.setVisible(true);

    }}

  • 8/2/2019 Swing Programming

    6/28

    JFramesJFrames

    A JFrame acts like an AWT FrameA JFrame acts like an AWT FrameExcept it handles Swing componentExcept it handles Swing component

    nestingnesting

    A JFrame is really two panesA JFrame is really two panes

    A LayeredPane that has an optionalA LayeredPane that has an optional

    menu bar and a content panemenu bar and a content pane

    A GlassPane that sits transparently inA GlassPane that sits transparently in

    front of the LayeredPanefront of the LayeredPane

    Partial Swing HierarchyPartial Swing Hierarchy

    JComponent

    AbstractButton

    JButton JToggleButtonJMenuItem

    JComboBox JPanelJLabel JList JSlider JTreeJTable

    JTabbedPane JScrollPane

    Container

  • 8/2/2019 Swing Programming

    7/28

    BordersBorders

    Any JComponent can have a BorderAny JComponent can have a Borderplaced on itplaced on it

    Usually only used on JPanelsUsually only used on JPanels

    Specify the border withSpecify the border with

    aJComponent.setBorder(Border aBorder)aJComponent.setBorder(Border aBorder)

    Common Borders include BevelBorder,Common Borders include BevelBorder,

    TitledBorderTitledBorder

    Normally built with a BorderFactoryNormally built with a BorderFactory

    JTitledBorder ExampleJTitledBorder Example

    public ExampleWithGroupBox ( ) {

    super();

    JPanel aPanel = new JPanel();

    aPanel.setLayout(new BorderLayout());

    TitledBorder border =

    BorderFactory.createTitledBorder(BorderFactory.createBevelBorder(2), "Group");

    aPanel.setBorder(border);

    getContentPane().add(aPanel);

    JLabel hello = new JLabel("Hello World");

    aPanel.add(hello, BorderLayout.CENTER);

    }

  • 8/2/2019 Swing Programming

    8/28

    JTabbedPaneJTabbedPane

    A JTabbedPane represents a notebookA JTabbedPane represents a notebookAny JComponent can be a page in aAny JComponent can be a page in a

    JTabbedPaneJTabbedPane

    JPanels are usually usedJPanels are usually used

    Tabs can be added, inserted at runtime,Tabs can be added, inserted at runtime,

    deleted and selecteddeleted and selected

    Creating TabsCreating Tabs

    public ExampleWithTabbedPane ( ) {

    super();

    JTabbedPane tabs = new JTabbedPane();

    tabs.addTab("Page1", buildTabOne());

    tabs.addTab("Page2", buildTabTwo());

    tabs.addTab("Page3", buildTabThree());

    getContentPane().add(tabs);

    }

    public JPanel buildTabOne() {

    JPanel aPanel = new JPanel();

    JLabel first = new JLabel("This is the first tab");

    aPanel.add(first, BorderLayout.CENTER);

    return aPanel;

    }

  • 8/2/2019 Swing Programming

    9/28

    JTabbedPane DetailsJTabbedPane Details

    Tabs are indexed from 0Tabs are indexed from 0JTabbedPane.getTabCount();JTabbedPane.getTabCount();

    Can remove tabs withCan remove tabs with

    JTabbedPane.removeTabAt(index);JTabbedPane.removeTabAt(index);

    Can select a tab withCan select a tab with

    JTabbedPane.setSelectedIndex(index)JTabbedPane.setSelectedIndex(index)

    JTabbedPane EventsJTabbedPane Events

    The JTabbedPane supports theThe JTabbedPane supports the

    ChangedEvent notificationChangedEvent notification

    Clients must implement theClients must implement the

    ChangeListener interfaceChangeListener interface

    void stateChanged(ChangeEvent e)void stateChanged(ChangeEvent e)

    No state information is passed inNo state information is passed inquery the source for the new statequery the source for the new state

  • 8/2/2019 Swing Programming

    10/28

    JScrollPaneJScrollPane

    A JScrollPane manages scrolling over aA JScrollPane manages scrolling over alarger viewlarger view

    It manages a viewport on the viewIt manages a viewport on the view

    Viewport

    View

    JScrollPane exampleJScrollPane example

    /*

    * Add a Scroll pane to the Jframe. Put a JLabel having

    * the numbers 0 - 49 into the scrollPanes viewport

    *

    */

    public ExampleScrolling ( ) {

    super();

    JScrollPane scroller = new JScrollPane();

    getContentPane().add(scroller);StringBuffer bigBuffer = new StringBuffer();

    for (int i=0; i

  • 8/2/2019 Swing Programming

    11/28

    Scrollable InterfaceScrollable Interface

    Components that will be scrolled by aComponents that will be scrolled by aJScrollPane should implement theJScrollPane should implement the

    Interface ScrollableInterface Scrollable

    Most Swing components implement thisMost Swing components implement this

    alreadyalready

    This Interface defines methods toThis Interface defines methods to

    return the preferred size of the viewportreturn the preferred size of the viewport

    get the increment in pixels to scroll by unitget the increment in pixels to scroll by unit

    and blockand block

    JSplitPaneJSplitPane

    A JSplitPane is a splitter pane thatA JSplitPane is a splitter pane that

    allows the user to resize two componentsallows the user to resize two components

    dynamicallydynamically

    Can split horizontally or verticallyCan split horizontally or vertically

    Use the constantUse the constant

    JSplitPane.VERTICAL_SPLIT orJSplitPane.VERTICAL_SPLIT orJSplitPane.HORIZONTAL_SPLIT inJSplitPane.HORIZONTAL_SPLIT in

    the constructorthe constructor

  • 8/2/2019 Swing Programming

    12/28

    JSplitPane ExampleJSplitPane Example

    public ExampleWithSplitPane ( ) {

    JSplitPane splitter = new JSplitPane(JSplitPane.VERTICAL_SPLIT);

    splitter.setLeftComponent(new JTextArea());

    splitter.setRightComponent(new JTextArea());

    getContentPane().add(splitter);

    }

    public static void main(String args[]) {

    ExampleWithSplitPane example = new ExampleWithSplitPane();

    example.pack();

    example.setVisible(true);

    }

    JProgressBarJProgressBar

    A JProgressBar is a standardA JProgressBar is a standard

    Windows-like progress indicatorWindows-like progress indicator

    LED-like display like a Stereo systemLED-like display like a Stereo system

    It is usually used in its own Frame orIt is usually used in its own Frame or

    dialogdialog

    Often combined with one or more labelsOften combined with one or more labels

  • 8/2/2019 Swing Programming

    13/28

    JSliderJSlider

    A JSlider is a volume-control sliderA JSlider is a volume-control slidercomponentcomponent

    Familiar in many Windows applicationsFamiliar in many Windows applications

    Jsliders have a variety of attributesJsliders have a variety of attributes

    Major and Minor TicksMajor and Minor Ticks

    LabelsLabels

    Minimum & Maximum valuesMinimum & Maximum values

    Clients watch for the ChangeEventClients watch for the ChangeEvent

    notificationnotification

    Similar to JTabbedPaneSimilar to JTabbedPane

    JSlider ExampleJSlider Example

    public ExampleWithSlider ( ) {

    JPanel aPanel = new JPanel();

    aPanel.setLayout(new BorderLayout());

    getContentPane().add(aPanel);

    counterLabel = new JLabel("0");

    aPanel.add(counterLabel, BorderLayout.SOUTH);

    JSlider slider = new

    JSlider(SwingConstants.HORIZONTAL, 0, 100, 0);

    slider.setMajorTickSpacing(20);

    slider.setMinorTickSpacing(10);

    slider.setPaintTicks(true);

    slider.setPaintLabels(true);

    slider.addChangeListener(this);aPanel.add(slider, BorderLayout.NORTH);

    }

    public void stateChanged(ChangeEvent e) {

    int value = ((JSlider) e.getSource()).getValue();

    counterLabel.setText(Integer.toString(value));

    }

  • 8/2/2019 Swing Programming

    14/28

    AbstractButton HierarchyAbstractButton Hierarchy

    Swing has a number ofSwing has a number ofbutton componentsbutton components

    push buttons, radiopush buttons, radio

    buttons, check boxesbuttons, check boxes

    Usually each will use anUsually each will use an

    ActionListener to hookActionListener to hook

    into UI actionsinto UI actions

    actionPerformed( )

    AbstractButton ActionListener

    JButton JToggleButt on

    JCheckBox JRadioButton

    JButton ExampleJButton Examplepublic ExampleJButton() {

    super();

    JPanel aPanel = new JPanel();

    aPanel.setLayout(new BorderLayout());

    getContentPane().add(aPanel);

    JBut ton push = new JBut ton(" Push Me" );

    push.addActionListener(new ActionListener() {

    public void act ionPerform ed(ActionEvent evt) {

    buttonPushed();

    }});

    aPanel.add(push, BorderLayout.NORTH);

    this.addWindowListener(new WindowAdapter() {

    public void windowClosing(WindowEvent e) {

    System.exit(0);

    }

    });

    }

    public void buttonPushed() {

    System.out.println("The button was pushed");

    }

  • 8/2/2019 Swing Programming

    15/28

    JMenu HierarchyJMenu Hierarchy

    Swing Menus are similarSwing Menus are similarto Buttonsto Buttons

    JMenuItems also haveJMenuItems also have

    ActionListenersActionListeners

    This is because they areThis is because they are

    AbstractButtonsAbstractButtons

    JComponent

    JMenuBar AbstractButton

    JCheckBoxMenuItem JRadioButtonMenuItem

    JMenuItem

    JMenu

    JPopupMenu

    JMenu ExampleJMenu Example

    JMenuBar menuBar = new JMenuBar();

    setJMenuBar(menuBar); // method of JFrame

    JMenu testMenu = new JMenu("Test");

    JMenuItem menuItem = new JMenuItem("Select Me");

    menuItem.addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent evt) {

    menuSelected();

    }});

    testMenu.add(menuItem);

    menuBar.add(testMenu);

  • 8/2/2019 Swing Programming

    16/28

    Text HandlingText Handling

    Swing has text handlingSwing has text handlingcapabilities similar tocapabilities similar to

    AWTAWT

    JTextField,JTextField,

    JPasswordField,JPasswordField,

    JTextAreaJTextArea

    However, it also hasHowever, it also has

    sophisticated support forsophisticated support for

    viewing HTML and RTFviewing HTML and RTFJEditorPaneJEditorPane

    JTextComponent Document

    JTextField JTextArea JEditorPane

    DocumentListener

    JListJList

    JList is the primary Swing list classJList is the primary Swing list class

    Its like the AWT List widget except:Its like the AWT List widget except:

    The widget doesnt support adding &The widget doesnt support adding &

    removing elements directlyremoving elements directly

    Adds customized data modelsAdds customized data models

    Adds custom element renderingAdds custom element rendering

  • 8/2/2019 Swing Programming

    17/28

    Simple JList ExampleSimple JList Example

    /*

    * You must place a Jlist inside a JScrollPane to get scroll bars!

    */

    public ExampleSimpleList ( ) {

    String[] strings = {"Bob", "Carol", "Ted", "Alice", "Jane", "Fred", "Sue"};

    JScrollPane scroller = new JScrollPane();

    JList aList = new JList(strings);

    scroller.getViewport().add(aList);

    getContentPane().add(scroller);

    }

    JList ConstructorsJList Constructors

    Jlist has four constructorsJlist has four constructors

    JList()JList()

    JList(Object[])JList(Object[])

    JList(Vector)JList(Vector)

    JList(ListModel)JList(ListModel)

    Use the array and Vector versions onlyUse the array and Vector versions onlyfor simple, static listsfor simple, static lists

    For more complex lists, use a ListModelFor more complex lists, use a ListModel

  • 8/2/2019 Swing Programming

    18/28

    ListModelListModel

    A ListModelA ListModel

    represents a list ofrepresents a list of

    elements to a JListelements to a JList

    SubclassSubclass

    AbstractListModelAbstractListModel

    to override getSize()to override getSize()

    and getElementAt()and getElementAt()

    contentsChanged( )

    ListModel

    getSize( )getElementAt( )addListDataListener( )

    removeListDataListener( )

    AbstractListModel

    addListDataListener( )

    removeListDataListener( )

    ListDataListener

    intervalAdded( )

    intervalRemoved( )

    fireContentsChanged( )

    fireIntervalAdded( )

    fireIntervalRemoved( )

    ListModelsListModels

    There would be several reasons youThere would be several reasons you

    might make a ListModelmight make a ListModel

    Loading database information as it isLoading database information as it is

    requestedrequested

    Synthetic lists of calculated itemsSynthetic lists of calculated items

    As our example well store informationAs our example well store informationin a hashtable, and display the keys asin a hashtable, and display the keys as

    they were added to the hashtablethey were added to the hashtable

  • 8/2/2019 Swing Programming

    19/28

    Example ListModelExample ListModelpublic class CustomListModel extends AbstractListModel {

    Hashtable data = new Hashtable();

    Vector orderedKeys = new Vector();

    public void put(Object key, Object value) {

    data.put(key, value);

    if (!orderedKeys.contains(key))

    orderedKeys.addElement(key);

    fireContentsChanged(this, -1, -1);

    }

    public Object get(Object key) { return data.get(key);}

    public Object getElementAt(int index) { return orderedKeys.elementAt(index);}

    public int getSize() { return orderedKeys.size();}

    }

    ListModel ExampleListModel Example

    public ExampleCustomListModelList ( ) {

    JPanel outerPanel = new JPanel();

    outerPanel.setLayout(new BorderLayout());

    JScrollPane scroller = new JScrollPane();

    JList aList = new JList(buildCustomListModel());

    scroller.getViewport().add(aList);

    JButton button = new JButton("Add");

    button.addActionListener(this);

    outerPanel.add(scroller, BorderLayout.NORTH);

    outerPanel.add(button, BorderLayout.SOUTH);

    getContentPane().add(outerPanel);

    }

    public void actionPerformed(ActionEvent e) {

    model.put("As", "If");

    }

  • 8/2/2019 Swing Programming

    20/28

    JList EventsJList Events

    JLists support the ListSelection eventJLists support the ListSelection eventnotificationnotification

    Clients implement theClients implement the

    ListSelectionListener interfaceListSelectionListener interface

    void valueChanged(ListSelectionEvent e)void valueChanged(ListSelectionEvent e)

    A ListSelectionEvent knows severalA ListSelectionEvent knows several

    thingsthings

    first selected indexfirst selected index

    last selected indexlast selected index

    getValueIsAdjusting()getValueIsAdjusting()

    JList Event ExampleJList Event Example

    public class ExampleListListening extends JFrame implements ListSelectionListener {

    ExampleListListening() {

    JList aList = new JList(someModel);

    aList.addListSelectionListener(this);

    public void valueChanged(ListSelectionEvent e) {if (!event.getValueIsAdjusting()) {

    String value = event.getSource().getSelectedValue();

    System.out.println(Selection is + value);

    }

    }

    }

  • 8/2/2019 Swing Programming

    21/28

    List Cell RenderingList Cell Rendering

    JList gives you the option to display notJList gives you the option to display notjust Strings, but graphical icons as welljust Strings, but graphical icons as well

    You need to create a new cell rendererYou need to create a new cell renderer

    implement the ListCellRenderer interfaceimplement the ListCellRenderer interface

    set the custom text and icon (image) in thisset the custom text and icon (image) in this

    classclass

    JTableJTable

    JTable is a Tabular (row-column) view withJTable is a Tabular (row-column) view with

    read-only or editable cellsread-only or editable cells

    Can create a JTable on:Can create a JTable on:

    Two ArraysTwo Arrays

    2d array of data, 1d array of column headings2d array of data, 1d array of column headings

    Two VectorsTwo Vectors(data of length row X columns), column(data of length row X columns), column

    headingsheadings

    TableModel, (optionally) ListSelectionModel andTableModel, (optionally) ListSelectionModel and

    TableColumnModelTableColumnModel

  • 8/2/2019 Swing Programming

    22/28

    Table ModelsTable Models

    TableModel is anTableModel is aninterface that definesinterface that defines

    the row/columnthe row/column

    behaviorbehavior

    AbstractTableModelAbstractTableModel

    implements most of theimplements most of the

    behaviorbehavior

    you implementyou implement

    getColumnCount(),getColumnCount(),getRowCount(),getRowCount(),

    getValueAt()getValueAt()

    TableModel

    getColumnCount( )

    getRowCount( )

    getValueAt( )isCellEditable( )

    AbstractTableModel

    JDBCAdapterYourTableModel

    Example Table ModelExample Table Model

    public ExampleTableCustomModel() {

    super();

    JTable table = new JTable(new CustomDataModel());

    createColumnHeadings(table);

    getContentPane().add(table.createScrollPaneForTable(table));

    }

    public void createColumnHeadings(JTable table) {

    String headers[] = {"Zero", "One", "Two", "Three", "Four"};

    table.setAutoCreateColumnsFromModel(false);

    for (int i=0; i

  • 8/2/2019 Swing Programming

    23/28

    Example Custom ModelExample Custom Model

    public class CustomDataModel extends AbstractTableModel {

    /**

    * getColumnCount returns 0 since we will create columns ourselves

    */

    public int getColumnCount() { return 0;}

    public int getRowCount() {return 5;}

    /**

    * getValueAt is semi-bogus; it returns a string of row * column.

    */

    public Object getValueAt(int row, int col) {

    return Integer.toString(row * col);}

    }

    Table SelectionTable Selection

    There are several selection attributes ofThere are several selection attributes of

    JTable you can setJTable you can set

    setRowSelectionAllowed(boolean value)setRowSelectionAllowed(boolean value)

    setColumnSelectionAllowed(booleansetColumnSelectionAllowed(booleanvalue)value)

    setSelectionForeground(Color value)setSelectionForeground(Color value)setSelectionBackground(Color value)setSelectionBackground(Color value)

    You can also turn horizontal and verticalYou can also turn horizontal and vertical

    lines on and offlines on and off

  • 8/2/2019 Swing Programming

    24/28

    List SelectionList Selection

    JTables support ListSelectionJTables support ListSelectionnotificationnotification

    Clients must implement theClients must implement the

    ListSelectionListener interfaceListSelectionListener interface

    Just like JLists in that respectJust like JLists in that respect

    The Event doesnt carry the necessaryThe Event doesnt carry the necessary

    selection informationselection information

    You need to query the table for selectionYou need to query the table for selection

    informationinformationUse getSelectedRow(),Use getSelectedRow(),

    getSelectedColumn(), getValueAt()getSelectedColumn(), getValueAt()

    TableSelectionListenerTableSelectionListenerExampleExamplepublic class ExampleTableSelection extends JFrame implements ListSelectionListener {

    ExampleTableSelection() {

    JTable table = new JTable(someModel);

    ListSelectionModel selectionModel = table.getSelectionModel();

    selectionModel.addListSelectionListener(this);

    }

    public void valueChanged(ListSelectionEvent e) {JTable table = (JTable) e.getSource();

    DefaultTableModel model = (DefaultTableModel) table.getModel();

    int row = table.getSelectedRow();

    int column = table.getSelectedColumn();

    String value = (String) model.getValueAt(row, column);

    System.out.println(Selected value is + value);

    }

    }

  • 8/2/2019 Swing Programming

    25/28

    Swing TreesSwing Trees

    JTree is a hierarchical display componentJTree is a hierarchical display componentallows expansion, contraction, editing ofallows expansion, contraction, editing of

    nodesnodes

    JTree displays a TreeModelJTree displays a TreeModel

    TreeModel is built from TreeNodesTreeModel is built from TreeNodes

    MutableTreeNodes hold arbitrary objectsMutableTreeNodes hold arbitrary objects

    TreeModel HierarchyTreeModel Hierarchy

    TreeNode is an interfaceTreeNode is an interface

    that describes nodethat describes node

    behaviorbehavior

    MutableTreeNode is anMutableTreeNode is an

    interface that allowsinterface that allows

    addition/removal ofaddition/removal ofchildrenchildren

    DefaultMutableTreeNodeDefaultMutableTreeNode

    implementsimplements

    MutableTreeNodeMutableTreeNode

    TreeNode

    getParent( )children( )getChildAt( )

    isLeaf( )

    MutableTreeNode

    remove(MutableTreeNode )insert(MutableTreeNode, int )

    setParent( MutableTreeNode)setUserObject(Object )

    DefaultMutableTreeNode

    getUserObject( )

    add( MutableTreeNode)

  • 8/2/2019 Swing Programming

    26/28

    TreeNode ExampleTreeNode Example

    public DefaultMutableTreeNode buildTree() {DefaultMutableTreeNode root = new DefaultMutableTreeNode("Classes");

    DefaultMutableTreeNode level1a = new DefaultMutableTreeNode("Java");

    DefaultMutableTreeNode level1b = new DefaultMutableTreeNode("Smalltalk");

    root.add(level1a);

    root.add(level1b);

    level1a.add(new DefaultMutableTreeNode("Introduction to Java"));

    level1a.add(new DefaultMutableTreeNode("Advanced Java"));

    level1a.add(new DefaultMutableTreeNode("Enterprise Java Programming"));

    return root;

    }

    public ExampleSimpleTree() {

    JScrollPane scroller = new JScrollPane();JTree tree = new JTree(buildTree());

    scroller.getViewport().add(tree);

    getContentPane().add(scroller);

    }

    Tree SelectionTree Selection

    JTrees support the TreeSelectionEventJTrees support the TreeSelectionEvent

    notificationnotification

    Clients must implement theClients must implement the

    TreeSelectionListener interfaceTreeSelectionListener interface

    void valueChanged(TreeSelectionEvent e)void valueChanged(TreeSelectionEvent e)

    Use the JTree method getSelectionPath()Use the JTree method getSelectionPath()to get a TreePath that gives theto get a TreePath that gives the

    selection(s)selection(s)

  • 8/2/2019 Swing Programming

    27/28

    Tree ExpansionTree Expansion

    JTrees also support theJTrees also support theTreeExpansionEvent notificationTreeExpansionEvent notification

    Clients implement TreeExpansionListenerClients implement TreeExpansionListener

    void treeExpanded(TreeExpansionEvent e)void treeExpanded(TreeExpansionEvent e)

    void treeCollapsed(TreeExpansionEvent e)void treeCollapsed(TreeExpansionEvent e)

    You can ask the TreeExpansionEvent toYou can ask the TreeExpansionEvent to

    getPath() and return the affected pathgetPath() and return the affected path

    SummarySummary

    Swing is a comprehensive expansion andSwing is a comprehensive expansion and

    replacement for AWTreplacement for AWT

    You've seen some basic and advancedYou've seen some basic and advanced

    concepts in Swing Programmingconcepts in Swing Programming

  • 8/2/2019 Swing Programming

    28/28

    More InformationMore Information

    For more information, see the SwingFor more information, see the Swingtutorials on the Sun Java Developer'stutorials on the Sun Java Developer's

    Connection websiteConnection website

    (http://developer.java.sun.com)(http://developer.java.sun.com)

    requires registration (free)requires registration (free)

    Steven Gutz, "Up to Speed With Swing,Steven Gutz, "Up to Speed With Swing,

    2nd Edition", Manning, 20002nd Edition", Manning, 2000