copyright 2003 mudra services1 swing why was swing/jfc introduced? many complex additional...
Post on 18-Jan-2016
214 Views
Preview:
TRANSCRIPT
Copyright 2003 Mudra Services
1
SWING
Why was SWING/JFC introduced? Many complex additional components like
tables, trees, internal frames, split panes etc Cross-platform A common look and feel across platforms
(Metal) A lightweight framework which does not use the
native peer objects JavaBean compliant. This makes building GUI
applications using an IDE very simple. Borland JBuilder and Symantec VisualCafe are examples of IDEs
Copyright 2003 Mudra Services
2
Model-View-Controller (MVC)
Model Stores the state of the component. For example
in a push button, the state can be ON or OFF View
Visual representation of the model on the screen. This is the LOOK of the component
Controller Event handling for the entire component. This is
the FEEL of the component. In case of a pushbutton, controller detects the button press and informs the model that the state has changed
Copyright 2003 Mudra Services
3
MVC - Diagram
Copyright 2003 Mudra Services
4
MVC - Swing
View can change without changes in model and controller
SWING api provides the ability to completely change the View and Controller parts of the component without changing the model. The Look and Feel (L&F) of the component is changed. SWING supports pluggable look and feel.
Replace the model without replacing the view and controller.
Copyright 2003 Mudra Services
5
MVC - Swing
Every SWING component comes with a default Model, View and Controller
In SWING, the View and the Controller are combined to create a Delegate object. Model-Delegate architecture.
This makes the architecture simple
Copyright 2003 Mudra Services
6
MVC - SWING Extends from Container
Copyright 2003 Mudra Services
7
JComponent
All SWING components inherit from Jcomponent
Responsible for the pluggable look and feel of the components
Responsible for handling keyboard events for each component
Responsible for handling borders around components
Controlling the size of the component Accessibility support for the blind
Copyright 2003 Mudra Services
8
JComponent
Every SWING Component extends from the Container class of AWT (not Component class)
All SWING Components start with the letter ‘J’
Copyright 2003 Mudra Services
9
Windows Look And Feel
Copyright 2003 Mudra Services
10
Metal Look And Feel
Copyright 2003 Mudra Services
11
Motif Look And Feel
Copyright 2003 Mudra Services
12
SWING
How do we create SWING containers and components?
Use SWING component and container constructors
How do we layout the SWING components within a container?
Use layout Managers (same as AWT layout managers)
How does the java code interact with the components?
1.1 AWT Event Model (same as AWT)
Copyright 2003 Mudra Services
13
SWING - Example
package swingexample;
import javax.swing.*;import java.awt.*;
public class SwingExample extends JFrame {
public SwingExample() { this.getContentPane().setLayout(new
FlowLayout(FlowLayout.CENTER));
// create componets JLabel textLabel = new JLabel("Click to submit "); JButton clickButton = new JButton("Submit");
All Components start with ‘J’
Copyright 2003 Mudra Services
14
SWING - Example
// add components to container this.getContentPane().add(textLabel); this.getContentPane().add(clickButton); }
public static void main(String[] s) { SwingExample example = new SwingExample(); example.setTitle("A Sample Frame");
// show the container on the screen example.pack(); example.setVisible(true); }}
Copyright 2003 Mudra Services
15
SWING - Example
Events are generated by event sources just like AWT
Listeners are used in SWING in a similar way as in AWT
Copyright 2003 Mudra Services
16
SWING – Component interaction
package swingexample;import javax.swing.*;import java.awt.*;import java.awt.event.*;
public class SwingExample extends JFrame implements
ActionListener,WindowListener { private JLabel textLabel; private JButton clickButton;
public SwingExample() { this.getContentPane().setLayout(new
FlowLayout(FlowLayout.CENTER));
Copyright 2003 Mudra Services
17
SWING – Component interaction
// create componets textLabel = new JLabel("Click to submit "); clickButton = new JButton("Submit");
// add a listener clickButton.addActionListener(this);
// add components to container this.getContentPane().add(textLabel); this.getContentPane().add(clickButton);
// add a listener to the window this.addWindowListener(this);
}
Copyright 2003 Mudra Services
18
SWING – Component interaction
public static void main(String[] s) { SwingExample example = new SwingExample(); example.setTitle("A Sample Frame");
// show the container on the screen example.pack(); example.setVisible(true); }
Copyright 2003 Mudra Services
19
SWING – Component interaction
public void actionPerformed(ActionEvent e) { if (textLabel.getText().startsWith("Click")) { textLabel.setText("Changed Text"); textLabel.setForeground(Color.blue); } else { textLabel.setText("Click to submit "); textLabel.setForeground(Color.black); } }
public void windowClosing(WindowEvent e) { this.dispose(); this.setVisible(false); System.exit(0); }
Copyright 2003 Mudra Services
20
SWING – Component interaction
// all methods we do not care about public void windowDeactivated(WindowEvent e) {} public void windowActivated(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowClosed(WindowEvent e) {} public void windowOpened(WindowEvent e) {}}
Adapter ClassesUseful when some methods need to be implemented from a set of methods in the listener interface.
Copyright 2003 Mudra Services
21
SWING - Listeners
Listeners are usually implemented as Inner classes
Adapter classes A class which implements a listener interface but
provides null implementations for all the methods Subclasses of adapter usually implement only a few
of the many methods Saves time by not typing all the methods
Anonymous Inner classes A very tiny implementation of a listener
Copyright 2003 Mudra Services
22
SWING – Listeners as Inner classes
class WindowHandler implements WindowListener { public void windowClosing(WindowEvent e) { dispose(); setVisible(false); System.exit(0); }
// all methods we do not care about public void windowDeactivated(WindowEvent e) {} public void windowActivated(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowClosed(WindowEvent e) {} public void windowOpened(WindowEvent e) {} }
Inner class of SwingExample.java
Copyright 2003 Mudra Services
23
SWING - Adapters
Adapters save time WindowAdapter implements
WindowListener but provides null method implementations
class WindowHandler extends WindowAdapter { public void windowClosing(WindowEvent e) { dispose(); setVisible(false); System.exit(0); } }
Notice that other methods are not required here
Copyright 2003 Mudra Services
24
SWING – Anonymous Inner classes
Create the listener object at the place where it is added to the component
// add a listener to the window
this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { dispose(); setVisible(false); System.exit(0); } });
Think of this as a block of codepassed as parameter – which is executed later. Much like functionPointers.
Copyright 2003 Mudra Services
25
SWING - JFrame
Extends from the Frame class (in AWT) Supports swing menubars which can be
moved around JFrame contains only one child object
called JRootPane When a SWING component is to be
added to the JFrame, always use as
frame.getContentPane().add(component);
Copyright 2003 Mudra Services
26
SWING - JPanel
Equivalent to Panel in AWT but does not extend from Panel class
Can be associated with a LayoutManager
Basically contains many SWING components
Do not mix SWING components with the AWT components.
Copyright 2003 Mudra Services
27
SWING - JPanel
JPanel topPanel = new JPanel();topPanel.setLayout(new GridLayout(3,2));topPanel.add(new JButton(“One”));topPanel.add(new JButton(“Two”));topPanel.add(new JButton(“Three”));topPanel.add(new JButton(“Four”));topPanel.add(new JButton(“Five”));topPanel.add(new JButton(“Six”));
Copyright 2003 Mudra Services
28
SWING - Layout
All of the 5 layouts of AWT can be used in SWING applications FlowLayout GridLayout BorderLayout CardLayout GridBagLayout
Copyright 2003 Mudra Services
29
SWING - BoxLayout
BoxLayout New layout in SWING Organizes the components along the X or Y
axis of the owner panel Alignment can be left, right or center
justified Will not wrap components to the next line.
Instead the components will be reduced to their minimum size
Copyright 2003 Mudra Services
30
SWING - BoxLayout
Four checkbox items are being added here in a panel with Boxlayout
Copyright 2003 Mudra Services
31
SWING - BoxLayout
package swingboxexample;
import java.awt.*;import javax.swing.*;
public class SwingboxExample extends JFrame {
public SwingboxExample() {
// BoxLayout panel JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));
Copyright 2003 Mudra Services
32
SWING - BoxLayout
panel.add(new JCheckBox("Pattern match")); panel.add(new JCheckBox("Search whole worlds only")); panel.add(new JCheckBox("Case sensitive")); panel.add(new JCheckBox("Search only selected text"));
this.getContentPane().add(panel); }
public static void main(String[] args) { SwingboxExample swingboxExample = new SwingboxExample();
swingboxExample.pack(); swingboxExample.setVisible(true); }}
Copyright 2003 Mudra Services
33
SWING - BoxLayout
Box A JPanel with BoxLayout
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));
Can be replaced by
Box panel = new Box(BoxLayout.Y_AXIS);
Copyright 2003 Mudra Services
34
SWING - Borders
Can be applied to any SWING component In most cases, a border is added to a JPanel object Border types
BevelBorder – 3D border supports raised/lowered look EmptyBorder – reserves space around the component EtchedBorder – etched line look LineBorder – line border of arbitrary thickness MatteBorder – tiling of specified icon or color TitledBorder – with a title CompoundBorder – nested border
Copyright 2003 Mudra Services
35
SWING - Border
Add the following line to BoxLayout example panel.setBorder(new BevelBorder(BevelBorder.LOWERED));
Copyright 2003 Mudra Services
36
SWING - Border
Instead of creating a border object every time, it is convenient and efficient to use a border factory object Reduces number of Border objects created
UseBorder bevel =
BorderFactory.createLoweredbevelBorder();
Instead of Border bevel = new BevelBorder(BevelBorder.LOWERED));
Copyright 2003 Mudra Services
37
SWING - CompoundBorder
Multiple borders can be applied to the same component
Useful when creating border with white space around the component
Again, use the BorderFactory to create a compound object instead of the constructor
Copyright 2003 Mudra Services
38
SWING - CompoundBorder
Add the following code to the BoxLayout examplepanel.setBorder(BorderFactory.createCompoundBorder
(BorderFactory.createLoweredBevelBorder() ,BorderFactory.createEmptyBorder(20,20,20,20)));
Outer
Inner
Copyright 2003 Mudra Services
39
SWING - JLabel
Can contain an image as well as text Font and colors of the text can be controlled Text and image can be aligned Image can be disabled (a gray filter is used
on the image dynamically) Constructors
JLabel label = new JLabel(“label1”);JLabel label = new
JLabel(“label1”,image,SwingConstants.CENTER);[where Icon image = new ImageIcon(“image1.gif”);]
Copyright 2003 Mudra Services
40
SWING - JLabel
Setting Fonts and Colorslabel.setFont(new Font(“Dialog”,Font.PLAIN,12));label.setBackground(Color.blue);
Setting Text Alignmentlabel.setHorizontalAlignment(SwingConstants.RIGHT)label.setVerticalAlignment(SwingConstants.TOP)
Disabling the iconlabel.setDisabledIcon(imageIcon);
Copyright 2003 Mudra Services
41
SWING - Buttons
Copyright 2003 Mudra Services
42
SWING - AbstractButton
All operations which are common to JButton, JToggleButton, JCheckBox, JRadioBox are included here.
Use ActionListener to handle events from a Button
button.addActionListener(listener); Enable or Disable buttons
button.setEnabled(false); Set Mnemonic
button.setMnemonic(‘R’); // Use ALT R to operate
Copyright 2003 Mudra Services
43
SWING - JButton
Represents a Push Button Important Constructors
JButton(Icon icon) JButton(String text) JButton(String text,Icon image)
Copyright 2003 Mudra Services
44
SWING - JButton
Add the following code clickButton = new JButton("Submit",new
ImageIcon("AppletIcon.gif")); clickButton.setMnemonic('S');
Copyright 2003 Mudra Services
45
SWING - JToggleButton
Operation is a toggle operation State is toggled It is parent for JCheckBox and JRadioBox.
Both these buttons also exhibit toggling behavior
Important Constructors JToggleButton(Icon icon) JToggleButton(Icon icon,boolean selected) JToggleButton(String txt,Icon icon,boolean selected)
Copyright 2003 Mudra Services
46
SWING - JToggleButton
Create ButtonGroups. Used to group multiple toggle buttons together. When a new button is pressed, all other buttons in the same group are untoggled.
ButtonGroup group = new ButtonGroup(); group.add(button1); group.add(button2); group.add(button3);
Copyright 2003 Mudra Services
47
SWING - JCheckBox
Represents a check box control Use check boxes to apply multiple
simultaneous states Important Constructors
JCheckBox(Icon icon) JCheckBox(String text) JCheckBox(String text,boolean selected) JCheckBox(Icon icon,boolean selected) JCheckBox(String txt,Icon icon,boolean selected)
Copyright 2003 Mudra Services
48
SWING - JRadioButton
Represents a radio button control Always used with a ButtonGroup Use the radio boxes to apply mutually
exclusive states Important Constructors
JRadioButton(Icon icon) JRadioButton(String text) JRadioButton(String text,boolean selected) JRadioButton(Icon icon,boolean selected) JRadioButton(String txt,Icon icon,boolean selected)
Copyright 2003 Mudra Services
49
SWING – Button Example
Copyright 2003 Mudra Services
50
SWING – Button Example
package swingbutton;
import java.awt.*;import javax.swing.*;import javax.swing.border.*;
public class SwingButton extends JFrame {
public SwingButton() {
// main panel JPanel mainPanel = new JPanel(); mainPanel.setLayout(new
BoxLayout(mainPanel,BoxLayout.Y_AXIS));
Copyright 2003 Mudra Services
51
SWING – Button Example
// checkbox panel JPanel checkPanel = new JPanel(); checkPanel.setLayout(new
BoxLayout(checkPanel,BoxLayout.Y_AXIS)); checkPanel.setBorder(BorderFactory.createTitledBorder("Find"));
// add all checkboxes to the checkpox panel checkPanel.add(new JCheckBox("Pattern match")); checkPanel.add(new JCheckBox("Search whole worlds only")); checkPanel.add(new JCheckBox("Case sensitive")); checkPanel.add(new JCheckBox("Search only selected text"));
Createcheckpanel
Copyright 2003 Mudra Services
52
SWING – Button Example
// create radio box panel JPanel radioPanel = new JPanel(); radioPanel.setLayout(new BoxLayout(radioPanel,BoxLayout.Y_AXIS)); radioPanel.setBorder(BorderFactory.createTitledBorder("Sex"));
JRadioButton maleB = new JRadioButton("Male"); JRadioButton femaleB = new JRadioButton("Female"); femaleB.setSelected(true); radioPanel.add(maleB); radioPanel.add(femaleB);
// create a button group for radio buttons ButtonGroup group = new ButtonGroup(); group.add(maleB); group.add(femaleB);
Createradiopanel
Copyright 2003 Mudra Services
53
SWING – Button Example
// add to main panel mainPanel.add(checkPanel); mainPanel.add(radioPanel);
// add to JFrame content pane this.getContentPane().add(mainPanel); }
public static void main(String[] args) { SwingButton swingButton = new SwingButton();
swingButton.pack(); swingButton.setVisible(true); }}
Copyright 2003 Mudra Services
54
SWING - JTextComponent
AWT text support was limited JTextComponent contains all
knowledge and algorithms related to a text editor
Copyright 2003 Mudra Services
55
SWING - JTextComponent
Supports clipboard operations Interacts with the OS to interface with the
clipboard Cut,copy paste
Can save and load a file Contains all code for
text selection background colors selection color Read/Write to a stream
Copyright 2003 Mudra Services
56
SWING - JTextField
Only a single line of text Supports Unicode character set Can add a mnemonic to a field Important constructors
JTextField() JTextField(String text) JTextField(int columns)
Methods String text = field.getText()
Copyright 2003 Mudra Services
57
SWING - JPasswordField
Extends from JTextField Similar to JTextField but does not echo
the characters on the field (instead displays a *)
Can set the display character passwordField.setEchoChar(‘$’);
Copyright 2003 Mudra Services
58
SWING - JTextArea
Accepts more than one line of text Important constructor
JTextArea() JTextArea(String text) JTextArea(int rows,int cols)
Methods void append(text) Void replaceRange(String txt,int start,int end)
Copyright 2003 Mudra Services
59
SWING – Text Example
Copyright 2003 Mudra Services
60
SWING – Text Example
package textexample;
import java.awt.*;import javax.swing.*;
public class TextExample extends JFrame {
public TextExample() { JPanel northPanel = new JPanel(); northPanel.setLayout(new GridLayout(2,2));
Copyright 2003 Mudra Services
61
SWING – Text Example
// name label and field. create a mnemonic JLabel name = new JLabel("Name"); JTextField nameF = new JTextField(); name.setLabelFor(nameF); name.setDisplayedMnemonic('N'); nameF.setFocusAccelerator('N');
// name label and field. create a mnemonic JLabel addr = new JLabel("Address"); JTextField addrF = new JTextField(); addr.setLabelFor(addrF); addr.setDisplayedMnemonic('A'); addrF.setFocusAccelerator('A');
ALT-N will move thefocus to the name field
ALT-A will move thefocus to the addressfield
Copyright 2003 Mudra Services
62
SWING – Text Example
northPanel.add(name);
northPanel.add(nameF); northPanel.add(addr); northPanel.add(addrF);
JPanel centerPanel = new JPanel(); centerPanel.setLayout(new BorderLayout()); centerPanel.add("Center",new JTextArea(20,20));
getContentPane().add("North",northPanel); getContentPane().add("Center",centerPanel); }
Copyright 2003 Mudra Services
63
SWING – Text Example
public static void main(String[] args) { TextExample textExample = new TextExample(); textExample.pack(); textExample.setVisible(true); }
} // End
Copyright 2003 Mudra Services
64
SWING - Exercise
Create a JFrame as shown in the next page. Figure out the layout Manager for the different
panels in the User Interface. Associate mnemonics and accelerators to the
swing components as indicated in the interface. Notice that all the buttons are the same size. Use
setMinimumSize() and setMaximumSize() to set the size of the button.
Notice the defaults in the interface What listener will you implement to act on the
button clicks? How will you differentiate between the different button clicks?
Copyright 2003 Mudra Services
65
SWING - Exercise
Copyright 2003 Mudra Services
66
SWING - JComboBox
A superset of AWT’s Choice class When an item is selected, an ItemEvent
is sent to all the ItemListeners registered for the event
Can be editable Important constructors
JComboBox() JComboBox(ComboBoxModel model)
Copyright 2003 Mudra Services
67
SWING - JComboBox
Adding item to a combo box combo.addItem(“item”);
Removing an item from a combo box combo.removeItem(“item”); combo.removeItemAt(3); combo.removeAllItems();
Selecting items combo.setSelectedItem(“item”); combo.setSelectedIndex(3); int index = combo.getSelectedIndex() String item = (String)combo.getSelectedItem()
Copyright 2003 Mudra Services
68
SWING - JComboBox
Enable editing combo.setEditable(true)
Copyright 2003 Mudra Services
69
SWING - JProgressBar
Issues with a Time consuming task Useful when a time consuming task
requires a user to wait It indicates the progress that the task is
making It lets the user know that the program
has not frozen or stopped Important constructors
JProgressBar()
Copyright 2003 Mudra Services
70
SWING - JProgressBar
Methods int getValue() int getMinimum() int getMaximum() void setValue(int i)
Changes in progress bar is generated as ChangeEvent
Copyright 2003 Mudra Services
71
SWING - Example
Example of the screen in the middle of the run
Copyright 2003 Mudra Services
72
SWING - Example
package progressexample;
import java.awt.*;import javax.swing.*;import javax.swing.border.*;import java.awt.event.*;
public class ProgressExample extends JFrame implements ActionListener {
private JLabel label = new JLabel("Progress"); private JButton button = new JButton("Start"); private JProgressBar pbar = null;
Copyright 2003 Mudra Services
73
SWING - Example
public ProgressExample() {
// create panel with box layout and border JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS)); panel.setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
panel.add(label);
// add progress bar to panel pbar = new JProgressBar(); pbar.setMinimum(0); pbar.setMaximum(20); panel.add(pbar);
Copyright 2003 Mudra Services
74
SWING - Example
button.addActionListener(this); panel.add(button);
getContentPane().add(panel); }
public static void main(String[] args) { ProgressExample progressExample = new ProgressExample();
progressExample.pack(); progressExample.setVisible(true); }
Copyright 2003 Mudra Services
75
SWING - Example
public void actionPerformed(ActionEvent e) { for (int j=0;j<20;j++) { // sleep for 1 sec try { Thread.sleep(1000); } catch(Exception exp) {}
// set the value of the progress bar and refresh immediately pbar.setValue(j+1); pbar.paintImmediately(new Rectangle(getWidth(),getHeight())); } }}
Simulating a time consuming task. Breakinto iterations.
Note that the user is not able to do anything else
Copyright 2003 Mudra Services
76
SWING - JSlider
Can be used to select from a range of values
When changing the values, it generates ChangeEvent.
Copyright 2003 Mudra Services
77
SWING - JSlider
Important constructors JSlider() JSlider(int orientation,int value,int min,int max)
Methods int getValue() void setValue(int value) int getMinimum() int getMaximum()
Copyright 2003 Mudra Services
78
SWING – JMenuBar,JMenu,JMenuItem
Menu at the top which provides all the functionality of the application
JMenuBar consructor JMenuBar()
JMenuBar methods JMenu add(JMenu menu)
Copyright 2003 Mudra Services
79
SWING – JMenuBar,JMenu,JMenuItem
Output of the code
Copyright 2003 Mudra Services
80
SWING – JMenuBar,JMenu,JMenuItem
package menuexample;
import java.awt.*;import javax.swing.*;
public class MenuExample extends JFrame {
public MenuExample() {
// create the menu bar JMenuBar menub = new JMenuBar();
Copyright 2003 Mudra Services
81
SWING – JMenuBar,JMenu,JMenuItem
// create the file menu JMenu fileMenu = new JMenu("File"); fileMenu.add(new JMenuItem("Open")); fileMenu.add(new JMenuItem("New")); fileMenu.add(new JSeparator()); fileMenu.add(new JMenuItem("Save")); fileMenu.add(new JMenuItem("Save As")); fileMenu.add(new JMenuItem("Exit"));
// create the edit menu JMenu editMenu = new JMenu("Edit"); editMenu.add(new JMenuItem("Delete")); editMenu.add(new JMenuItem("Copy"));
Copyright 2003 Mudra Services
82
SWING – JMenuBar,JMenu,JMenuItem
// create the tools menu JMenu toolsMenu = new JMenu("Tools"); toolsMenu.add(new JMenuItem("Generate Documentation")); toolsMenu.add(new JMenuItem("Generate Code"));
// create the help menu JMenu helpMenu = new JMenu("Help"); helpMenu.add(new JMenuItem("Help Documentation")); helpMenu.add(new JMenuItem("About ..."));
// add menus to the menu bar menub.add(fileMenu); menub.add(editMenu); menub.add(toolsMenu); menub.add(helpMenu);
Copyright 2003 Mudra Services
83
SWING – JMenuBar,JMenu,JMenuItem
// set the menubar setJMenuBar(menub); }
public static void main(String[] args) { MenuExample menuExample = new MenuExample();
menuExample.setSize(200,200); menuExample.setVisible(true); }}
Copyright 2003 Mudra Services
84
SWING – JMenuBar,JMenu,JMenuItem
Menu Selection can be observed by adding action listener to the menu item
menuitem.addActionListener(this);
Set a tooltip for a menu item menuItem.setToolTipText(text);
Add a image to the menu item menuItem.setIcon(image); JMenuItem(String text,Icon image)
Copyright 2003 Mudra Services
85
SWING – JMenuBar,JMenu,JMenuItem
Add a accelerator key to the menu item menuItem.setMnemonic(‘F’);
JCheckboxMenuItem Offers model operation from the menu JCheckBoxMenuItem(String text) JCheckBoxMenuItem(String text,Icon icon) menuitem.setState(false)
Copyright 2003 Mudra Services
86
SWING – JMenuBar,JMenu,JMenuItem
JRadioButtonMenuItem Implement radio buttons from inside the
menu Use button groups to group multiple radio
button menu items JRadioButtonMenuItem(String text) JRadioButtonMenuItem(String text,Icon icon)
Copyright 2003 Mudra Services
87
SWING - JPopupMenu
Context sensitive options for a given task
Pops up all the items on Right click (in windows)
Add JMenuItem objects to the Popup menu
Constructor JPopupMenu()
Copyright 2003 Mudra Services
88
SWING - JPopupMenu
Copyright 2003 Mudra Services
89
SWING - JPopupMenu
package popupexample;import java.awt.*;import javax.swing.*;import java.awt.event.*;public class PopupExample extends JFrame {
private JPopupMenu popup = new JPopupMenu();
public class MouseHandler extends MouseAdapter { public void mouseReleased(MouseEvent e) { if (e.isPopupTrigger()) { popup.show(e.getComponent(),e.getX(),e.getY()); } } }
Copyright 2003 Mudra Services
90
SWING - JPopupMenu
public PopupExample() { setSize(300,300);
// add items to the popup JMenuItem openItem = new JMenuItem("Open"); JMenuItem saveItem = new JMenuItem("Save"); JMenuItem saveasItem = new JMenuItem("Save As"); JMenuItem closeItem = new JMenuItem("Close");
// add to popup menu popup.add(openItem); popup.add(saveItem); popup.add(saveasItem); popup.add(closeItem);
Copyright 2003 Mudra Services
91
SWING - JPopupMenu
getContentPane().add("Center",new JPanel()); getContentPane().addMouseListener(new
MouseHandler()); }
public static void main(String[] args) { PopupExample popupExample = new PopupExample();
// show popupExample.setVisible(true); }
}
Copyright 2003 Mudra Services
92
SWING - JToolBar
Most common features of the application are usually in the toolbar
Significantly improves the user interface No toolbar in AWT Tooltips for each item in the toolbar Dock and undock a toolbar Constructors
JToolBar()
Copyright 2003 Mudra Services
93
SWING - JToolBar
Method add(Component comp) addSeparator() setFloatable(false)
Copyright 2003 Mudra Services
94
SWING - JToolBar
Copyright 2003 Mudra Services
95
SWING - JToolBar
JToolBar tool = new JToolBar();
tool.add(new JButton(new ImageIcon("open.gif"))); tool.add(new JButton(new ImageIcon("save.gif"))); tool.add(new JButton(new ImageIcon("saveall.gif"))); tool.addSeparator(); tool.add(new JButton(new ImageIcon("zoom.gif"))); tool.add(new JButton(new ImageIcon("zoomin.gif"))); tool.add(new JButton(new ImageIcon("zoomout.gif")));
getContentPane().add("North",tool);
Copyright 2003 Mudra Services
96
SWING - Exercise Create a JFrame which changes a color as shown below.
Copyright 2003 Mudra Services
97
SWING – Exercise
Each of the sliders associated with the red, blue and green color has a minimum value of 0 and maximum value of 255
As the user changes the slider value, the actual value must be displayed on the text label on the right of the slider
Provide implementation for “Apply” and “Cancel” which just closes the Jframe.
top related