Tabbed panes - WordPress.com

Document technical information

Format pptx
Size 986.7 kB
First found May 22, 2018

Document content analysis

Category Also themed
Language
English
Type
not defined
Concepts
no text concepts found

Persons

Organizations

Places

Transcript

Chapter 8
Graphics Programming
(contd.)
Outline
 Text Input
 Choice Components
 Menus
 Mnemonics
 Toolbars
 Tooltips
 Tabbed panes
 Scroll panes
 Dialog Boxes
2
JTextField

If the cursor is in the text field, the user presses the
Enter key, JTextField generates an Action event
• Listener?
– … implements ActionListener
• Method in the listener?
– public void actionPerformed(ActionEvent e)
• Register listener to the text field?
– void addActionListener(ActionListener listener)
3
Example: JTextFieldDemo.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JTextFieldDemo extends JFrame
implements ActionListener
{
JTextField mmText;
JLabel resultLabel;
public JTextFieldDemo() {
super("Chuyen doi don vi");
setLayout(new GridLayout(2,2));
public void actionPerformed(ActionEvent e)
{
double cm, mm;
mm = Double.parseDouble(mmText.getText());
cm = mm/10;
resultLabel.setText (Double.toString(cm));
}
add (new JLabel (“Nhap vao so millimet:"));
add (mmText = new JTextField (10));
add (new JLabel (“So centimet tuong ung: "));
add (resultLabel = new JLabel ("---"));
public static void main(String[] args)
new JTextFieldDemo();
}
mmText.addActionListener (this);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(300,90);
setVisible(true);
{
}
}
4
JTextArea

Purpose
• For texts with more than one line long

Constructors
• JTextArea(int rows, int cols)
– constructs a new text area with number of rows and
columns
• JTextArea(String text, int rows, int
cols)
– constructs a new text area with an initial text
5
Example: JTextAreaDemo.java
JPanel buttonPanel = new JPanel();
buttonPanel.add(insertButton=new JButton("Insert"));
buttonPanel.add(wrapButton = new JButton("Wrap"));
add(buttonPanel, BorderLayout.SOUTH);
textArea = new JTextArea(8, 40);
add(textArea, BorderLayout.CENTER);
6
JPasswordField


Purpose: used to enter a password
A JPasswordField is similar to a JTextField
except the characters typed in by the user are not
echoed back to the user
• Instead, an alternate character such as asterisks (*) is
displayed
• You can set the echo character using the method:
– public void setEchoChar(char c)
7
JPasswordField - Methods


String getText()
char[] getPassword()
• returns the text contained in this password field


char getEchoChar()
void setEchoChar(char ch)
• gets or sets the character that is displayed as the user
types into this field
8
Example: JPasswordFieldDemo.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JPasswordFieldDemo extends JFrame
implements ActionListener
{
JPasswordField txtPassword;
JButton btnOk, btnCancel;
pnlRight = new JPanel(new GridLayout(0,1));
pnlRight.add(btnOk = new JButton("OK"));
pnlRight.add(btnCancel=new JButton("Cancel"));
add(pnlLeft, BorderLayout.WEST);
add(pnlRight, BorderLayout.CENTER);
btnOk.addActionListener(this);
public JPasswordFieldDemo()
{
super("JPasswordField Demo");
JPanel pnlLeft, pnlRight;
btnCancel.addActionListener(this);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setsize(200, 200);
txtPassword = new JPasswordField(12);
txtPassword.addActionListener(this);
setVisible(true);
}
pnlLeft = new JPanel();
pnlLeft.add(new JLabel("Password: "));
pnlLeft.add(txtPassword);
9
JPasswordFieldDemo.java
public void actionPerformed(ActionEvent e)
{
Object o = e.getSource();
if (o == btnOk || o == txtPassword)
{
char chPassword[] = txtPassword.getPassword();
String strPassword = new String(chPassword);
if(strPassword.trim().equals("pass")) {
JOptionPane.showMessageDialog(this,"Correct Password");
System.exit(0);
}
else {
JOptionPane.showMessageDialog(this,"Incorrect Password","Error Message",
JOptionPane.ERROR_MESSAGE);
txtPassword.selectAll();
txtPassword.requestFocus();
}
}
else {
System.exit(0);
}
}
public static void main(String [] args){
new JPasswordFieldDemo();
}
}
10
Outline
 Text Input
 Choice Components
 Menus
 Mnemonics
 Toolbars
 Tooltips
 Tabbed panes
 Scroll panes
 Dialog Boxes
11
JCheckBox

Purpose:
• Used for multi-option user input that the user may
select or deselect by clicking on them

Constructors:

JCheckBox()
• Creates an initially unchecked checkbox with no label

JCheckBox(String text)
• Creates a checkbox (initially unchecked) with the
specified text; see setSelected for changing it

JCheckBox(String text, boolean selected)
• Creates a checkbox with the specified text
– The initial state is determined by the boolean value
provided
– A value of true means it is checked
12
JCheckBox – Methods

boolean isSelected()
• returns the state of the checkbox

void setSelected(boolean state)
• sets the checkbox to a new state


String getText()
void setText(String text)
• gets or sets the button’s text

addItemListener/removeItemListener
• Add or remove an ItemListener to process ItemEvent
in itemStateChanged
13
Example: JCheckBoxDemo.java
import java.awt.*;
import javax.swing.*;
public class JCheckBoxDemo extends JFrame {
JCheckBox cboxRead, cboxMusic, cboxPaint, cboxMovie , cboxDance;
JButton btnExit;
public JCheckBoxDemo() {
super("JCheckBox Demo");
JPanel panel = new JPanel(new GridLayout(7,1));
panel.add( new JLabel("What's your hobby?" ));
panel.add(cboxRead = new JCheckBox("Reading"));
panel.add(cboxMusic = new JCheckBox("Music"));
panel.add(cboxPaint = new JCheckBox("Painting"));
panel.add(cboxMovie = new JCheckBox("Movies"));
panel.add(cboxDance = new JCheckBox("Dancing"));
panel.add(btnExit= new JButton("Exit"));
add(panel);
setLocation(400, 300);
setSize(250, 250);
setVisible(true);
}
public static void main(String args[]) {new JCheckBoxDemo();}
}
14
Handling JCheckBox event

A JCheckBox generates an Item event whenever
it changes state (checked/unchecked)
• Handle the event
– implements ItemListener
– Method: public void itemStateChanged (ItemEvent e)
– The ItemEvent class has a getItem method which
returns the item just selected or deselected
– Register: addItemListener
• Ignore the event
– With checkboxes, it is relatively common to ignore the
select/deselect event when it occurs
– Instead, you look up the state of the checkbox later
using the isSelected method of JCheckBox
15
JRadioButton

Purpose: Used as option button to specify choices

Only one radio button in a group can be selected at any
given time

To define the group of radio buttons, create a
ButtonGroup object
ButtonGroup group = new ButtonGroup();
group.add(smallButton);
group.add(mediumButton);


Note: the ButtonGroup controls only the behavior of the
buttons; if you want to group the buttons for layout purposes,
you also need to add them to a container
When the user checks a radio button, JRadioButton
generates an Action event (…)
16
JRadioButton – Constructors

JRadioButton()
• Creates an initially unchecked radio button with no label

JRadioButton(String text)
• Creates a radio button (initially unchecked) with the
specified text; see setSelected for changing it

JRadioButton(String text, boolean selected)
• Creates a radio button with the specified text
– The initial state is determined by the boolean value provided
– A value of true means it is checked
17
JRadioButton – Methods

boolean isSelected()
• returns the state of the radio button

void setSelected(boolean state)
• sets the radio button to a new state


String getText()
void setText(String text)
• gets or sets the button’s text
18
Example: JRadioButtonDemo.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JRadioButtonDemo extends JFrame {
JRadioButton radUnder, radGra, radPost, radDoc;
public JRadioButtonDemo() {
super("JRadioButton Demo");
setLayout(new GridLayout(6,1));
ButtonGroup group = new ButtonGroup();
group.add (radUnder);
group.add (radGra);
group.add (radPost);
group.add (radDoc);
setLocation(400, 300);
setSize(250, 250);
setVisible(true);
radUnder = new JRadioButton("Undergraduate");
radGra = new JRadioButton("Graduate");
radPost = new JRadioButton("Post Graduate");
radDoc = new JRadioButton("Doctorate");
add(new JLabel("What's your primary qualification?" ));
}
public static void main(String args[]) {
new JRadioButtonDemo ();
}
}
add(radUnder);
add(radGra);
add(radPost);
add(radDoc);
19
JComboBox

Purpose
• To present a set of choices in a
small space

Current selection
• item displaying

Can be editable
• A JComboBox can be either
editable or uneditable (default)
20
JComboBox - Constructors

JComboBox()
• Creates a JComboBox with a default data model

JComboBox(Object[] items)
• Creates a JComboBox that contains the elements of
the specified array
• Example:
String[] words= { "quick", "brown", "hungry", "wild", ... };
JComboBox wordChoose = new JComboBox(words);

JComboBox(ComboBoxModel asModel)
• Creates a JComboBox that takes its items from an
existing ComboBoxModel
21
JComboBox – Methods

void addItem(Object item)
• adds the specified item to the end of the combo box

Object getItemAt(int index)
• returns the item at the specified index

int getSelectedIndex()
• returns the position of selected item

void setSelectedIndex(int index)
• sets the selected index

Object getSelectedItem()
• returns the currently selected item

void setSelectedItem(Object item)
• sets the selected item
22
JComboBox – Methods (cont.)

void removeAllItems()
• removes all items from the combo box

void removeItem(Object item)
• removes an item from the combo box

void removeItemAt(int index)
• removes the item at an index

int getItemCount()
• returns the number of items in the list

void setEditable(boolean flag)
• sets whether this combo box is editable (default by
false). Note that editing affects only the current item, it
does not change the content of the list
23
Example

The user can choose a font style from a list of styles
(Serif, SansSerif, Monospaced, etc.). The user can
also type in another font
24
Handle event in JComboBox

When the user selects an item from a combo box,
the combo box generates an Action event or Item
event
• implement?
• method?
public void actionPerformed(ActionEvent e) {
// sử dụng hàm getSelectedItem()
// hoặc getSelectedIndex()
// để lấy mục đang được chọn trên combo
}
• register?
25
JComboBoxDemo.java
import java.awt.*;
import java.awt.event.*;
faceCombo.addItem("Dialog");
faceCombo.addItem("DialogInput");
import javax.swing.*;
faceCombo.addActionListener(this);
public class JComboBoxDemo extends JFrame
add(faceCombo, BorderLayout.SOUTH);
implements ActionListener {
JComboBox faceCombo;
setSize(300, 200);
setVisible(true);
JLabel label;
public JComboBoxDemo() {
}
setTitle("JComboBox Demo");
public void actionPerformed (ActionEvent e) {
String fontName = (String)faceCombo.getSelectedItem();
label = new JLabel("The quick brown fox jumps
over the lazy dog.");
label.setFont (new Font(fontName, Font.PLAIN, 12));
label.setFont(new Font("Serif", Font.PLAIN, 12));
}
add(label, BorderLayout.CENTER);
public static void main(String[] args) {
new JComboBoxDemo();
}
// make a combo box
faceCombo = new JComboBox();
faceCombo.addItem("Serif");
}
faceCombo.addItem("SansSerif");
faceCombo.addItem("Monospaced");
26
Outline
 Text Input
 Choice Components
 Menus
 Mnemonics
 Toolbars
 Tooltips
 Tabbed panes
 Scroll panes
 Dialog Boxes
27
Menus

Menus display several options that are broadly
categorized
• Menu bar (JMenuBar)
• Menu (JMenu)
• Menu item (JMenuItem)

Clicking a JMenuItem, it generates an Action event
28
Components in the menu
JMenu
JMenuBar
JMenuItem
JMenu
JCheckBoxMenuItem
JRadioButtonMenuItem
29
JMenuBar


JMenuBar is a container for JMenu
Constructor:
• JMenuBar()

To set the menu bar for JFrame, using method:
• void setJMenuBar(JMenuBar menubar)

To add a JMenu to the menu bar, using add method
of JMenuBar
• add(JMenu menu)
30
JMenu - Constructors and Methods

JMenu(String label)
• constructs a menu

JMenuItem add(JMenuItem item)
• adds a menu item (or a menu)

JMenuItem add(String label)
• adds a menu item to this menu

void addSeparator()
• adds a separator line to the menu

void remove(int index)
• removes a specific item from the menu

void remove(JMenuItem item)
• removes a specific item from the menu
31
JMenuItem – Constructors

JMenuItem()
• constructs an empty menu item

JMenuItem(String label)
• constructs a menu item with a given label

JMenuItem(Icon icon)
• constructs a menu item with the given icon

JMenuItem(String label, Icon icon)
• constructs a menu item with the given label and icon

JMenuItem(String label, int mnemonic)
• constructs a menu item with the given label and
mnemonic
32
Example: JMenuDemo.java
import java.awt.*;
import javax.swing.*;
public class JMenuDemo extends JFrame {
JMenuBar mnubar;
JMenu mnuFile, mnuEdit, mnuHelp;
JMenuItem mnuFileNew, mnuFileOpen, mnuFileSave, mnuFileSaveAs, mnuFileExit;
JMenuItem mnuEditCut, mnuEditCopy, mnuEditPaste, mnuEditOption;
public JMenuDemo()
{
mnubar = new JMenuBar();
setJMenuBar(mnubar);
mnuFile = new JMenu("File"); mnubar.add(mnuFile);
mnuEdit = new JMenu("Edit"); mnubar.add(mnuEdit);
mnuHelp = new JMenu("Help"); mnubar.add(mnuHelp);
// menu File
mnuFileNew = new JMenuItem("New"); mnuFile.add(mnuFileNew);
mnuFileOpen = new JMenuItem("Open"); mnuFile.add(mnuFileOpen);
mnuFileSave = new JMenuItem("Save"); mnuFile.add(mnuFileSave);
mnuFileSaveAs = new JMenuItem("Save As..."); mnuFile.add(mnuFileSaveAs);
mnuFile.addSeparator();
mnuFileExit = new JMenuItem("Exit", 'x'); mnuFile.add(mnuFileExit);
33
Example (cont.)
//menu Edit
mnuEditCut = new JMenuItem("Cut", new ImageIcon("cut.gif"));
mnuEditCopy = new JMenuItem("Copy", new ImageIcon("copy.gif"));
mnuEditPaste = new JMenuItem("Paste", new ImageIcon("paste.gif"));
mnuEditOption = new JMenu("Options");
mnuEdit.add(mnuEditCut);
mnuEdit.add(mnuEditCopy);
mnuEdit.add(mnuEditPaste);
mnuEdit.addSeparator();
mnuEdit.add(mnuEditOption);
//…
setLocation(200, 200);
setSize(500, 400);
setVisible(true);
}
public static void main(String[] args)
new JMenuDemo();
}
{
}
34
Example (cont.)
JCheckBoxMenuItem readonlyItem = new JCheckBoxMenuItem("Read-only");
optionsMenu.add(readonlyItem);
JRadioButtonMenuItem insertItem = new JRadioButtonMenuItem("Insert", true);
JRadioButtonMenuItem overtypeItem = new JRadioButtonMenuItem("Overtype");
optionsMenu.add(insertItem);
optionsMenu.add(overtypeItem);
ButtonGroup group = new ButtonGroup();
group.add(insertItem);
group.add(overtypeItem);
35
JPopupMenu



A pop-up menu is a menu that is not attached to a
menu bar but that floats somewhere
It is also used as a shortcut menu, which is activated
by the right click of the mouse
The constructors used to create JPopupMenu are:
• JPopupMenu()
– creates a JPopupMenu
• JPopupMenu(String label)
– creates a JPopupMenu with the specified title

To pop up a menu when the user clicks on a
component, simply call the
setComponentPopupMenu method
36
JPopupMenu – Methods

JMenuItem add(JMenuItem menuItem)
• appends the specified menu item at the end of the menu

JMenuItem add(String s)
• creates a new menu item with the specified text and
appends it to the end of the menu

void show(Component c, int x, int y)
• displays the popup menu at the position (x,y) in the
coordinate space of the component “c”

boolean isPopupTrigger()
• determines whether the mouse event is considered as the
popup trigger for the current platform
37
Example: JMenuPopupDemo.java
import java.awt.event.*;
import javax.swing.*;
public class JMenuPopupDemo extends JFrame implements ActionListener {
JPopupMenu popup;
JMenuItem mnuEditCut, mnuEditCopy, mnuEditPaste;
public JMenuPopupDemo() {
popup = new JPopupMenu();
mnuEditCut = new JMenuItem("Cut", new ImageIcon("cut.gif"));
mnuEditCopy = new JMenuItem("Copy", new ImageIcon("copy.gif"));
mnuEditPaste = new JMenuItem("Paste", new ImageIcon("paste.gif"));
popup.add(mnuEditCut);
popup.add(mnuEditCopy);
popup.add(mnuEditPaste);
mnuEditCut.addActionListener(this);
mnuEditCopy.addActionListener(this);
mnuEditPaste.addActionListener(this);
JPanel panel = new JPanel();
panel.setComponentPopupMenu(popup);
panel.addMouseListener( new MouseAdapter() {} );
add(panel);
38
Example (cont.)
setLocation(200, 200);
setSize(500, 400);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
Object o = e.getSource();
System.out.println(((JMenuItem)o).getText() + " selected.");
}
public static void main(String[] args)
{
new JMenuPopupDemo();
}
}
39
Outline
 Text Input
 Choice Components
 Menus
 Mnemonics
 Toolbars
 Tooltips
 Tabbed panes
 Scroll panes
 Dialog Boxes
40
Mnemonics



Mnemonics (shortcut keys) provide quick access to
menu commands or button commands through the
keyboard
Once the mnemonic has been established, the
character in the label will appear underlined
You can supply a mnemonic letter by calling the
setMnemonic method:
• public void setMnemonic(int mnemonic)
Example:
JMenu helpMenu = new JMenu("Help");
helpMenu.setMnemonic('H');
41
Outline
 Text Input
 Choice Components
 Menus
 Mnemonics
 Toolbars
 Tooltips
 Tabbed panes
 Scroll panes
 Dialog Boxes
42
Toolbars

A toolbar is a button bar that gives quick access to the
most commonly used commands in a program
43
Toolbars – Constructors and Methods




JToolBar()
JToolBar(String titleString)
JToolBar(int orientation)
JToolBar(String titleString, int
orientation)

• construct a toolbar with the given title string and
orientation, orientation is one of
SwingConstants.HORIZONTAL (the default) and
SwingConstants.VERTICAL
void add(Component comp)

• add a component to toolbar
void addSeparator()
• adds a separator to the end of the toolbar
44
Example: JToolbarDemo.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JToolbarDemo extends JFrame implements ActionListener {
private JPanel panel;
private JButton btnBlue, btnYell, btnRed, btnExit;
JToolBar bar;
public JToolbarDemo() {
super("JToolBar Demo");
btnBlue = new JButton(new ImageIcon("blue-ball.gif")); btnBlue.addActionListener(this);
btnYell = new JButton(new ImageIcon("yellow-ball.gif")); btnYell.addActionListener(this);
btnRed = new JButton(new ImageIcon("red-ball.gif")); btnRed.addActionListener(this);
btnExit = new JButton(new ImageIcon("exit.gif"));
btnExit.addActionListener(this);
bar = new JToolBar();
bar.add(btnBlue);
bar.add(btnYell);
bar.add(btnRed);
bar.addSeparator();
bar.add(btnExit);
add(bar, BorderLayout.NORTH);
45
Example (cont.)
panel = new JPanel();
add(panel);
setSize(300, 200);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
Object o = e.getSource();
if (o.equals(btnBlue))
panel.setBackground(Color.BLUE);
if (o.equals(btnYell))
panel.setBackground(Color.YELLOW);
if (o.equals(btnRed))
panel.setBackground(Color.RED);
if (o.equals(btnExit))
System.exit(0);
}
public static void main(String[] args) { new JToolbarDemo();
}
}
46
Outline
 Text Input
 Choice Components
 Menus
 Mnemonics
 Toolbars
 Tooltips
 Tabbed panes
 Scroll panes
 Dialog Boxes
47
Tooltips

A tooltip represents a text tip that is displayed
when the mouse cursor rests for a moment over a
button and when the user moves the mouse away,
the tooltip is removed
• The tooltip text is displayed inside a colored
rectangle

Add tooltip by calling the setToolTipText
method
• void setToolTipText(String text)
Example:
exitButton.setToolTipText("Bấm vào đây để thoát chương trình");
48
Outline
 Text Input
 Choice Components
 Menus
 Mnemonics
 Toolbars
 Tooltips
 Tabbed panes
 Scroll panes
 Dialog Boxes
49
Tabbed panes
50
Tabbed panes

Purpose
• Break up a complex dialog box into subsets of related
options


A tabbed pane is defined by the JTabbedPane class
To create a tabbed pane, you first construct a
JTabbedPane object, then you add tabs to it
• Example:
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab(“ScreenSaver”, new ImageIcon(“Ss.gif”), panel1);
51
JTabbedPane

You set the tab layout to wrapped or scrolling mode by
calling setTabLayoutPolicy method:
• tabbedPane.setTabLayoutPolicy(JTabbedPane.WRAP_TAB_LAYOUT);
or
• tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
52
Methods



void addTab(String title, Component c)
void addTab(String title, Icon icon, Component c)
void addTab(String title, Icon icon, Component c,
String tooltip)
• add a tab to the end of the tabbed pane

void insertTab(String title, Icon icon, Component
c, String tooltip, int index)
• inserts a tab to the tabbed pane at the given index

void removeTabAt(int index)
• removes the tab at the given index

void setSelectedIndex(int index)
• selects the tab at the given index

int getSelectedIndex()
• returns the index of the selected tab
53
Example: JTabbedPaneExample.java
54
Outline
 Text Input
 Choice Components
 Menus
 Mnemonics
 Toolbars
 Tooltips
 Tabbed panes
 Scroll panes
 Dialog Boxes
55
JScrollPane

Why do we use JScrollPane?
• Components do not automatically provide a scrollbar
• Such as: JTextArea, JList, JTable,…

A JScrollPane object is used to provide the
automatic scrolling capability for components
• JScrollPane automatically appears if there is much
data than the component can display, and they vanish
again if text is deleted
56
JScrollPane - Contructors

JScrollPane(Component comp)
• Creates a JScrollPane that displays the contents of the specified
component, where both horizontal and vertical scrollbars appear
whenever the component's contents are larger than the view

JScrollPane(Component comp, int vsbPolicy,
int hsbPolicy)
• Creates a JScrollPane that displays the view component in a
viewport whose view position can be controlled with a pair of
scrollbars
– JScrollPane.VERTICAL_SCROLLBAR_ALWAYS
– JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS
– JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED
– JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED
57
Example: TextAreaTest.java
textArea = new JTextArea(8, 40);
scrollPane = new JScrollPane(textArea);
add(scrollPane, BorderLayout.CENTER);
58
Outline
 Text Input
 Choice Components
 Menus
 Mnemonics
 Toolbars
 Tooltips
 Tabbed panes
 Scroll pane
 Dialog Boxes
59
Dialog Boxes


A dialog box is a window that appears on top of
any currently active window
It may be used to:
•
•
•
•

Show message / confirm an action / enter data
Display information
Choose a file
Pick a color
Dialog box in Swing
•
•
•
•
JOptionPane
JDialog
JFileChooser
JColorChooser
60
JOptionPane


Purpose: presenting information, confirming an
action, or accepting an input value
Four static methods to show these simple dialogs:
• showMessageDialog(…)
– Show a message and wait for the user to click OK
• showConfirmDialog(…)
– Show a message and get a confirmation (like OK/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
– The message string can contain newline ('\n')
characters
61
JOptionPane - Parameters






Component parent
• The parent component (this or null)
Object message
• The message to show on the dialog (can be a string, icon,
component, or an array of them)
String title
• the string in the title bar of the dialog
int messageType: a property of JOptionPane class
• Can be one of ERROR_MESSAGE, INFORMATION_MESSAGE,
WARNING_MESSAGE, QUESTION_MESSAGE,
PLAIN_MESSAGE
int optionType: a property of JOptionPane class
• Can be one of DEFAULT_OPTION, YES_NO_OPTION,
YES_NO_CANCEL_OPTION, OK_CANCEL_OPTION
Icon icon
• an icon to show instead of one of the standard icons
62
JOptionPane – Message and Confirm
JOptionPane.showMessageDialog(this, "Message", "Title",
JOptionPane.WARNING_MESSAGE);
int selection = JOptionPane.showConfirmDialog(this, "Message", "Title",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.WARNING_MESSAGE);
if (selection == JOptionPane.OK_OPTION) . . .
63
Example: JOptionPaneDemo.java
import javax.swing.*;
public class JOptionPaneDemo {
public static void main (String[] args)
{
String numStr, result;
int num, again;
do {
numStr = JOptionPane.showInputDialog ("Enter an integer: ");
num = Integer.parseInt(numStr);
result = "That number is " + ((num%2 == 0) ? "even" : "odd");
JOptionPane.showMessageDialog (null, result);
again = JOptionPane.showConfirmDialog (null, "Do Another?");
} while (again == JOptionPane.YES_OPTION);
}
}
64
JDialog

To implement a dialog box, you derive a class from
JDialog

A modal dialog box won't let users interact with the
remaining windows of the application until it is closed
• You use a modal dialog box when you need
information from the user before you can proceed with
execution
65
Example: JDialogDemo.java
public class AboutDialog extends JDialog implements ActionListener {
JPanel panel;
JButton ok;
JLabel infor;
public AboutDialog(JFrame owner) {
super(owner, "About DialogTest", true);
infor = new JLabel("Core Java By Cay Horstmann and Gary Cornell");
add(infor, BorderLayout.CENTER);
ok = new JButton("Ok");
ok.addActionListener(this);
panel = new JPanel();
panel.add(ok);
add(panel, BorderLayout.SOUTH);
setSize(300, 150);
setLocation(300,300);
AboutDialog dialog;
public void actionPerformed(ActionEvent e)
{
if (dialog == null)
dialog = new AboutDialog(this);
dialog.setVisible(true);
}
}
public void actionPerformed(ActionEvent e) { setVisible(false); }
}
66
JFileChooser

Purpose
• display a dialog for opening a file or saving a file
67
JFileChooser

To create a JFileChooser object:
• JFileChooser chooser = new JFileChooser();

To show the dialog box, calling the
showOpenDialog or showSaveDialog method
• return JFileChooser.APPROVE_OPTION: if approval (Yes, Ok) is
chosen
• return JFileChooser.CANCEL_OPTION: if Cancel is chosen
• return JFileChooser.ERROR_OPTION: if an error occured

To get the selected file or files:
• File f = chooser.getSelectedFile();
• File[] f = chooser.getSelectedFiles();

To get path of the selected file:
• String filename = chooser.getSelectedFile().getPath();
68
JFileChooser

To set the current directory:
• setCurrentDirectory(new File("."));

To allow to select multiple files in the dialog
• setMultiSelectionEnabled(true);

To allow to select only directories, only files or files
and directories:
• setFileSelectionMode(JFileChooser.FILES_ONLY)
(default)
• setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY)
• setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES)

To restrict the display of files in the dialog to those of
a particular type, you need to set a file filter

See JFileChooserDemo.java, DisplayFileToTextArea.java
69
JColorChooser

Purpose
• To allow the user to select a color

A dialog box that lets the user click on a color of
choice from a palette or specify the color using RGB
values
70
Example: JColorChooserDemo.java
panel = new JPanel();
add (panel);
setLocation(200,100);
setSize(500, 500);
setVisible(true);
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JColorChooserDemo extends JFrame
implements ActionListener {
JMenuBar mnubar;
JMenu mnuFile, mnuEdit;
JMenuItem mnuFileExit;
JMenuItem mnuEditColor;
JPanel panel;
public JColorChooserDemo() {
mnubar = new JMenuBar();
mnuFile = new JMenu("File"); mnubar.add(mnuFile);
mnuEdit = new JMenu("Edit"); mnubar.add(mnuEdit);
// menu File
mnuFileExit = new JMenuItem("Exit");
mnuFile.add(mnuFileExit);
}
public void actionPerformed(ActionEvent e) {
Color mau= panel.getBackground();
mau = JColorChooser.showDialog (this,
"Pick a Color!", mau);
panel.setBackground (mau);
}
public static void main(String[] args) {
new JColorChooserDemo();
}
}
// menu Edit
mnuEditColor = new JMenuItem("Color");
mnuEditColor.addActionListener(this);
mnuEdit.add(mnuEditColor);
setJMenuBar(mnubar);
71

Similar documents

×

Report this document