730 likes | 750 Views
Swings. Agenda. Introduction Swings Event Handling Containers Swing Components Layout Managers. Swing overview. Defined in package javax.swing Original GUI components from AWT in java.awt Heavyweight components - rely on local platform's windowing system for look and feel
E N D
Agenda • Introduction • Swings • Event Handling • Containers • Swing Components • Layout Managers
Swing overview • Defined in package javax.swing • Original GUI components from AWT in java.awt • Heavyweight components - rely on local platform's windowing system for look and feel • Swing components are lightweight • Not weighed down by GUI capabilities of platform • More portable than heavyweight components • Swing components allow programmer to specify look and feel • Can change depending on platform • Can be same across all platforms
java.awt.Component java.awt.Container javax.swing.JComponent java.lang.Object Swing component inheritance hierarchy • Component defines methods used in its subclasses • (for example, paint and repaint) • Container - collection of related components • When using JFrame, add components to content pane (a Container) • JComponent - superclass to most Swing components
Swing vs. AWT • Swing is bigger • Swing is more flexible and better looking • Swing and AWT are incompatible--you can use either, but you can’t mix them • Learning the AWT is a good start on learning Swing • AWT: Button b = new Button (“OK”);Swing: Jbutton b = new Jbutton(“OK”);
To build a GUI... • Make somewhere to display things--a Frame, a Window, or an Applet • Create controls (buttons, text areas, etc.) • Add your controls to your display area • Arrange, or lay out, your controls • Attach Listeners actions to your controls
GUI Builders • Netbeans (Sun) • JBuilder (Borland) • Eclipse (IBM and others) • Visual Editor • Help Software Updates Find and Install…
JFC – Java Foundation Classes • Graphical framework for building portable Java-based graphical user interfaces (GUIs). • Features of the Java Foundation Classes • Swing GUI Components • Pluggable Look-and-Feel Support • Accessibility API • Java 2D API • Internationalization
Swing Features • Vast Range of Components • Pluggable Look and Feel • Data Transfer • Drag and Drop • Cut, Copy, and Paste • Internationalization and Localization • Accessibility • Integrating with the Desktop • System Tray Icon Support
Swing Components JOptionPane JProgressBar JRootPane JSeparator JSlider JSplitPane JTabbedPane JToolBar JToolTip JViewport JColorChooser JTextComponent JTextArea JTextField JPasswordField JTextField JEditorPane JTextPane JFileChooser JLayeredPane JDesktopPane AbstractButton AbstractButton Class JToggleButton -- JCheckBox and JRadioButton JButton JMenuItem -- JMenu, JRadioButtonMenuItem and JCheckButtonItem JApplet JDialog JFrame JWindow JComponent JComboBox JLabel JList JMenuBar JPanel JPopupMenu JScrollBar JScrollPane JTable JTree JInternalFrame
Swing Architecture – MVC Architecture • Swing uses the Model-View-Controller architecture (MVC) as the fundamental design behind each of its components. • MVC breaks GUI components into 3 elements • Each elements plays an important role in how component behaves • Allows for Portability etc.
Basic MVC Model • The three elements interact as follows: • The MVC Communication Model
MVC in Swing Swing uses a simplified model of the MVC design: model-delegate • Combines View and Controller into a single element -- the UI-delegate • Easy to bundle graphics and event handling in Java -- AWT. • Model delegate interaction is now Two way. • Model -- maintains information • UI-delegate -- Draws and reacts to events that propagate through component
Event Delegation Model • Source and the Listener • Event Listeners • Event Sources • Adapters
Your First Swing Program Import javax.swing.*; public class JFrameTester { public static void main(String[] args) { JFrame jf = new JFrame("My JFrame"); jf.getContentPane().setLayout(new FlowLayout()); JButton button = new JButton("My Button"); jf.setSize(250, 250); jf.setLocation(300,200); jf.getContentPane().add(button); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jf.setVisible(true); } }
Lets Add Action to the Button • public class JFrameTester implements ActionListener { • public static void main(String[] args) { • SwingUtilities.invokeLater(new Runnable() { • public void run() { • JFrameTester test = new JFrameTester(); • test.createAndShowFrame(); • } • }); • }
public void createAndShowFrame() { • JFrame jf = new JFrame("My JFrame"); • jf.getContentPane().setLayout(new FlowLayout()); • JButton button = new JButton("My Button"); • button.addActionListener(this); • jf.setSize(250, 250); • jf.setLocation(300, 200); • jf.getContentPane().add(button); • jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); • jf.setVisible(true); • } • public void actionPerformed(ActionEvent e) { • ((JButton)e.getSource()).setText("Action Event"); • } • }
Types of Event Classes / Listeners • ActionEvent ActionListener • AdjustmentEvent AdjustmentListener • ComponentEvent ComponentListener • ContainerEvent ContainerListener • FocusEvent FocusListener • ItemEvent ItemListener • KeyEvent KeyListener • MouseEvent MouseListener • MouseWheelEvent MouseWheelListener • TextEvent TextListener • WindowEvent WindowFocusListener,WindowListener
AdapterClasses / Listeners • ComponentAdapter ComponentListener • ContainerAdapter ContainerListener • FocusAdapter FocusListener • KeyAdapter KeyListener • MouseAdapter MouseListener • MouseMotionAdapter MouseMotionListener • WindowAdapter WindowListener
Adapter Example public void createAndShowFrame() { JFrame jf = new JFrame("My JFrame"); jf.getContentPane().setLayout(new FlowLayout()); JButton button1 = new JButton("My Button1"); JButton button2 = new JButton("My Button2"); button2.addFocusListener(new MyFocusAdapter()); jf.setSize(250, 250); jf.setLocation(300, 200); jf.getContentPane().add(button1); jf.getContentPane().add(button2); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jf.setVisible(true); } class MyFocusAdapter extends FocusAdapter{ public void focusGained(FocusEvent e){ ((JButton)e.getSource()).setText("Focus Adapter"); } } }
Top Level Containers • Swing provides three generally useful top-level container classes: JFrame, JDialog, and JApplet. • To appear onscreen, every GUI component must be part of a containment hierarchy. A containment hierarchy is a tree of components that has a top-level container as its root. • Each GUI component can be contained only once. If a component is already in a container and you try to add it to another container, the component will be removed from the first container and then added to the second. • Each top-level container has a content pane that, generally speaking, contains (directly or indirectly) the visible components in that top-level container's GUI.
Panes • Root Pane • Content Pane • Glass Pane • Layered Pane
JFrames • Like all other JFC/Swing top-level containers, a JFrame contains a JRootPane as its only child. The content pane provided by the root pane should, as a rule, contain all the non-menu components displayed by the JFrame. This is different from the AWT Frame case. For example, to add a child to an AWT frame you'd write: • frame.add(child); • However using JFrame you need to add the child to the JFrame's content pane instead: • frame.getContentPane().add(child);
The same is true for setting layout managers, removing components, listing children, and so on. All these methods should normally be sent to the content pane instead of the JFrame itself. The content pane will always be non-null. Attempting to set it to null will cause the JFrame to throw an exception. The default content pane will have a BorderLayout manager set on it. • Unlike a Frame, a JFrame has some notion of how to respond when the user attempts to close the window. The default behavior is to simply hide the JFrame when the user closes the window. To change the default behavior, you invoke the method setDefaultCloseOperation(int). To make the JFrame behave the same as a Frame instance, use setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE).
InternalFrame • Internal frames are not windows or top-level containers, however, which makes them different from frames. For example, you must add an internal frame to a container (usually a JDesktopPane); • an internal frame cannot be the root of a containment hierarchy. Also, internal frames do not generate window events. Instead, the user actions that would cause a frame to fire window events cause an internal frame to fire internal frame events.
JInternalFrame • A lightweight object that provides many of the features of a native frame, including dragging, closing, becoming an icon, resizing, title display, and support for a menu bar. • Generally, you add JInternalFrames to a JDesktopPane. The JInternalFrame content pane is where you add child components. So, to create a JInternalFrame that has a number of buttons arranged with the content pane's default BorderLayout object, you might do something like this: • JComponent c = (JComponent) internalFrame.getContentPane(); c.add(new JButton(), BorderLayout.NORTH); c.add(new JButton(), BorderLayout.CENTER);
JPanel • The JPanel class provides general-purpose containers for lightweight components • Like other containers, a panel uses a layout manager to position and size its components. By default, a panel's layout manager is an instance of FlowLayout, which places the panel's contents in a row. You can easily make a panel use any other layout manager by invoking the setLayout method or by specifying a layout manager when creating the panel. • When you add components to a panel, you use the add method.
JTabbedPane • component that lets the user switch between a group of components by clicking on a tab with a given title and/or icon • Tabs/components are added to a TabbedPane object by using the addTab and insertTab methods. A tab is represented by an index corresponding to the position it was added in, where the first tab has an index equal to 0 and the last tab has an index equal to the tab count minus 1. • The TabbedPane uses a SingleSelectionModel to represent the set of tab indices and the currently selected index. If the tab count is greater than 0, then there will always be a selected index, which by default will be initialized to the first tab. If the tab count is 0, then the selected index will be -1.
FlowLayout • A flow layout arranges components in a left-to-right flow, much like lines of text in a paragraph. Flow layouts are typically used to arrange buttons in a panel. It will arrange buttons left to right until no more buttons fit on the same line. Each line is centered. • Constructor Summary • FlowLayout() Constructs a new FlowLayout with a centered alignment and a default 5-unit horizontal and vertical gap.
FlowLayout(int align) Constructs a new FlowLayout with the specified alignment and a default 5-unit horizontal and vertical gap. • FlowLayout(int align, int hgap, int vgap) Creates a new flow layout manager with the indicated alignment and the indicated horizontal and vertical gaps.
BorderLayout • A border layout lays out a container, arranging and resizing its components to fit in five regions: north, south, east, west, and center. Each region may contain no more than one component, and is identified by a corresponding constant: NORTH, SOUTH, EAST, WEST, and CENTER. When adding a component to a container with a border layout, use one of these five constants, for example: • Panel p = new Panel(); • p.setLayout(new BorderLayout()); • p.add(new Button("Okay"), BorderLayout.SOUTH);
As a convenience, BorderLayout interprets the absence of a string specification the same as the constant CENTER: • For compatibility with previous releases, BorderLayout also includes the relative positioning constants BEFORE_FIRST_LINE, AFTER_LAST_LINE, BEFORE_LINE_BEGINS and AFTER_LINE_ENDS. These are equivalent to PAGE_START, PAGE_END, LINE_START and LINE_END respectively. For consistency with the relative positioning constants used by other components, the latter constants are preferred.
GridLayout • The GridLayout class is a layout manager that lays out a container's components in a rectangular grid. The container is divided into equal-sized rectangles, and one component is placed in each rectangle. • When both the number of rows and the number of columns have been set to non-zero values, either by a constructor or by the setRows and setColumns methods, the number of columns specified is ignored. Instead, the number of columns is determined from the specified number or rows and the total number of components in the layout. So, for example, if three rows and two columns have been specified and nine components are added to the layout, they will be displayed as three rows of three columns. Specifying the number of columns affects the layout only when the number of rows is set to zero.
Icon • Many Swing components, such as labels, buttons, and tabbed panes, can be decorated with an icon — a fixed-sized picture. An icon is an object that adheres to the Icon interface. Swing provides a particularly useful implementation of the Icon interface: ImageIcon, which paints an icon from a GIF, JPEG, or PNG image. • Constructor • ImageIcon icon = new ImageIcon(imageName); • ImageIcon icon = new ImageIcon(imageName, description);
JLabels • In many cases, JLabel is used exactly like Label: as a way to display text. However, since a JLabel can have an image instead of or in addition to the text, it is also frequently used as a way to put an image in a display. • Features: Images, Borders, and HTML Content The first is the ability to display images, usually by supplying an ImageIcon eiher to the constructor or via a call to setIcon. The second new feature is the ability to place borders around the labels.
JButton • Simple uses of JButton are very similar to Button. You create a JButton with a String as a label, and then drop it in a window. Events are normally handled just as with a Button: you attach an ActionListener via the addActionListener method • The most obvious new feature is the ability to associate images with buttons. Swing introduced a utility class called ImageIcon that lets you very easily specify an image file (jpeg or GIF, including animated GIFs). Many Swing controls allow the inclusion of icons. The simplest way to associate an image with a JButton is to pass the ImageIcon to the constructor, either in place of the text or in addition to it. However, a JButton actually allows seven associated images:
the main image (use setIcon to specify it if not supplied in the constructor), • the image to use when the button is pressed (setPressedIcon), • the image to use when the mouse is over it (setRolloverIcon, but you need to call setRolloverEnabled(true) first), • the image to use when the button is selected and enabled (setSelectedIcon), • the image to use when the button is disabled (setDisabledIcon), • the image to use when it is selected but disabled (setDisabledSelectedIcon), and • the image to use when the mouse is over it while it is selected (setRolloverSelectedIcon).
JButton Continued.. • You can also change the alignment of the text or icon in the button (setHorizontalAlignment and setVerticalAlignment; only valid if button is larger than preferred size), and change where the text is relative to the icon (setHorizontalTextPosition, setVerticalTextPosition). • You can also easily set keyboard mnemonics via setMnemonic. This results in the specified character being underlined on the button, and also results in ALT-char activating the button.
Constructor Summary • JButton() Creates a button with no set text or icon supplied. • JButton(Icon icon) Creates a button with an icon. • JButton(String text) Creates a button with text. • JButton(String text, Icon icon) Creates a button with initial text and an icon.
JCheckBox • The JCheckBox class provides support for check box buttons. You can also put check boxes in menus, using the JCheckBoxMenuItem class. Because JCheckBox and JCheckBoxMenuItem inherit from AbstractButton, Swing check boxes have all the usual button characteristics. For example, you can specify images to be used in check boxes. Check boxes are similar to radio buttons but their selection model is different, by convention. Any number of check boxes in a group — none, some, or all — can be selected. A group of radio buttons, on the other hand, can have only one button selected.
JCheckBox Continued… • JCheckBox() Creates an initially unselected check box button with no text, no icon. • JCheckBox(Icon icon) Creates an initially unselected check box with an icon. • JCheckBox(Icon icon, boolean selected) Creates a check box with an icon and specifies whether or not it is initially selected. • JCheckBox(String text) Creates an initially unselected check box with text.
JCheckBox(String text, boolean selected) Creates a check box with text and specifies whether or not it is initially selected. • JCheckBox(String text, Icon icon) Creates an initially unselected check box with the specified text and icon. • JCheckBox(String text, Icon icon, boolean selected) Creates a check box with text and icon, and specifies whether or not it is initially selected.
JComboBox • The actions of the combo box are as follows: • By default, the selected text is displayed in the text field, which acts as the current selection box. • The button to the right of the text field controls the display of the list box, and is used to select a preconfigured list of items. • the combo box has the addition of editing capability in the selection text field, • the ability to display icons along with, or in place of, the text is also available.
When the use combo boxes? Use combo boxes to conserve GUI Space: • Combo boxes are ideal for allowing the user to choose a single item from a long list of options, without consuming a lot of dialog space. • If you are running out of room in a dialog, and you need a UI that allows for either selecting from a list of choices or typing in place, use a combo box. • Consider deploying the scroll bar when the item list reaches ten items, or if you need to display a hierarchy. • The Swing JComboBox will automatically add scroll bars after approximately seven items, but you can change this by setting the preferred size of the instance.
JComboBox Continued.. • Constructor Summary • JComboBox() Creates a JComboBox with a default data model. • JComboBox(ComboBoxModel aModel) Creates a JComboBox that takes it's items from an existing ComboBoxModel. • JComboBox(Object[] items) Creates a JComboBox that contains the elements in the specified array. • JComboBox(Vector items) Creates a JComboBox that contains the elements in the specified Vector.