SlideShare a Scribd company logo
Topic 10: Swing User Interface Components
Chapter 9
Advanced Programming Techniques
Objective and Outline
• Objective:
– What else do you need to know in order to create a
full-featured GUI?
• Outline:
– Overview of Swing components
– Layout management
– Using Swing components
• Text input, Buttons, ComboBox, Menus, Dialogs
Overview of Swing Components
http://java.sun.com/docs/books/tutorial/uiswing/components/components.html
Top-Level Containers
 Windows: JFrame class
 Dialog boxes: JOptionPane,JDialog *,
JFileChooser classes
 Applets: JApplet * class
v2: covered in volume 2, *: will discuss
Overview of Swing Components
General-Purpose containers for laying out components.
 JPanel class
 JScrollPane * class provides a
scrollable view of components.
 JSplitPane v2 displays two groups of
components, either side by side or
one on top of the other.
Overview of Swing Components
Basic control: Components for getting user input
 Textfields: JTextField *,
JPasswordField *, JTextArea *
 Buttons: JButton *, JCheckBox *,
JRadioButton *, …

Overview of Swing Components
Basic control: Components for getting user input
 JMenu *, JMenuItem *
 JSlider v2, JScrollbar
 JComboBox *
 JSpinner
Overview of Swing Components
non-editable components for information display
 Jlabel * class can display
non-selectable text and images.
 JProgressBar v2 class displays
progress of a job.
 Tool Tips v2: created using JComponent
Overview of Swing Components
Editable components for information display
 JTable v2 class can display and edit
tables of data,
 Texts *:
 JTree v2 class can display
hierarchical data
 File Chooser
 JColorChooser class to provide users
with a palette of colors to choose from.
Overview of Swing Components
Summary:
Containers
Top-Level: JFrame, JOptinePane, JDialog, JFileChooser,JApplet,
General-purpose: JPanel, JScrollPane, JSplitPane
User input
JTextField, JPasswordField, JTextArea, JButton, JCheckbox,
JRadioButton, Jlist, JComboBox, JMenu, JMenuItem, JSlider,
JScrollBar
Information display
Non-editable: Jlabel, JProgressBar, Tool tips
Editable: Jtable, Texts, Jtree, JColorChooser
Outline
Outline:
Overview of Swing components
Layout management
Using Swing components
– Text input, Buttons, ComboBox, Menus, Dialogs
Layout Management
Layout management determines the size and
position of components.
Each container has a default layout manager.
Can be changed using the method: setLayout
Generally, need to set the layout manager of two
types of containers:
content panes (which use BorderLayout by
default) and
JPanels (which use FlowLayout by default).
• Types of Layout
– FlowLayout
– BorderLayout
– GridLayout
– BoxLayout
– GridBagLayout
Layout Management
Layout Management
• Component size
– Default/natural minimum/preferred sizes
calculated by the LayoutManager interface, which
is implemented by all layout management classes
• Dimension minimumLayoutSize(Container parent)
• Dimension preferredLayoutSize(Container parent)
– Can be changed using methods of JComponent
• voidsetMaximumSize(Dimension maximumSize)
• voidsetMinimumSize(Dimension minimumSize)
• voidsetPreferredSize(Dimension preferredSize)
Flow Layout
FlowLayout class
FlowLayout arranges components in a left-to-right flow, much like
lines of text in a paragraph.
Components sized at their preferred size.
If the horizontal space in the container is too small,
FlowLayout uses multiple rows.
Within each row, components are centered (the default), left-
aligned, or right-aligned as specified when the FlowLayout is
created.
Default layout manager of JPanel : typically used to arrange buttons
in a panel
Example: FlowWindow.java
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
contentPane.add(new JButton("Button 1"));
contentPane.add(new JButton("2"));
contentPane.add(new JButton("Button 3"));
contentPane.add(new JButton("Long-Named Button 4"));
contentPane.add(new JButton("Button 5"));
Flow Layout
FlowLayout class constructors:
FlowLayout( int align, int hgap, int
vgap)
1. align: FlowLayout.LEFT,
FlowLayout.CENTER, FlowLayout.RIGHT
2. hgap: horizontal gap in pixels between components
3. vgap: vertical gap in pixels between components
FlowLayout( int align)
FlowLayout( )
Flow Layout
Border Layout
• BorderLayout:
– Has five areas
• Specify area for a component using one of the constants: NORTH, SOUTH,
EAST, WEST, and CENTER.
– Size of components determined by
• Their preferred sizes and the constraints of the container's size.
• The NORTH and SOUTH components may be stretched horizontally; the
EAST and WEST components may be stretched vertically; the CENTER
component may stretch both horizontally and vertically to fill any space
left over.
– Default for contentPane
Container contentPane = getContentPane();
//Use the content pane's default BorderLayout.
//contentPane.setLayout(new BorderLayout());
unnecessary
contentPane.add(new JButton("Button 1 (NORTH)"),
BorderLayout.NORTH);
contentPane.add(new JButton("2 (CENTER)"),
BorderLayout.CENTER);
contentPane.add(new JButton("Button 3 (WEST)"),
BorderLayout.WEST);
contentPane.add(new JButton("Long-Named Button 4
(SOUTH)"),BorderLayout.SOUTH);
contentPane.add(new JButton("Button 5 (EAST)"),
BorderLayout.EAST);
// BorderWindow.java
BorderLayout class constructors:
BorderLayout( int hgap, int vgap)
1. hgap: horizontal gap in pixels between
components
2. vgap: vertical gap in pixels between components
BorderLayout( )
Border Layout
Grid Layout
GridLayout: places components in a grid of cells.
Each component takes all the available space within
its cell. Each cell is exactly the same size.
Number of columns ignored when number of rows
set to non-zero
Example:
Container contentPane = getContentPane();
contentPane.setLayout(new GridLayout(0,2));
//construct an instance of GridLayout that has two
// columns and as many rows as necessary.
contentPane.add(new JButton("Button 1"));
contentPane.add(new JButton("2"));
contentPane.add(new JButton("Button 3"));
contentPane.add(new JButton("Long-Named Button 4"));
contentPane.add(new JButton("Button 5"));
// GridWindow.java
GridLayout class constructors:
GridLayout(int rows, int columns,
int hgap, int vgap)
1. hgap: horizontal gap in pixels between
components
2. vgap: vertical gap in pixels between components
GridLayout(int rows, int columns )
Grid Layout
Box Layout
• BoxLayout: places components in a single row or column
– Attempt to arrange components at their preferred widths (for
horizontal layout) or heights (for vertical layout).
• For a horizontal layout, if not all the components are the same height,
BoxLayout attempts to make all the components as high as the highest
component.
• For a vertical layout, BoxLayout attempts to make all components in the
column as wide as the widest component. If that fails, it aligns them
horizontally according to their X alignments.
Box Layout
• Instead of using BoxLayout directly, many programs use the
Box class.
• The Box class is a lightweight container that uses a BoxLayout.
• It also provides handy methods to help you use BoxLayout
well.
• Adding components to multiple nested boxes is a powerful
way to get the arrangement you want.
Box class methods: all static
Factory methods:
createHorizontalBox(),
createVerticalBox()
If all the components your Box contains have a fixed size, you
might want to use a glue component to control the components'
positions.
createHorizontalGlue(),
createVerticalGlue,
createGlue():
//push components as far away as possible
Box Layout
For a fixed amount of space between two components,
try using a strut & rigid area
createHorizontalStrut(int),
createVecticalStrut(int)
createRigidArea( Dimension )
//BoxLayoutTest.java
Box Layout
// construct the top horizontal box
JLabel label1 = new JLabel("Name:");
JTextField textField1 = new JTextField(10);
textField1.setMaximumSize(textField1.getPreferredSize());
Box hbox1 = Box.createHorizontalBox();
hbox1.add(label1);
// separate with a 10-pixel strut
hbox1.add(Box.createHorizontalStrut(10));
hbox1.add(textField1);
// construct the middle horizontal box
JLabel label2 = new JLabel("Password:");
JTextField textField2 = new JTextField(10);
textField2.setMaximumSize(textField2.getPreferredSize());
Box hbox2 = Box.createHorizontalBox();
hbox2.add(label2);
// separate with a 10-pixel strut
hbox2.add(Box.createHorizontalStrut(10));
hbox2.add(textField2);
// construct the bottom horizontal box
JButton button1 = new JButton("Ok");
JButton button2 = new JButton("Cancel");
Box hbox3 = Box.createHorizontalBox();
hbox3.add(button1);
// use "glue" to push the two buttons apart
hbox3.add(Box.createGlue());
hbox3.add(button2);
// add the three horizontal boxes inside a vertical box
Box vbox = Box.createVerticalBox();
vbox.add(hbox1);
vbox.add(hbox2);
vbox.add(Box.createGlue());
vbox.add(hbox3);
Container contentPane = getContentPane();
contentPane.add(vbox, BorderLayout.CENTER);
GridBag Layout
GridBagLayout:
The most sophisticated, flexible layout manager the Java platform
provides.
It aligns components by placing them within a grid of cells, allowing
some components to span more than one cell.
The rows in the grid aren't necessarily all the same height;
similarly, grid columns can have different widths.
Layout Management
Hierarchy of containers for achieving better layout:
Containers inside other containers
Each has a potentially a different layout manager
Allows you to create sophisticated layout with simple
layout managers
//CombineTest.java
// create vertical box
Box b = Box.createVerticalBox();
// create top panel (FlowLayout)
JPanel p1 = new JPanel();
p1.add( new JButton("Button 1"));
p1.add( new JButton("2"));
p1.add( new JButton("Button 3"));
b.add(p1);
// create Scrollable text area
JTextArea t = new JTextArea(200, 50);
JScrollPane sp = new JScrollPane( t );
b.add(sp);
// create bottom panel (right-aligned FlowLayout)
JPanel p2 = new JPanel();
p2.setLayout( new FlowLayout( FlowLayout.RIGHT ));
p2.add( new JButton("OK"));
b.add( p2 );
Container cp = getContentPane();
cp.add( b ); //CombineTest.java
Borders for Components
JComponents can have borders
Create Border objects using static methods of
BorderFactory class:
createLineBorder, createMatteBorder,
createEmptyBorder createEtchedBorder, ….
Set border using the setBorder method of Jcomponent
Example: BorderTest.java
This example also demonstrate the use of
JRadioButton, which will be discussed later
public BorderFrame()
{
setTitle("BorderTest");
setSize(WIDTH, HEIGHT);
demoPanel = new JPanel();
buttonPanel = new JPanel();
group = new ButtonGroup();
addRadioButton("Lowered bevel",
BorderFactory.createLoweredBevelBorder());
addRadioButton("Raised bevel",
BorderFactory.createRaisedBevelBorder());
addRadioButton("Etched",
BorderFactory.createEtchedBorder());
addRadioButton("Line",
BorderFactory.createLineBorder(Color.blue));
addRadioButton("Matte",
BorderFactory.createMatteBorder(
10, 10, 10, 10, Color.blue));
addRadioButton("Empty",
BorderFactory.createEmptyBorder());
Border etched =
BorderFactory.createEtchedBorder();
Border titled = BorderFactory.createTitledBorder
(etched, "Border types");
buttonPanel.setBorder(titled);
Container contentPane = getContentPane();
contentPane.setLayout(new GridLayout(2, 1));
contentPane.add(buttonPanel);
contentPane.add(demoPanel);
}
public void addRadioButton(String buttonName, final Border b)
{
JRadioButton button = new JRadioButton(buttonName);
button.addActionListener(new
ActionListener()
{
public void actionPerformed(ActionEvent event)
{
demoPanel.setBorder(b);
validate();
}
});
group.add(button);
buttonPanel.add(button);
}
Outline
Outline:
Overview of Swing components
Layout management
Using Swing components
– Text input, Buttons, ComboBox, Menus, Dialogs
Text Input
JTextField, JPasswordField: one line.
JTextArea: A multi-line area that displays plain
text.
JEditorPane: A text component to edit various kinds
of content, plain text, html, rtf.
Can be monitored using either CaretListener or
DocumentListener
Check Documentation of JTextComponent
• JTextField also produces ActionEvent
when ”return” is pressed.
• Let’s make use of this to write a program:
Text1.java.
• Next, show how to make it better using
DocumentListener (Text.java)
Text Input
Model-View-Controller Design Pattern
Separates a software component into three distinct
pieces: a model, a view, and a controller.
Model-View-Controller Design Pattern
• Model
– represents the state and low-level behavior of the component.
– manages the state and conducts all transformations on that state.
– system itself maintains links between model and views and notifies
the views when the model changes state.
– Example: ButtonModel
• Query internal state
• Manipulate internal state
• Add and remove event listeners
• Fire events
Model-View-Controller Design Pattern
• view:
– manages the visual display of the state represented by the model.
• controller
– manages user interaction with the model. It provides the mechanism
by which changes are made to the state of the model.
• Example: ButtonUI
– Paint
– Return geometric information
– Handle AWT events
Model-View-Controller Design Pattern
• The component class JButton acts as the glue, or scaffolding, that holds the MVC
triad together
• Programmers do not typically work with model and view/controller classes
directly
• Example about what you can do using MVC:
http://www.developer.com/java/ent/article.php/3336761
Text Input
Model for all text components, including TextField, JPasswordField,
JTextArea are described by Document Interface.
Text component generates DocumentEvents when its content is changed.
To listen to such events, register a DocumentListener with the text
component
textComponent.getDocument()
.addDocumentListener(listener);
Check Documentation of JTextComponent
Text Input
The DocumentListener has three methods
void insertUpdate(DocumentEvent e)
void removeUpdate(DocumentEvent e)
void changeUpdate(DocumentEvent e)
// Gives notification that an attribute or set of attributes
changed.
No adapter class.
class TextTestFrame extends JFrame
{ public TextTestFrame()
{ setTitle("TextTest");
setSize(WIDTH, HEIGHT);
Container contentPane = getContentPane();
DocumentListener listener =
new ClockFieldListener();
// add a panel with text fields
JPanel panel = new JPanel();
hourField = new JTextField("12", 3);
panel.add(hourField);
hourField.getDocument().addDocumentListener(listener);
minuteField = new JTextField("00", 3);
panel.add(minuteField);
minuteField.getDocument().addDocumentListener(listener);
contentPane.add(panel, BorderLayout.SOUTH);
// add the clock
clock = new ClockPanel();
contentPane.add(clock, BorderLayout.CENTER);
} //TextTest.java.
Text Input/JTextField
private class ClockFieldListener implements
DocumentListener
{
public void insertUpdate(DocumentEvent e)
{ setClock(); }
public void removeUpdate(DocumentEvent e)
{ setClock(); }
public void changedUpdate(DocumentEvent e) {}
}
}
Text Input/JTextField
class TextTestFrame extends JFrame
{ public TextTestFrame()
{ …}
public void setClock() // retrieving from both fields
{ int hours =
Integer.parseInt(hourField.getText().trim());
int minutes =
Integer.parseInt(minuteField.getText().trim());
clock.setTime(hours, minutes);
}
……
}
Will change clock without pressing “Return”
• Exercise:
– Re-write Text.java using CaretListener
Text Input/JTextField
Outline
Outline:
Overview of Swing components
Layout management
Using Swing components
– Text input, Buttons, ComboBox, Menus, Dialogs
Buttons
All button classes descend from AbstractButton
JButton: A common button.
JCheckBox: For “yes” or “no” input.
JRadioButton: For exclusive choices among a
group. If one button is pushed, all other buttons in the
group depressed.
JCheckBox
Use a check box to collect yes/no input. The user checks/ the box by
clicking inside it and turns off the check mark by clinking it again.
Check boxes need a label next to them to identify their purpose.
Bold = new JCheckBox(“Bold”);
Use the setSelected method to turn a check box on or off
Bold.setSelected(true);
The isSelected method then retrieves the current state of each check
box. It is false if unchecked; true if checked.
When the user clicks on a check box, an action event is triggered. As
always, you attach an action listener.
ActionListener listener = …
Bold.addActionListener(listener)
class CheckBoxFrame extends JFrame
{ public CheckBoxFrame()
{ ……
ActionListener listener = new ActionListener()
{ public void actionPerformed(Actionevent event)
{ int mode = 0;
if (bold.isSelected()) mode +=Font.BOLD;
if (italic.isSelected()) mode +=Font.ITALIC;
label.setFont(new Font(“Serif”, mode, FONTSIZE));
}
}
JPanel buttonPanel = new JPanel();
bold = new JCheckBox( "Bold");
bold.addActionListener(listener);
buttonPanel.add(bold);
italic = new JCheckBox("Italic");
italic.addActionListener(listener);
buttonPanel.add(italic);
getContentPane().add(buttonPanel, BorderLayout.South);
…} // CheckBoxTest.java
Buttons/Radio Buttons
Radio buttons group are groups of buttons in which
only one button at a time can be selected.
The Swing release supports radio buttons with the
JRadioButton and ButtonGroup classes
Example: Choosing pets
(RadioButtonDemo.java)
// Create the radio buttons.
JRadioButton birdButton = new JRadioButton(birdString);
birdButton.setMnemonic('b'); // Enable ALT+b
// this is to be used together with getActionCommand
birdButton.setActionCommand(birdString);
birdButton.setSelected(true); // birButton selected
JRadioButton catButton = new JRadioButton(catString);
catButton.setMnemonic('c');
catButton.setActionCommand(catString);
// Note catButton not selected
// dogButton, RabbitButton, PigButton
// Group the radio buttons.
ButtonGroup group = new ButtonGroup();
group.add(birdButton);
group.add(catButton);
group.add(dogButton);
group.add(rabbitButton);
group.add(pigButton);
// now one of those buttons can be selected
// Register a listener for the radio buttons.
RadioListener myListener = new RadioListener();
birdButton.addActionListener(myListener);
catButton.addActionListener(myListener);
...
class RadioListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
picture.setIcon(new ImageIcon("images/“
+ e.getActionCommand()
+ ".gif"));
}
Get this string set by
setActionCommand
images/cat.gif
images/bird.gif
…
Outline
Outline:
Overview of Swing components
Layout management
Using Swing components
– Text input, Buttons, ComboBox, Menus, Dialogs
JComboBox
A JComboBox looks like a text field with an
arrow next to it. If you click on the arrow,
the list of possible values is displayed.
If the Jcombobox is set to be editable, then
you can edit the current selection as if it
was a text field.
Only one item can be selected at a time.
You can retrieve it by calling:
getSelectedItem method.
Add the choice items to the end of the list
with the addItem method.
JComboBox
Insert new items anywhere in the list with the insertItemAt :
faceCombo.insertItemAt(“Monospaced”, 0) //add at head
Remove items at run time by using removeItem or removeItemAt
faceCombo.removeItem(“Monospaced”);
faceCombo.removeItemAt(0); // remove first item
or
removeAllItems to remove all items at once
When an item is selected, the combo box generates an ActionEvent.
Call getSource on the event to get a reference to the combo box that
sent the event. Then call getSelectedItem to retrieve the selected
item.
//see ComboBoxTest.java
class ComboBoxFrame extends JFrame
{
public ComboBoxFrame()
{ setTitle("ComboBoxTest");
setSize(WIDTH, HEIGHT);
Container contentPane =
getContentPane();
// add the sample text label
label = new JLabel(
"The quick brown fox jumps over the lazy dog.");
label.setFont(new Font("Serif", Font.PLAIN, DEFAULT_SIZE));
contentPane.add(label, BorderLayout.CENTER);
// make a combo box and add face names
faceCombo = new JComboBox();
faceCombo.setEditable(true);
faceCombo.addItem("Serif");
faceCombo.addItem("SansSerif");
faceCombo.addItem("Monospaced");
faceCombo.addItem("Dialog");
faceCombo.addItem("DialogInput");
// the combo box listener changes the label font to the
// selected face name
faceCombo.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
label.setFont(new Font(
(String)faceCombo.getSelectedItem(),
Font.PLAIN, DEFAULT_SIZE));
}
});
//add combo box to a panel at the frame's souther
JPanel comboPanel = new JPanel();
comboPanel.add(faceCombo);
contentPane.add(comboPanel, BorderLayout.SOUTH);
}
Outline
Outline:
Overview of Swing components
Layout management
Using Swing components
– Text input, Buttons, ComboBox, Menus, Dialogs
Menus
Inheritance hierarchy of menu-related classes.
A menu bar contains one or more menus, placed onto a
frame.
A menu contains one or more menu items, which can be
menus themselves.
Menus/Creating Menus
1. Create JMenus
2. Create JmenuItems and associate
Actions with them
3. Add those JmenuItems to the Jmenu
4. When user selects a JmenuItem , an
Action is triggered.
5. Create a JMenuBar and place it onto a
frame
6. Add the JMenus to the JMenuBar
public class MenuTest extends JFrame …
{ public MenuTest()
{ …
JMenu fileMenu = new JMenu("File");
JMenuItem newItem = fileMenu.add(new TestAction("New"));
JMenuItem openItem = fileMenu.add(new TestAction(“Open”));
JMenuItem saveItem = fileMenu.add(new TestAction("Save"));
JMenuItem saveAsItem =fileMenu.add(new TestAction("Save As"));
….
JMenuBar mbar = new JMenuBar();
setJMenuBar(mbar); // add menu bar to the frame
menuBar.add(fileMenu);
menuBar.add(editMenu);
menuBar.add(helpMenu);
….
}
//MenuTest.java
Menus/Mnemonics and Accelerators
Keyboard Mnemonics are set by using setMnemonic
method
fileMenu.setMnemonic('F');
openItem.setMnemonic('O');
Accelerators are keyboard shortcuts (CTR+S, CTR+O)
openItem.setAccelerator
(KeyStroke.getKeyStroke(KeyEvent.VK_O,
InputEvent.CTRL_MASK));
saveItem.setAccelerator
(KeyStroke.getKeyStroke(KeyEvent.VK_S,
InputEvent.CTRL_MASK));
Menus/Menu Item Events
When user selects a menu item, an Action is triggered.
class TestAction extends AbstractAction
{
public TestAction(String name){super(name);}
public void actionPerformed(ActionEvent event)
{
System.out.println(getValue(Action.NAME) +
“ selected.”);
}
}
Menus/Menu Events
When user selects a menu, an MenuEvent is triggered.
MenuListener interface has three method
void menuSelected(MenuEvent )
// called before display menu
void menuDeselected(MenuEvent )
void menuCanceled(MenuEvent )
// called before menu selection is canceled, e.g.
// by clicking outside menu
Menus/Enable & Disabling Menu Items
Do this with setEnabled method.
saveItem.setEnabled( false);
saveAsItem.setEnabled( true );
Good time to enable and disable menu items: right before displaying, i.e.
within MenuListener
private class FileMenuListener implements MenuListener
{ …
public void menuSelected(MenuEvent evt)
{ saveItem.setEnabled(!readonlyItem.isSelected());
saveAsItem.setEnabled(!readonlyItem.isSelected());
}
This enables or disables saveItem and saveAsItem depending on
whether readonlyItem is selected.
Menus
Can have submenus, menu within menu. Inheritance
hierarchy of menu-related classes.
Can have check boxes, radio buttons as menu items
(JCheckBoxItem, JRadioButtonItem)
Can have popup menus.
MenuTest.java
Outline
Outline:
Overview of Swing components
Layout management
Using Swing components
– Text input, Buttons, ComboBox, Menus, Dialogs
Dialogs
Classes for specific dialogs
ProgressMonitor
JColorChooser
JFilerChooser
Class for standard dialogs
JOptionPane
Class for custom dialogs
JDialog
Dialogs
Every dialog box is a dependant of a parentComponent (frame).
parentComponent determines location of dialog box.
When that parentComponent is destroyed, so are its dependent
dialogs.
modal dialog box, when visible, blocks user input to all other windows
in the program. The dialogs that JOptionPane provides are modal.
A modeless dialog box lets the user enter information in both the
dialog box and the remainder of the application.
To create a modeless dialog, you must use the JDialog class
directly.
JDialog is a subclass of the AWT java.awt.Dialog
Using JDialog directly is very similar to using JFrame directly.
Option Dialogs
Commonly used methods of
JOptionPane
ShowMessageDialog
Show a message and wait for user
to click OK
ShowConfirmDialog
Show a message and get a
confirmation(Yes/No/Cancel)
ShowOptionDialog
Show a message and get a user
option from a set of options.
ShowInputDialog
Show a message and get one line
of user input.
//show DialogTest.java
Option Dialogs
Every Dialog has: an icon, a message , one or more option buttons.
icon type: ERROR_MESSAGE, INFORMATION_MESSAGE, WARNING_MESSAGE,
QUESTION_MESSAGE, PLAIN_MESSAGE
Message can be:
A String: Draw the string
Icon: Show the icon
Component: Show the component
Object[]: Show all objects in the array, stacked on top of each other.
Option buttons are:
DEFAULT_OPTION
YES_NO_OPTION
YES_NO_CANCEL_OPTION
OK_CANCEL_OPTION
Return value: An integer representing the chosen option
or a string that the user supplied or selected
Step to Create Option Dialogs
1. Choose the dialog type (message, confirmation, option or input),
2. Choose the icon(error, information, warning, question, none or custom).
3. Choose the message (string, icon, custom component, or a stack of
them).
4. For a confirmation dialog, choose the option type (default, yes/No,
Yes/No/Cancel, or OK/Cancel).
5. For an option dialog, choose the options (strings, icons, or custom
components ) and the default option.
6. For an input dialog, choose between a text field and a combo box.
7. Locate the appropriate method to call in the JOptionPane API.
Creating Dialogs
You can also create a dialog box by deriving a class from JDialog:
1. In the constructor of your dialog box, call the constructor of the base class
JDialog. You will need to tell it the owner frame (the frame window over
which the dialog pops up), the title of the dialog frame, and a Boolean flag to
indicate if the dialog box is modal or modeless.
2. Add the user interface components to the dialog box.
3. Add the event handlers.
4. Set the size for the dialog box.
//DialogTest.java
Data Exchange
The most common reason to put up a dialog box is to get information
from the user.
Your dialog box should provide methods to set default data:
public void setUser(User u)
{
username.setText(u.getName());
}
Then you can show the dialog such as the following:
boolean showDialog()
{
ok = false;
show();
return ok; //OK button sets the ok flag to true
}
Data Exchange
You should test the return value of the showDialog. If it is true, then
you can retrieve the user input by:
Public User getUser()
{
return new User (username.getText(),
password.getPassword());
}
private class ConnectAction implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
// if first time, construct dialog
if (dialog == null)
dialog = new PasswordChooser();
// set default values
dialog.setUser(new User("yourname", null));
// pop up dialog
if(dialog.showDialog(DataExchangeFrame.this, "Connect"))
{
// if accepted, retrieve user input
User u = dialog.getUser();
textArea.append(
"user name = " + u.getName() + ", password = "
+ (new String(u.getPassword())) + "n");
}
}
} //DataExchangeTest.java

More Related Content

What's hot

Control structures in java
Control structures in javaControl structures in java
Control structures in java
VINOTH R
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
Madishetty Prathibha
 
GUI Programming In Java
GUI Programming In JavaGUI Programming In Java
GUI Programming In Java
yht4ever
 
Java String
Java String Java String
Java String
SATYAM SHRIVASTAV
 
Javascript built in String Functions
Javascript built in String FunctionsJavascript built in String Functions
Javascript built in String Functions
Avanitrambadiya
 
Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVA
Ankita Totala
 
C Structures and Unions
C Structures and UnionsC Structures and Unions
C Structures and Unions
Dhrumil Patel
 
Hash table in java
Hash table in javaHash table in java
Hash table in java
siriindian
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
Naz Abdalla
 
Java threads
Java threadsJava threads
Java threads
Prabhakaran V M
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
Tech_MX
 
Java awt (abstract window toolkit)
Java awt (abstract window toolkit)Java awt (abstract window toolkit)
Java awt (abstract window toolkit)
Elizabeth alexander
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
Abhilash Nair
 
String, string builder, string buffer
String, string builder, string bufferString, string builder, string buffer
String, string builder, string buffer
SSN College of Engineering, Kalavakkam
 
Creating a frame within an applet
Creating a frame within an appletCreating a frame within an applet
Creating a frame within an applet
myrajendra
 
Swing
SwingSwing
Threads in JAVA
Threads in JAVAThreads in JAVA
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
CPD INDIA
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
VINOTH R
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate ppt
Aneega
 

What's hot (20)

Control structures in java
Control structures in javaControl structures in java
Control structures in java
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
 
GUI Programming In Java
GUI Programming In JavaGUI Programming In Java
GUI Programming In Java
 
Java String
Java String Java String
Java String
 
Javascript built in String Functions
Javascript built in String FunctionsJavascript built in String Functions
Javascript built in String Functions
 
Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVA
 
C Structures and Unions
C Structures and UnionsC Structures and Unions
C Structures and Unions
 
Hash table in java
Hash table in javaHash table in java
Hash table in java
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Java threads
Java threadsJava threads
Java threads
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Java awt (abstract window toolkit)
Java awt (abstract window toolkit)Java awt (abstract window toolkit)
Java awt (abstract window toolkit)
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
String, string builder, string buffer
String, string builder, string bufferString, string builder, string buffer
String, string builder, string buffer
 
Creating a frame within an applet
Creating a frame within an appletCreating a frame within an applet
Creating a frame within an applet
 
Swing
SwingSwing
Swing
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate ppt
 

Viewers also liked

Yaazli International Spring Training
Yaazli International Spring Training Yaazli International Spring Training
Yaazli International Spring Training
Arjun Sridhar U R
 
For Loops and Variables in Java
For Loops and Variables in JavaFor Loops and Variables in Java
For Loops and Variables in Java
Pokequesthero
 
Yaazli International AngularJS 5 Training
Yaazli International AngularJS 5 TrainingYaazli International AngularJS 5 Training
Yaazli International AngularJS 5 Training
Arjun Sridhar U R
 
Yaazli International Web Project Workshop
Yaazli International Web Project WorkshopYaazli International Web Project Workshop
Yaazli International Web Project Workshop
Arjun Sridhar U R
 
02basics
02basics02basics
02basics
Waheed Warraich
 
Toolbarexample
ToolbarexampleToolbarexample
Toolbarexample
yugandhar vadlamudi
 
Core java online training
Core java online trainingCore java online training
Core java online training
Glory IT Technologies Pvt. Ltd.
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
Garuda Trainings
 
Savr
SavrSavr
Java quick reference v2
Java quick reference v2Java quick reference v2
Java quick reference v2
Christopher Akinlade
 
Non ieee dot net projects list
Non  ieee dot net projects list Non  ieee dot net projects list
Non ieee dot net projects list
Mumbai Academisc
 
Yaazli International Hibernate Training
Yaazli International Hibernate TrainingYaazli International Hibernate Training
Yaazli International Hibernate Training
Arjun Sridhar U R
 
Exception handling in java
Exception handling in java Exception handling in java
Exception handling in java
yugandhar vadlamudi
 
09events
09events09events
09events
Waheed Warraich
 
Java Basic Operators
Java Basic OperatorsJava Basic Operators
Java Basic Operators
Shahid Rasheed
 
Non ieee java projects list
Non  ieee java projects list Non  ieee java projects list
Non ieee java projects list
Mumbai Academisc
 
DIWE - Using Extensions and Image Manipulation
DIWE - Using Extensions and Image ManipulationDIWE - Using Extensions and Image Manipulation
DIWE - Using Extensions and Image Manipulation
Rasan Samarasinghe
 
Singleton pattern
Singleton patternSingleton pattern
Singleton pattern
yugandhar vadlamudi
 
DIWE - Multimedia Technologies
DIWE - Multimedia TechnologiesDIWE - Multimedia Technologies
DIWE - Multimedia Technologies
Rasan Samarasinghe
 
Yaazli International Java Training
Yaazli International Java Training Yaazli International Java Training
Yaazli International Java Training
Arjun Sridhar U R
 

Viewers also liked (20)

Yaazli International Spring Training
Yaazli International Spring Training Yaazli International Spring Training
Yaazli International Spring Training
 
For Loops and Variables in Java
For Loops and Variables in JavaFor Loops and Variables in Java
For Loops and Variables in Java
 
Yaazli International AngularJS 5 Training
Yaazli International AngularJS 5 TrainingYaazli International AngularJS 5 Training
Yaazli International AngularJS 5 Training
 
Yaazli International Web Project Workshop
Yaazli International Web Project WorkshopYaazli International Web Project Workshop
Yaazli International Web Project Workshop
 
02basics
02basics02basics
02basics
 
Toolbarexample
ToolbarexampleToolbarexample
Toolbarexample
 
Core java online training
Core java online trainingCore java online training
Core java online training
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Savr
SavrSavr
Savr
 
Java quick reference v2
Java quick reference v2Java quick reference v2
Java quick reference v2
 
Non ieee dot net projects list
Non  ieee dot net projects list Non  ieee dot net projects list
Non ieee dot net projects list
 
Yaazli International Hibernate Training
Yaazli International Hibernate TrainingYaazli International Hibernate Training
Yaazli International Hibernate Training
 
Exception handling in java
Exception handling in java Exception handling in java
Exception handling in java
 
09events
09events09events
09events
 
Java Basic Operators
Java Basic OperatorsJava Basic Operators
Java Basic Operators
 
Non ieee java projects list
Non  ieee java projects list Non  ieee java projects list
Non ieee java projects list
 
DIWE - Using Extensions and Image Manipulation
DIWE - Using Extensions and Image ManipulationDIWE - Using Extensions and Image Manipulation
DIWE - Using Extensions and Image Manipulation
 
Singleton pattern
Singleton patternSingleton pattern
Singleton pattern
 
DIWE - Multimedia Technologies
DIWE - Multimedia TechnologiesDIWE - Multimedia Technologies
DIWE - Multimedia Technologies
 
Yaazli International Java Training
Yaazli International Java Training Yaazli International Java Training
Yaazli International Java Training
 

Similar to java swing

Java GUI Programming for beginners-graphics.pdf
Java GUI Programming for beginners-graphics.pdfJava GUI Programming for beginners-graphics.pdf
Java GUI Programming for beginners-graphics.pdf
PBMaverick
 
14a-gui.ppt
14a-gui.ppt14a-gui.ppt
14a-gui.ppt
DrDGayathriDevi
 
Chapter 11.3
Chapter 11.3Chapter 11.3
Chapter 11.3
sotlsoc
 
Chap1 1.4
Chap1 1.4Chap1 1.4
Chap1 1.4
Hemo Chella
 
Graphical User Interface in JAVA
Graphical User Interface in JAVAGraphical User Interface in JAVA
Graphical User Interface in JAVA
suraj pandey
 
3_ppt_Layout.pptxgßbdbdbdbsbsbsbbsbsbsbsbsb
3_ppt_Layout.pptxgßbdbdbdbsbsbsbbsbsbsbsbsb3_ppt_Layout.pptxgßbdbdbdbsbsbsbbsbsbsbsbsb
3_ppt_Layout.pptxgßbdbdbdbsbsbsbbsbsbsbsbsb
abhishekmathuroffici
 
Swing basics
Swing basicsSwing basics
Swing basics
Medi-Caps University
 
Getting started with GUI programming in Java_1
Getting started with GUI programming in Java_1Getting started with GUI programming in Java_1
Getting started with GUI programming in Java_1
Muhammad Shebl Farag
 
13457272.ppt
13457272.ppt13457272.ppt
13457272.ppt
aptechaligarh
 
Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1
PRN USM
 
Chap1 1 4
Chap1 1 4Chap1 1 4
Chap1 1 4
Hemo Chella
 
8layout Managers
8layout Managers8layout Managers
8layout Managers
Adil Jafri
 
9awt Components
9awt Components9awt Components
9awt Components
Adil Jafri
 
ch20.pptx
ch20.pptxch20.pptx
Layout manager
Layout managerLayout manager
Dr. Rajeshree Khande :Introduction to Java AWT
Dr. Rajeshree Khande :Introduction to Java AWTDr. Rajeshree Khande :Introduction to Java AWT
Dr. Rajeshree Khande :Introduction to Java AWT
DrRajeshreeKhande
 
03_GUI.ppt
03_GUI.ppt03_GUI.ppt
03_GUI.ppt
DrDGayathriDevi
 
swingbasics
swingbasicsswingbasics
swingbasics
Arjun Shanka
 
Chap1 1 1
Chap1 1 1Chap1 1 1
Chap1 1 1
Hemo Chella
 
Chap1 1.1
Chap1 1.1Chap1 1.1
Chap1 1.1
Hemo Chella
 

Similar to java swing (20)

Java GUI Programming for beginners-graphics.pdf
Java GUI Programming for beginners-graphics.pdfJava GUI Programming for beginners-graphics.pdf
Java GUI Programming for beginners-graphics.pdf
 
14a-gui.ppt
14a-gui.ppt14a-gui.ppt
14a-gui.ppt
 
Chapter 11.3
Chapter 11.3Chapter 11.3
Chapter 11.3
 
Chap1 1.4
Chap1 1.4Chap1 1.4
Chap1 1.4
 
Graphical User Interface in JAVA
Graphical User Interface in JAVAGraphical User Interface in JAVA
Graphical User Interface in JAVA
 
3_ppt_Layout.pptxgßbdbdbdbsbsbsbbsbsbsbsbsb
3_ppt_Layout.pptxgßbdbdbdbsbsbsbbsbsbsbsbsb3_ppt_Layout.pptxgßbdbdbdbsbsbsbbsbsbsbsbsb
3_ppt_Layout.pptxgßbdbdbdbsbsbsbbsbsbsbsbsb
 
Swing basics
Swing basicsSwing basics
Swing basics
 
Getting started with GUI programming in Java_1
Getting started with GUI programming in Java_1Getting started with GUI programming in Java_1
Getting started with GUI programming in Java_1
 
13457272.ppt
13457272.ppt13457272.ppt
13457272.ppt
 
Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1
 
Chap1 1 4
Chap1 1 4Chap1 1 4
Chap1 1 4
 
8layout Managers
8layout Managers8layout Managers
8layout Managers
 
9awt Components
9awt Components9awt Components
9awt Components
 
ch20.pptx
ch20.pptxch20.pptx
ch20.pptx
 
Layout manager
Layout managerLayout manager
Layout manager
 
Dr. Rajeshree Khande :Introduction to Java AWT
Dr. Rajeshree Khande :Introduction to Java AWTDr. Rajeshree Khande :Introduction to Java AWT
Dr. Rajeshree Khande :Introduction to Java AWT
 
03_GUI.ppt
03_GUI.ppt03_GUI.ppt
03_GUI.ppt
 
swingbasics
swingbasicsswingbasics
swingbasics
 
Chap1 1 1
Chap1 1 1Chap1 1 1
Chap1 1 1
 
Chap1 1.1
Chap1 1.1Chap1 1.1
Chap1 1.1
 

More from Waheed Warraich

java jdbc connection
java jdbc connectionjava jdbc connection
java jdbc connection
Waheed Warraich
 
java networking
 java networking java networking
java networking
Waheed Warraich
 
java threads
java threadsjava threads
java threads
Waheed Warraich
 
java applets
java appletsjava applets
java applets
Waheed Warraich
 
08graphics
08graphics08graphics
08graphics
Waheed Warraich
 
06 exceptions
06 exceptions06 exceptions
06 exceptions
Waheed Warraich
 
05io
05io05io
04inherit
04inherit04inherit
04inherit
Waheed Warraich
 
03class
03class03class
01intro
01intro01intro

More from Waheed Warraich (10)

java jdbc connection
java jdbc connectionjava jdbc connection
java jdbc connection
 
java networking
 java networking java networking
java networking
 
java threads
java threadsjava threads
java threads
 
java applets
java appletsjava applets
java applets
 
08graphics
08graphics08graphics
08graphics
 
06 exceptions
06 exceptions06 exceptions
06 exceptions
 
05io
05io05io
05io
 
04inherit
04inherit04inherit
04inherit
 
03class
03class03class
03class
 
01intro
01intro01intro
01intro
 

Recently uploaded

Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
adhitya5119
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
National Information Standards Organization (NISO)
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
chanes7
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
Jean Carlos Nunes Paixão
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
mulvey2
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
heathfieldcps1
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
ak6969907
 
Community pharmacy- Social and preventive pharmacy UNIT 5
Community pharmacy- Social and preventive pharmacy UNIT 5Community pharmacy- Social and preventive pharmacy UNIT 5
Community pharmacy- Social and preventive pharmacy UNIT 5
sayalidalavi006
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
RAHUL
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Excellence Foundation for South Sudan
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
RitikBhardwaj56
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
Israel Genealogy Research Association
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
Colégio Santa Teresinha
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
Nicholas Montgomery
 
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Fajar Baskoro
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
adhitya5119
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
Priyankaranawat4
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
WaniBasim
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
eBook.com.bd (প্রয়োজনীয় বাংলা বই)
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
GeorgeMilliken2
 

Recently uploaded (20)

Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
 
World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024World environment day ppt For 5 June 2024
World environment day ppt For 5 June 2024
 
Community pharmacy- Social and preventive pharmacy UNIT 5
Community pharmacy- Social and preventive pharmacy UNIT 5Community pharmacy- Social and preventive pharmacy UNIT 5
Community pharmacy- Social and preventive pharmacy UNIT 5
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
 
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
 
Liberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdfLiberal Approach to the Study of Indian Politics.pdf
Liberal Approach to the Study of Indian Politics.pdf
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
 

java swing

  • 1. Topic 10: Swing User Interface Components Chapter 9 Advanced Programming Techniques
  • 2. Objective and Outline • Objective: – What else do you need to know in order to create a full-featured GUI? • Outline: – Overview of Swing components – Layout management – Using Swing components • Text input, Buttons, ComboBox, Menus, Dialogs
  • 3. Overview of Swing Components http://java.sun.com/docs/books/tutorial/uiswing/components/components.html Top-Level Containers  Windows: JFrame class  Dialog boxes: JOptionPane,JDialog *, JFileChooser classes  Applets: JApplet * class v2: covered in volume 2, *: will discuss
  • 4. Overview of Swing Components General-Purpose containers for laying out components.  JPanel class  JScrollPane * class provides a scrollable view of components.  JSplitPane v2 displays two groups of components, either side by side or one on top of the other.
  • 5. Overview of Swing Components Basic control: Components for getting user input  Textfields: JTextField *, JPasswordField *, JTextArea *  Buttons: JButton *, JCheckBox *, JRadioButton *, … 
  • 6. Overview of Swing Components Basic control: Components for getting user input  JMenu *, JMenuItem *  JSlider v2, JScrollbar  JComboBox *  JSpinner
  • 7. Overview of Swing Components non-editable components for information display  Jlabel * class can display non-selectable text and images.  JProgressBar v2 class displays progress of a job.  Tool Tips v2: created using JComponent
  • 8. Overview of Swing Components Editable components for information display  JTable v2 class can display and edit tables of data,  Texts *:  JTree v2 class can display hierarchical data  File Chooser  JColorChooser class to provide users with a palette of colors to choose from.
  • 9. Overview of Swing Components Summary: Containers Top-Level: JFrame, JOptinePane, JDialog, JFileChooser,JApplet, General-purpose: JPanel, JScrollPane, JSplitPane User input JTextField, JPasswordField, JTextArea, JButton, JCheckbox, JRadioButton, Jlist, JComboBox, JMenu, JMenuItem, JSlider, JScrollBar Information display Non-editable: Jlabel, JProgressBar, Tool tips Editable: Jtable, Texts, Jtree, JColorChooser
  • 10. Outline Outline: Overview of Swing components Layout management Using Swing components – Text input, Buttons, ComboBox, Menus, Dialogs
  • 11. Layout Management Layout management determines the size and position of components. Each container has a default layout manager. Can be changed using the method: setLayout Generally, need to set the layout manager of two types of containers: content panes (which use BorderLayout by default) and JPanels (which use FlowLayout by default).
  • 12. • Types of Layout – FlowLayout – BorderLayout – GridLayout – BoxLayout – GridBagLayout Layout Management
  • 13. Layout Management • Component size – Default/natural minimum/preferred sizes calculated by the LayoutManager interface, which is implemented by all layout management classes • Dimension minimumLayoutSize(Container parent) • Dimension preferredLayoutSize(Container parent) – Can be changed using methods of JComponent • voidsetMaximumSize(Dimension maximumSize) • voidsetMinimumSize(Dimension minimumSize) • voidsetPreferredSize(Dimension preferredSize)
  • 14. Flow Layout FlowLayout class FlowLayout arranges components in a left-to-right flow, much like lines of text in a paragraph. Components sized at their preferred size. If the horizontal space in the container is too small, FlowLayout uses multiple rows. Within each row, components are centered (the default), left- aligned, or right-aligned as specified when the FlowLayout is created. Default layout manager of JPanel : typically used to arrange buttons in a panel
  • 15. Example: FlowWindow.java Container contentPane = getContentPane(); contentPane.setLayout(new FlowLayout()); contentPane.add(new JButton("Button 1")); contentPane.add(new JButton("2")); contentPane.add(new JButton("Button 3")); contentPane.add(new JButton("Long-Named Button 4")); contentPane.add(new JButton("Button 5")); Flow Layout
  • 16. FlowLayout class constructors: FlowLayout( int align, int hgap, int vgap) 1. align: FlowLayout.LEFT, FlowLayout.CENTER, FlowLayout.RIGHT 2. hgap: horizontal gap in pixels between components 3. vgap: vertical gap in pixels between components FlowLayout( int align) FlowLayout( ) Flow Layout
  • 17. Border Layout • BorderLayout: – Has five areas • Specify area for a component using one of the constants: NORTH, SOUTH, EAST, WEST, and CENTER. – Size of components determined by • Their preferred sizes and the constraints of the container's size. • The NORTH and SOUTH components may be stretched horizontally; the EAST and WEST components may be stretched vertically; the CENTER component may stretch both horizontally and vertically to fill any space left over. – Default for contentPane
  • 18. Container contentPane = getContentPane(); //Use the content pane's default BorderLayout. //contentPane.setLayout(new BorderLayout()); unnecessary contentPane.add(new JButton("Button 1 (NORTH)"), BorderLayout.NORTH); contentPane.add(new JButton("2 (CENTER)"), BorderLayout.CENTER); contentPane.add(new JButton("Button 3 (WEST)"), BorderLayout.WEST); contentPane.add(new JButton("Long-Named Button 4 (SOUTH)"),BorderLayout.SOUTH); contentPane.add(new JButton("Button 5 (EAST)"), BorderLayout.EAST); // BorderWindow.java
  • 19. BorderLayout class constructors: BorderLayout( int hgap, int vgap) 1. hgap: horizontal gap in pixels between components 2. vgap: vertical gap in pixels between components BorderLayout( ) Border Layout
  • 20. Grid Layout GridLayout: places components in a grid of cells. Each component takes all the available space within its cell. Each cell is exactly the same size. Number of columns ignored when number of rows set to non-zero Example:
  • 21. Container contentPane = getContentPane(); contentPane.setLayout(new GridLayout(0,2)); //construct an instance of GridLayout that has two // columns and as many rows as necessary. contentPane.add(new JButton("Button 1")); contentPane.add(new JButton("2")); contentPane.add(new JButton("Button 3")); contentPane.add(new JButton("Long-Named Button 4")); contentPane.add(new JButton("Button 5")); // GridWindow.java
  • 22. GridLayout class constructors: GridLayout(int rows, int columns, int hgap, int vgap) 1. hgap: horizontal gap in pixels between components 2. vgap: vertical gap in pixels between components GridLayout(int rows, int columns ) Grid Layout
  • 23. Box Layout • BoxLayout: places components in a single row or column – Attempt to arrange components at their preferred widths (for horizontal layout) or heights (for vertical layout). • For a horizontal layout, if not all the components are the same height, BoxLayout attempts to make all the components as high as the highest component. • For a vertical layout, BoxLayout attempts to make all components in the column as wide as the widest component. If that fails, it aligns them horizontally according to their X alignments.
  • 24. Box Layout • Instead of using BoxLayout directly, many programs use the Box class. • The Box class is a lightweight container that uses a BoxLayout. • It also provides handy methods to help you use BoxLayout well. • Adding components to multiple nested boxes is a powerful way to get the arrangement you want.
  • 25. Box class methods: all static Factory methods: createHorizontalBox(), createVerticalBox() If all the components your Box contains have a fixed size, you might want to use a glue component to control the components' positions. createHorizontalGlue(), createVerticalGlue, createGlue(): //push components as far away as possible Box Layout
  • 26. For a fixed amount of space between two components, try using a strut & rigid area createHorizontalStrut(int), createVecticalStrut(int) createRigidArea( Dimension ) //BoxLayoutTest.java Box Layout
  • 27. // construct the top horizontal box JLabel label1 = new JLabel("Name:"); JTextField textField1 = new JTextField(10); textField1.setMaximumSize(textField1.getPreferredSize()); Box hbox1 = Box.createHorizontalBox(); hbox1.add(label1); // separate with a 10-pixel strut hbox1.add(Box.createHorizontalStrut(10)); hbox1.add(textField1); // construct the middle horizontal box JLabel label2 = new JLabel("Password:"); JTextField textField2 = new JTextField(10); textField2.setMaximumSize(textField2.getPreferredSize()); Box hbox2 = Box.createHorizontalBox(); hbox2.add(label2); // separate with a 10-pixel strut hbox2.add(Box.createHorizontalStrut(10)); hbox2.add(textField2);
  • 28. // construct the bottom horizontal box JButton button1 = new JButton("Ok"); JButton button2 = new JButton("Cancel"); Box hbox3 = Box.createHorizontalBox(); hbox3.add(button1); // use "glue" to push the two buttons apart hbox3.add(Box.createGlue()); hbox3.add(button2); // add the three horizontal boxes inside a vertical box Box vbox = Box.createVerticalBox(); vbox.add(hbox1); vbox.add(hbox2); vbox.add(Box.createGlue()); vbox.add(hbox3); Container contentPane = getContentPane(); contentPane.add(vbox, BorderLayout.CENTER);
  • 29. GridBag Layout GridBagLayout: The most sophisticated, flexible layout manager the Java platform provides. It aligns components by placing them within a grid of cells, allowing some components to span more than one cell. The rows in the grid aren't necessarily all the same height; similarly, grid columns can have different widths.
  • 30. Layout Management Hierarchy of containers for achieving better layout: Containers inside other containers Each has a potentially a different layout manager Allows you to create sophisticated layout with simple layout managers //CombineTest.java
  • 31. // create vertical box Box b = Box.createVerticalBox(); // create top panel (FlowLayout) JPanel p1 = new JPanel(); p1.add( new JButton("Button 1")); p1.add( new JButton("2")); p1.add( new JButton("Button 3")); b.add(p1); // create Scrollable text area JTextArea t = new JTextArea(200, 50); JScrollPane sp = new JScrollPane( t ); b.add(sp); // create bottom panel (right-aligned FlowLayout) JPanel p2 = new JPanel(); p2.setLayout( new FlowLayout( FlowLayout.RIGHT )); p2.add( new JButton("OK")); b.add( p2 ); Container cp = getContentPane(); cp.add( b ); //CombineTest.java
  • 32. Borders for Components JComponents can have borders Create Border objects using static methods of BorderFactory class: createLineBorder, createMatteBorder, createEmptyBorder createEtchedBorder, …. Set border using the setBorder method of Jcomponent Example: BorderTest.java This example also demonstrate the use of JRadioButton, which will be discussed later
  • 33. public BorderFrame() { setTitle("BorderTest"); setSize(WIDTH, HEIGHT); demoPanel = new JPanel(); buttonPanel = new JPanel(); group = new ButtonGroup(); addRadioButton("Lowered bevel", BorderFactory.createLoweredBevelBorder()); addRadioButton("Raised bevel", BorderFactory.createRaisedBevelBorder()); addRadioButton("Etched", BorderFactory.createEtchedBorder()); addRadioButton("Line", BorderFactory.createLineBorder(Color.blue)); addRadioButton("Matte", BorderFactory.createMatteBorder( 10, 10, 10, 10, Color.blue)); addRadioButton("Empty", BorderFactory.createEmptyBorder());
  • 34. Border etched = BorderFactory.createEtchedBorder(); Border titled = BorderFactory.createTitledBorder (etched, "Border types"); buttonPanel.setBorder(titled); Container contentPane = getContentPane(); contentPane.setLayout(new GridLayout(2, 1)); contentPane.add(buttonPanel); contentPane.add(demoPanel); }
  • 35. public void addRadioButton(String buttonName, final Border b) { JRadioButton button = new JRadioButton(buttonName); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { demoPanel.setBorder(b); validate(); } }); group.add(button); buttonPanel.add(button); }
  • 36. Outline Outline: Overview of Swing components Layout management Using Swing components – Text input, Buttons, ComboBox, Menus, Dialogs
  • 37. Text Input JTextField, JPasswordField: one line. JTextArea: A multi-line area that displays plain text. JEditorPane: A text component to edit various kinds of content, plain text, html, rtf. Can be monitored using either CaretListener or DocumentListener Check Documentation of JTextComponent
  • 38. • JTextField also produces ActionEvent when ”return” is pressed. • Let’s make use of this to write a program: Text1.java. • Next, show how to make it better using DocumentListener (Text.java) Text Input
  • 39. Model-View-Controller Design Pattern Separates a software component into three distinct pieces: a model, a view, and a controller.
  • 40. Model-View-Controller Design Pattern • Model – represents the state and low-level behavior of the component. – manages the state and conducts all transformations on that state. – system itself maintains links between model and views and notifies the views when the model changes state. – Example: ButtonModel • Query internal state • Manipulate internal state • Add and remove event listeners • Fire events
  • 41. Model-View-Controller Design Pattern • view: – manages the visual display of the state represented by the model. • controller – manages user interaction with the model. It provides the mechanism by which changes are made to the state of the model. • Example: ButtonUI – Paint – Return geometric information – Handle AWT events
  • 42. Model-View-Controller Design Pattern • The component class JButton acts as the glue, or scaffolding, that holds the MVC triad together • Programmers do not typically work with model and view/controller classes directly • Example about what you can do using MVC: http://www.developer.com/java/ent/article.php/3336761
  • 43. Text Input Model for all text components, including TextField, JPasswordField, JTextArea are described by Document Interface. Text component generates DocumentEvents when its content is changed. To listen to such events, register a DocumentListener with the text component textComponent.getDocument() .addDocumentListener(listener); Check Documentation of JTextComponent
  • 44. Text Input The DocumentListener has three methods void insertUpdate(DocumentEvent e) void removeUpdate(DocumentEvent e) void changeUpdate(DocumentEvent e) // Gives notification that an attribute or set of attributes changed. No adapter class.
  • 45. class TextTestFrame extends JFrame { public TextTestFrame() { setTitle("TextTest"); setSize(WIDTH, HEIGHT); Container contentPane = getContentPane(); DocumentListener listener = new ClockFieldListener(); // add a panel with text fields JPanel panel = new JPanel(); hourField = new JTextField("12", 3); panel.add(hourField); hourField.getDocument().addDocumentListener(listener); minuteField = new JTextField("00", 3); panel.add(minuteField); minuteField.getDocument().addDocumentListener(listener); contentPane.add(panel, BorderLayout.SOUTH); // add the clock clock = new ClockPanel(); contentPane.add(clock, BorderLayout.CENTER); } //TextTest.java.
  • 46. Text Input/JTextField private class ClockFieldListener implements DocumentListener { public void insertUpdate(DocumentEvent e) { setClock(); } public void removeUpdate(DocumentEvent e) { setClock(); } public void changedUpdate(DocumentEvent e) {} } }
  • 47. Text Input/JTextField class TextTestFrame extends JFrame { public TextTestFrame() { …} public void setClock() // retrieving from both fields { int hours = Integer.parseInt(hourField.getText().trim()); int minutes = Integer.parseInt(minuteField.getText().trim()); clock.setTime(hours, minutes); } …… } Will change clock without pressing “Return”
  • 48. • Exercise: – Re-write Text.java using CaretListener Text Input/JTextField
  • 49. Outline Outline: Overview of Swing components Layout management Using Swing components – Text input, Buttons, ComboBox, Menus, Dialogs
  • 50. Buttons All button classes descend from AbstractButton JButton: A common button. JCheckBox: For “yes” or “no” input. JRadioButton: For exclusive choices among a group. If one button is pushed, all other buttons in the group depressed.
  • 51. JCheckBox Use a check box to collect yes/no input. The user checks/ the box by clicking inside it and turns off the check mark by clinking it again. Check boxes need a label next to them to identify their purpose. Bold = new JCheckBox(“Bold”); Use the setSelected method to turn a check box on or off Bold.setSelected(true); The isSelected method then retrieves the current state of each check box. It is false if unchecked; true if checked. When the user clicks on a check box, an action event is triggered. As always, you attach an action listener. ActionListener listener = … Bold.addActionListener(listener)
  • 52. class CheckBoxFrame extends JFrame { public CheckBoxFrame() { …… ActionListener listener = new ActionListener() { public void actionPerformed(Actionevent event) { int mode = 0; if (bold.isSelected()) mode +=Font.BOLD; if (italic.isSelected()) mode +=Font.ITALIC; label.setFont(new Font(“Serif”, mode, FONTSIZE)); } } JPanel buttonPanel = new JPanel(); bold = new JCheckBox( "Bold"); bold.addActionListener(listener); buttonPanel.add(bold); italic = new JCheckBox("Italic"); italic.addActionListener(listener); buttonPanel.add(italic); getContentPane().add(buttonPanel, BorderLayout.South); …} // CheckBoxTest.java
  • 53. Buttons/Radio Buttons Radio buttons group are groups of buttons in which only one button at a time can be selected. The Swing release supports radio buttons with the JRadioButton and ButtonGroup classes Example: Choosing pets (RadioButtonDemo.java)
  • 54. // Create the radio buttons. JRadioButton birdButton = new JRadioButton(birdString); birdButton.setMnemonic('b'); // Enable ALT+b // this is to be used together with getActionCommand birdButton.setActionCommand(birdString); birdButton.setSelected(true); // birButton selected JRadioButton catButton = new JRadioButton(catString); catButton.setMnemonic('c'); catButton.setActionCommand(catString); // Note catButton not selected // dogButton, RabbitButton, PigButton
  • 55. // Group the radio buttons. ButtonGroup group = new ButtonGroup(); group.add(birdButton); group.add(catButton); group.add(dogButton); group.add(rabbitButton); group.add(pigButton); // now one of those buttons can be selected
  • 56. // Register a listener for the radio buttons. RadioListener myListener = new RadioListener(); birdButton.addActionListener(myListener); catButton.addActionListener(myListener); ... class RadioListener implements ActionListener { public void actionPerformed(ActionEvent e) { picture.setIcon(new ImageIcon("images/“ + e.getActionCommand() + ".gif")); } Get this string set by setActionCommand images/cat.gif images/bird.gif …
  • 57. Outline Outline: Overview of Swing components Layout management Using Swing components – Text input, Buttons, ComboBox, Menus, Dialogs
  • 58. JComboBox A JComboBox looks like a text field with an arrow next to it. If you click on the arrow, the list of possible values is displayed. If the Jcombobox is set to be editable, then you can edit the current selection as if it was a text field. Only one item can be selected at a time. You can retrieve it by calling: getSelectedItem method. Add the choice items to the end of the list with the addItem method.
  • 59. JComboBox Insert new items anywhere in the list with the insertItemAt : faceCombo.insertItemAt(“Monospaced”, 0) //add at head Remove items at run time by using removeItem or removeItemAt faceCombo.removeItem(“Monospaced”); faceCombo.removeItemAt(0); // remove first item or removeAllItems to remove all items at once When an item is selected, the combo box generates an ActionEvent. Call getSource on the event to get a reference to the combo box that sent the event. Then call getSelectedItem to retrieve the selected item. //see ComboBoxTest.java
  • 60. class ComboBoxFrame extends JFrame { public ComboBoxFrame() { setTitle("ComboBoxTest"); setSize(WIDTH, HEIGHT); Container contentPane = getContentPane(); // add the sample text label label = new JLabel( "The quick brown fox jumps over the lazy dog."); label.setFont(new Font("Serif", Font.PLAIN, DEFAULT_SIZE)); contentPane.add(label, BorderLayout.CENTER); // make a combo box and add face names faceCombo = new JComboBox(); faceCombo.setEditable(true); faceCombo.addItem("Serif"); faceCombo.addItem("SansSerif"); faceCombo.addItem("Monospaced"); faceCombo.addItem("Dialog"); faceCombo.addItem("DialogInput");
  • 61. // the combo box listener changes the label font to the // selected face name faceCombo.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { label.setFont(new Font( (String)faceCombo.getSelectedItem(), Font.PLAIN, DEFAULT_SIZE)); } }); //add combo box to a panel at the frame's souther JPanel comboPanel = new JPanel(); comboPanel.add(faceCombo); contentPane.add(comboPanel, BorderLayout.SOUTH); }
  • 62. Outline Outline: Overview of Swing components Layout management Using Swing components – Text input, Buttons, ComboBox, Menus, Dialogs
  • 63. Menus Inheritance hierarchy of menu-related classes. A menu bar contains one or more menus, placed onto a frame. A menu contains one or more menu items, which can be menus themselves.
  • 64. Menus/Creating Menus 1. Create JMenus 2. Create JmenuItems and associate Actions with them 3. Add those JmenuItems to the Jmenu 4. When user selects a JmenuItem , an Action is triggered. 5. Create a JMenuBar and place it onto a frame 6. Add the JMenus to the JMenuBar
  • 65. public class MenuTest extends JFrame … { public MenuTest() { … JMenu fileMenu = new JMenu("File"); JMenuItem newItem = fileMenu.add(new TestAction("New")); JMenuItem openItem = fileMenu.add(new TestAction(“Open”)); JMenuItem saveItem = fileMenu.add(new TestAction("Save")); JMenuItem saveAsItem =fileMenu.add(new TestAction("Save As")); …. JMenuBar mbar = new JMenuBar(); setJMenuBar(mbar); // add menu bar to the frame menuBar.add(fileMenu); menuBar.add(editMenu); menuBar.add(helpMenu); …. } //MenuTest.java
  • 66. Menus/Mnemonics and Accelerators Keyboard Mnemonics are set by using setMnemonic method fileMenu.setMnemonic('F'); openItem.setMnemonic('O'); Accelerators are keyboard shortcuts (CTR+S, CTR+O) openItem.setAccelerator (KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_MASK)); saveItem.setAccelerator (KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK));
  • 67. Menus/Menu Item Events When user selects a menu item, an Action is triggered. class TestAction extends AbstractAction { public TestAction(String name){super(name);} public void actionPerformed(ActionEvent event) { System.out.println(getValue(Action.NAME) + “ selected.”); } }
  • 68. Menus/Menu Events When user selects a menu, an MenuEvent is triggered. MenuListener interface has three method void menuSelected(MenuEvent ) // called before display menu void menuDeselected(MenuEvent ) void menuCanceled(MenuEvent ) // called before menu selection is canceled, e.g. // by clicking outside menu
  • 69. Menus/Enable & Disabling Menu Items Do this with setEnabled method. saveItem.setEnabled( false); saveAsItem.setEnabled( true ); Good time to enable and disable menu items: right before displaying, i.e. within MenuListener private class FileMenuListener implements MenuListener { … public void menuSelected(MenuEvent evt) { saveItem.setEnabled(!readonlyItem.isSelected()); saveAsItem.setEnabled(!readonlyItem.isSelected()); } This enables or disables saveItem and saveAsItem depending on whether readonlyItem is selected.
  • 70. Menus Can have submenus, menu within menu. Inheritance hierarchy of menu-related classes. Can have check boxes, radio buttons as menu items (JCheckBoxItem, JRadioButtonItem) Can have popup menus. MenuTest.java
  • 71. Outline Outline: Overview of Swing components Layout management Using Swing components – Text input, Buttons, ComboBox, Menus, Dialogs
  • 72. Dialogs Classes for specific dialogs ProgressMonitor JColorChooser JFilerChooser Class for standard dialogs JOptionPane Class for custom dialogs JDialog
  • 73. Dialogs Every dialog box is a dependant of a parentComponent (frame). parentComponent determines location of dialog box. When that parentComponent is destroyed, so are its dependent dialogs. modal dialog box, when visible, blocks user input to all other windows in the program. The dialogs that JOptionPane provides are modal. A modeless dialog box lets the user enter information in both the dialog box and the remainder of the application. To create a modeless dialog, you must use the JDialog class directly. JDialog is a subclass of the AWT java.awt.Dialog Using JDialog directly is very similar to using JFrame directly.
  • 74. Option Dialogs Commonly used methods of JOptionPane ShowMessageDialog Show a message and wait for user to click OK ShowConfirmDialog Show a message and get a confirmation(Yes/No/Cancel) ShowOptionDialog Show a message and get a user option from a set of options. ShowInputDialog Show a message and get one line of user input. //show DialogTest.java
  • 75. Option Dialogs Every Dialog has: an icon, a message , one or more option buttons. icon type: ERROR_MESSAGE, INFORMATION_MESSAGE, WARNING_MESSAGE, QUESTION_MESSAGE, PLAIN_MESSAGE Message can be: A String: Draw the string Icon: Show the icon Component: Show the component Object[]: Show all objects in the array, stacked on top of each other. Option buttons are: DEFAULT_OPTION YES_NO_OPTION YES_NO_CANCEL_OPTION OK_CANCEL_OPTION Return value: An integer representing the chosen option or a string that the user supplied or selected
  • 76. Step to Create Option Dialogs 1. Choose the dialog type (message, confirmation, option or input), 2. Choose the icon(error, information, warning, question, none or custom). 3. Choose the message (string, icon, custom component, or a stack of them). 4. For a confirmation dialog, choose the option type (default, yes/No, Yes/No/Cancel, or OK/Cancel). 5. For an option dialog, choose the options (strings, icons, or custom components ) and the default option. 6. For an input dialog, choose between a text field and a combo box. 7. Locate the appropriate method to call in the JOptionPane API.
  • 77. Creating Dialogs You can also create a dialog box by deriving a class from JDialog: 1. In the constructor of your dialog box, call the constructor of the base class JDialog. You will need to tell it the owner frame (the frame window over which the dialog pops up), the title of the dialog frame, and a Boolean flag to indicate if the dialog box is modal or modeless. 2. Add the user interface components to the dialog box. 3. Add the event handlers. 4. Set the size for the dialog box. //DialogTest.java
  • 78. Data Exchange The most common reason to put up a dialog box is to get information from the user. Your dialog box should provide methods to set default data: public void setUser(User u) { username.setText(u.getName()); } Then you can show the dialog such as the following: boolean showDialog() { ok = false; show(); return ok; //OK button sets the ok flag to true }
  • 79. Data Exchange You should test the return value of the showDialog. If it is true, then you can retrieve the user input by: Public User getUser() { return new User (username.getText(), password.getPassword()); }
  • 80. private class ConnectAction implements ActionListener { public void actionPerformed(ActionEvent event) { // if first time, construct dialog if (dialog == null) dialog = new PasswordChooser(); // set default values dialog.setUser(new User("yourname", null)); // pop up dialog if(dialog.showDialog(DataExchangeFrame.this, "Connect")) { // if accepted, retrieve user input User u = dialog.getUser(); textArea.append( "user name = " + u.getName() + ", password = " + (new String(u.getPassword())) + "n"); } } } //DataExchangeTest.java