cs3340: swing and event handling l. grewe. swing differences between swing and awt naming...
TRANSCRIPT
CS3340: Swing and CS3340: Swing and Event handlingEvent handling
L. GreweL. Grewe
SwingDifferences between Swing and AWT
Naming Conventions
All Swing components begin with a capital J -- JPanel, JButton, JScrollBar, JApplet, etc..
Most Swing Components are “Lightweight”
•Use Java code rather than native code to draw in the underlying window.
•The Exceptions are JFrame, JApplet, JWindow, and JDialog
Use Content Pane for adding Components to “Heavyweight” Containers
To add Components to a JApplet (in method init( )) use
Container cp = new getContentPane( );
cp.add(new JButton(“Start”);
SwingDifferences between Swing and AWT Components
Use of paintComponent for Drawing
public void paintComponent(Graphics g) {
super.paintComponent(g);
//always call super.paintComponent( ) before performing custom drawing
// draw Shape on the Swing Component
}Double Buffering
In Swing a JPanel is used instead of a Canvas to be the target for drawing graphics objects. When drawing to a JPanel using paintComponent double buffering is automatically employed. There is an option to perform drawing directly to the screen using the paint method by using panel.getGraphics( );
Anatomy of a Java Swing GUIAnatomy of a Java Swing GUI JFrameJFrame JPanelJPanel Layout ManagerLayout Manager JComponentsJComponents
JPanel
JButton
JFrame
Layout Manager
Build from bottom upBuild from bottom up
Create:Create: FrameFrame PanelPanel Layout managerLayout manager ComponentsComponents ListenersListeners
Add: (bottom up)Add: (bottom up) layout manager to panel layout manager to panel listeners to componentslisteners to components components to panelcomponents to panel panel to framepanel to frame
JPanel
JButton
Layout
Listener
JFrame
CodeCode
JFrame f = new JFrame(“title”)JFrame f = new JFrame(“title”)
JPanel p = new JPanel( );JPanel p = new JPanel( );
JButton b = new JButton(“press me”);JButton b = new JButton(“press me”);
p.add(b);p.add(b); // add button to // add button to panelpanel
f.setContentPane(p); // add panel to framef.setContentPane(p); // add panel to frame
f.setVisible(true);f.setVisible(true);
General-Purpose ContainersGeneral-Purpose Containers
Intermediate containers which can Intermediate containers which can be used under many different be used under many different circumstances:circumstances:• Panel (JPanel)Panel (JPanel)• Scroll pane (JScrollPane)Scroll pane (JScrollPane)• Split paneSplit pane• Tabbed paneTabbed pane• Tool barTool bar
General Purpose Containers General Purpose Containers
PanelPanel—most flexible and frequently used. —most flexible and frequently used. Add almost no functionality beyond what Add almost no functionality beyond what all objects have. Often used to group all objects have. Often used to group components.components.
Scroll paneScroll pane—provides scroll bars around —provides scroll bars around a large or growable component.a large or growable component.
Split paneSplit pane—displays two components in a —displays two components in a fixed amount of space, letting the user fixed amount of space, letting the user adjust the amount of space devoted to adjust the amount of space devoted to each component.each component.
General Purpose Containers General Purpose Containers
Tabbed paneTabbed pane—contains multiple —contains multiple components but show only one at a components but show only one at a time. The user can easily switch time. The user can easily switch between components.between components.
Tool barTool bar—holds a group of —holds a group of components (usually buttons) in a components (usually buttons) in a row or column, optionally allowing row or column, optionally allowing the user to drag the tool bar into the user to drag the tool bar into different locations.different locations.
General-Purpose ContainersGeneral-Purpose Containers
Panel
Scroll Pane
Tool bar
Split pane
Tabbed pane
Special-Purpose ContainersSpecial-Purpose Containers
Intermediate containers that play specific Intermediate containers that play specific roles in the use interface. roles in the use interface. • Internal frameInternal frame— Able to display display a — Able to display display a
Frame-like window within another window. Frame-like window within another window. Usually, you add internal frames to a desktop Usually, you add internal frames to a desktop pane.pane.
• Layered frameLayered frame—Provides a third dimension for —Provides a third dimension for positioning components: depth, also known as Z positioning components: depth, also known as Z order.order.
• Root paneRoot pane—Has 4 parts: glass pane, layered —Has 4 parts: glass pane, layered pane, content pane, and the (optional) menu pane, content pane, and the (optional) menu bar. bar.
Special-Purpose ContainersSpecial-Purpose Containers
Internal Frame
Layered Pane
Root Pane
Layout ManagersLayout Managers Review -layout managers:Review -layout managers:
null (no manager, programmer sets x,y,w,h)null (no manager, programmer sets x,y,w,h) FlowlayoutFlowlayout GridLayoutGridLayout BorderLayoutBorderLayout
c
n
s
ew
CodeCode
JFrame f = new JFrame(“title”)JFrame f = new JFrame(“title”)
JPanel p = new JPanel( );JPanel p = new JPanel( );
JButton b = new JButton(“press me”);JButton b = new JButton(“press me”);
b.setBounds(new Rectangle(10,10, 100,50));b.setBounds(new Rectangle(10,10, 100,50));
p.setLayout(null);p.setLayout(null); // x,y layout// x,y layout
p.add(b);p.add(b);
f.setContentPane(p);f.setContentPane(p);
1515
An example nested layoutAn example nested layout Container container = new Container container = new JFrame() or JApplet()JFrame() or JApplet();;
JPanel p1 = new JPanel(); JPanel p1 = new JPanel(); p1.setLayout(new BorderLayout());p1.setLayout(new BorderLayout());p1.add(new JButton("A"), BorderLayout.NORTH);p1.add(new JButton("A"), BorderLayout.NORTH); // also add buttons B, C, D, E // also add buttons B, C, D, E
JPanel p2 = new JPanel();JPanel p2 = new JPanel();p2.setLayout(new GridLayout(3, 2));p2.setLayout(new GridLayout(3, 2));p2.add(new JButton("F"));p2.add(new JButton("F")); // also add buttons G, H, I, J, K // also add buttons G, H, I, J, K
JPanel p3 = new JPanel();JPanel p3 = new JPanel();p3.setLayout(new BoxLayout(p3, BoxLayout.Y_AXIS));p3.setLayout(new BoxLayout(p3, BoxLayout.Y_AXIS));p3.add(new JButton("L"));p3.add(new JButton("L")); // also add buttons M, N, O, P // also add buttons M, N, O, P
container.setLayout(new BorderLayout()); container.setLayout(new BorderLayout()); container.add(p1, BorderLayout.CENTER); container.add(p1, BorderLayout.CENTER); container.add(p2, BorderLayout.SOUTH); container.add(p2, BorderLayout.SOUTH); container.add(p3, BorderLayout.EAST); container.add(p3, BorderLayout.EAST);
ComponentsComponents• Buttons—Buttons—can be square or roundcan be square or round• Combo BoxCombo Box—can be uneditable and —can be uneditable and
editable.editable.• ListList—Presents the user with a group of —Presents the user with a group of
items, displayed in a column, to choose from. items, displayed in a column, to choose from. • MenuMenu—provides a space-saving way to let —provides a space-saving way to let
the user choose one of several options.the user choose one of several options.• SliderSlider—lets user enter a numeric value —lets user enter a numeric value
bounded by a minimum and maximum value.bounded by a minimum and maximum value.• Text FieldsText Fields—basic text control that lets the —basic text control that lets the
user enter a small amount of text.user enter a small amount of text.
Basic ComponentsBasic Components
Buttons Combo BoxList
Menu Slider Text Fields
More Components – not More Components – not selectableselectable
Atomic components that exist solely to Atomic components that exist solely to give the user information. give the user information. • LabelLabel—able to display unselectable text and —able to display unselectable text and
images.images.• Progress BarProgress Bar—displays the progress of a —displays the progress of a
long-running task (also, ProgressMonitor and long-running task (also, ProgressMonitor and ProgressMonitorInputStream)ProgressMonitorInputStream)
• Tool tipTool tip—comes up when the user of the —comes up when the user of the program pauses with the cursor over any of the program pauses with the cursor over any of the program's buttonsprogram's buttons
Uneditable Information Uneditable Information DisplaysDisplays
Tool Tips
Progress Bar
Label
Editable Displays of Editable Displays of Formatted InformationFormatted Information
Atomic components that display highly Atomic components that display highly formatted information that can be edited by formatted information that can be edited by the user. the user. • Color chooser—Color chooser—provide users with a palette of provide users with a palette of
colors to choose from.colors to choose from.• File chooser—File chooser—provide a GUI for navigating the provide a GUI for navigating the
file system, and then either choosing a file or file system, and then either choosing a file or directory from a list or entering a file name or directory from a list or entering a file name or directory name.directory name.
• Table—Table—displays tables of data, optionally allowing displays tables of data, optionally allowing the user to edit the data. the user to edit the data.
• Text—Text—displays text and allows user to edit itdisplays text and allows user to edit it• Tree—Tree—displays data in hierarchical waydisplays data in hierarchical way
Editable Displays of Editable Displays of Formatted InformationFormatted Information
File Chooser
Color Chooser
Table Text
Tree
Editable Displays of Editable Displays of Formatted InformationFormatted Information
Atomic components that display highly Atomic components that display highly formatted information that can be edited by formatted information that can be edited by the user. the user. • Color chooser—Color chooser—provide users with a palette of provide users with a palette of
colors to choose from.colors to choose from.• File chooser—File chooser—provide a GUI for navigating the provide a GUI for navigating the
file system, and then either choosing a file or file system, and then either choosing a file or directory from a list or entering a file name or directory from a list or entering a file name or directory name.directory name.
• Table—Table—displays tables of data, optionally allowing displays tables of data, optionally allowing the user to edit the data. the user to edit the data.
• Text—Text—displays text and allows user to edit itdisplays text and allows user to edit it• Tree—Tree—displays data in hierarchical waydisplays data in hierarchical way
Editable Displays of Editable Displays of Formatted InformationFormatted Information
File Chooser
Color Chooser
Table Text
Tree
EventsEvents
How to handle user events related to How to handle user events related to GUI componentsGUI components
EventsEvents Register with a component to receive Register with a component to receive
eventsevents Give component a ref to a Listener objectGive component a ref to a Listener object
ActionListenerActionListener KeyListenerKeyListener MouseListenerMouseListener WindowListenerWindowListener ……
JButton
Listener
click
ActionEventregister
CodeCode
myListener = new myListenClass;myListener = new myListenClass;
btn.addActionListener(myListener);btn.addActionListener(myListener);
Class myListenClass implements ActionListener {Class myListenClass implements ActionListener {
public void actionPerformed(ActionEvent e){public void actionPerformed(ActionEvent e){
// button pressed, do stuff here// button pressed, do stuff here
}}
}}
Simplifying: InheritanceSimplifying: Inheritance
Class myframe Class myframe extendsextends JFrame{ JFrame{
public myframe(){public myframe(){
// create panel, buttons, …// create panel, buttons, …
setContentPane(p);setContentPane(p); // I am a jframe// I am a jframe
}}
public static void main(){public static void main(){
JFrame f = new myframe();JFrame f = new myframe();
}}
}}
Myframe creates JFrame via inheritanceMyframe creates JFrame via inheritance
Simplifying: InheritanceSimplifying: InheritanceClass myframe extends JFrame{Class myframe extends JFrame{public myframe(){public myframe(){
// create panel, buttons, …// create panel, buttons, …}}public static void main(){public static void main(){
JFrame f = new myframe();JFrame f = new myframe();}}public void public void paintpaint(Graphics g){(Graphics g){
super.paint(g); //call overriden methodsuper.paint(g); //call overriden method// paint stuff here// paint stuff here
}}}} Override JFrame methods to add functionalityOverride JFrame methods to add functionality
Simplifying: ImplementsSimplifying: Implements
Class myframe extends JFrame Class myframe extends JFrame
implementsimplements ActionListener { ActionListener {
public myframe(){public myframe(){
// create panel, buttons, …// create panel, buttons, …
btn.addActionListener(btn.addActionListener(thisthis););
}}
public void public void actionPerformedactionPerformed(ActionEvent e){(ActionEvent e){
// button pressed, do stuff here// button pressed, do stuff here
}}
}}
Simplifying: Anonymous classesSimplifying: Anonymous classes
Class myframe extends JFrame {Class myframe extends JFrame {
public myframe(){public myframe(){// create panel, buttons, …// create panel, buttons, …btn.addActionListener(btn.addActionListener( newnew ActionListener() { ActionListener() {
public void public void actionPerformedactionPerformed(ActionEvent e)(ActionEvent e){{
// button pressed, do stuff here// button pressed, do stuff here }}
} } ););
}}}}
Defining and instantiating a class on the fly
3131
Components use various Components use various listenerslisteners
JButton, JMenuItem, JComboBox, JTextField:JButton, JMenuItem, JComboBox, JTextField:• addActionListener(ActionListener)addActionListener(ActionListener)
public void actionPerformed(ActionEvent event)public void actionPerformed(ActionEvent event) JCheckBox, JRadioButton:JCheckBox, JRadioButton:
• addItemListener(ItemListener)addItemListener(ItemListener) public void itemStateChanged(ItemEvent event)public void itemStateChanged(ItemEvent event)
JSliderJSlider• addChangeListener(ChangeListener)addChangeListener(ChangeListener)
public void stateChanged(ChangeEvent event)public void stateChanged(ChangeEvent event) JTextAreaJTextArea
• getDocument().getDocument().addDocumentListener(DocumentListener)addDocumentListener(DocumentListener) public void insertUpdate(DocumentEvent event)public void insertUpdate(DocumentEvent event) public void removeUpdate(DocumentEvent event)public void removeUpdate(DocumentEvent event) public void changedUpdate(DocumentEvent event)public void changedUpdate(DocumentEvent event)
3232
Components- Getting valuesComponents- Getting values Some user actions normally cause the program to Some user actions normally cause the program to
dodo something: clicking a button, or selecting from something: clicking a button, or selecting from a menua menu
Some user actions set values to be used Some user actions set values to be used later: later: entering text, setting a checkbox or a radio buttonentering text, setting a checkbox or a radio button• You You cancan listen for events from these, but it’s not listen for events from these, but it’s not
usually a good ideausually a good idea• Instead, Instead, readread their values when you need them their values when you need them
String myText = myJTextField.getText();String myText = myJTextField.getText(); String myText = myJTextArea.getText();String myText = myJTextArea.getText(); boolean checked = myJCheckBox.isSelected();boolean checked = myJCheckBox.isSelected(); boolean selected1 = myJRadioButton1.isSelected();boolean selected1 = myJRadioButton1.isSelected();
3333
Components - Enabling and disablingComponents - Enabling and disabling It is poor style to remove components It is poor style to remove components
you don’t want the user to be able to you don’t want the user to be able to use use • ““Where did it go? It was here a minute ago!”Where did it go? It was here a minute ago!”• Exception – changing to new interfaceException – changing to new interface
It’s better to It’s better to enableenable and and disabledisable controls controls• Disabled controls appear “grayed out”Disabled controls appear “grayed out”• The user may still wonder The user may still wonder why?why?, but that’s still less confusing, but that’s still less confusing
anyComponentanyComponent.setEnabled(.setEnabled(enabledenabled););• Parameter should beParameter should be true true to enable,to enable, false false to disableto disable
An exampleAn example
Example 1 – an applet with 3 buttons and 2 text fields
Step1 – Design the interface
Read Write
Enter text
Correct Entry?
Applet
The JApplet will consist of 2 JPanels –
The top one containing labels and text fields
The bottom one containing three JButtonsThe browser will add a title bar when the applet is running
Swing
Read Write Clear
Enter text
Correct Entry?
Applet
The top Panel will use a GridLayout with 2 rows and 2 columns
(with a separation of 10 pixels)
Swing Example 1
//(global) attributes of the classprivate MyJTextField source = new MyJTextField(25);
private MyJTextField target = new MyJTextField(25);
private JLabel edit = new JLabel("Enter text");
private JLabel verify = new JLabel("Correct Entry?");
private String inStr = new String("");
//method to construct the top panel
private JPanel makeJTextPanel( ) {
JPanel theText = new JPanel( );
theText.setLayout(new GridLayout(2,2, 10, 10));
theText.add(edit);
theText.add(source);
theText.add(verify);
theText.add(target);
return theText;
}
Construct the top panel – write a method makeJTextPanel( )
Add components to the grid – left to right, top to bottom
Swing Example 1
Read Write Clear
Enter text
Correct Entry?
Applet
Construct the bottom Panel – Use FlowLayout (center adjusted)
Top JPanel
Bottom JPanel
Swing Example 1Construct the bottom panel – with a methodprivate MyJButton read;
private MyJButton write;
private MyJButton clear;
//build the bottom panel with method makeJButtonPanel( )
private JPanel makeJButtonPanel() {
read = new MyJButton ("Read", source);
write = new MyJButton("Write", target);
clear = new MyJButton("Clear", target);
JPanel theButtons = new JPanel( );
theButtons.setLayout(new FlowLayout(FlowLayout.CENTER));
theButtons.add(read);
theButtons.add(write);
theButtons.add(clear);
theButtons.setBackground(Color.blue);
return theButtons;
}
Create the bottom panel
Set its layout and color, and add the buttons to it (left to right)
Swing Example 1Place the panels into the applet in method init( )
public void init( ) {
Container cp = getContentPane( );
theButtons = makeJButtonPanel( );
cp.add(BorderLayout.SOUTH, theButtons);
theText = makeJTextPanel( );
cp.add(BorderLayout.CENTER, theText);
}
For heavyweight component like JApplet components must be added to a ContentPane
//add theButtons (a JPanel) to the ContentPane
//the default LayoutManager of a JApplet is BorderLayout
MyJButton objects interact with MyJTextField objects
Swing Example 1Design of the System
A button event will cause a read, write, or clear of a text field.
JPanel
JApplet
MyJTextField
MyJTextField(int size)
doButtonAct(MyJButton)
String response
MyJButtonJLabel
MyJButton(String, MyJTextField)
actionPerformed(ActionEvent)
MyJTextField target
ActionListener
activates
The applet is an aggregate of 2 JPanels2
32
describes
JPanels contain JLabels and MyJTextField objects OR MyJButtons
Swing Example 1
class MyJButton extends JButton implements ActionListener {
private MyJTextField target;
public MyJButton(String name, MyJTextField targ) {
Font buttonFont = new Font ("Times Roman", Font.BOLD, 12);
setFont(buttonFont);
setText(name);
setBackground(Color.cyan);
target = targ;
addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
target.doButtonAct(this);
}
}
class MyJButton
Constructor receives handle to text field
Hold handle to target text field
Event causes message to be sent to the target to perform a read or write
Swing Example 1
class MyJTextField extends JTextField {
private String response = new String( );
public MyJTextField(int size) {
super(size);
}
public void doButtonAct(MyJButton source) {
response = source.getText( );
if (response.equals("Read") )
inStr = super.getText( );
else if (response.equals("Write") )
setText(inStr);
else if (response.equals("Clear") )
setText("");
}
}
A MyJButton object notifies a MyJTextField of a button event and elicits an action
Now some more Classes Now some more Classes
Lets examine a few classes in more Lets examine a few classes in more detailsdetails
Swing And JScrollPaneAdding scroll bars to a component such as a JTextArea
Just wrap a JTextArea object inside a JScrollPane.
JTextArea ta = new JTextArea(10, 25);
JScrollPane sp = new JScrollPane(ta);
The programmer can control which scrollbars are allowed – vertical, horizontal, both, or neither
JScrollPane sp = new JScrollPane(ta,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
4646
DialogsDialogs A A dialogdialog (small accessory window) (small accessory window)
can be can be modalmodal or or nonmodalnonmodal• When your code opens a modal dialog, it waits for a When your code opens a modal dialog, it waits for a
result from the dialog before continuingresult from the dialog before continuing• When your code opens a nonmodal dialog, it does so in When your code opens a nonmodal dialog, it does so in
a separate thread, and your code just keeps goinga separate thread, and your code just keeps going
Sun supplies a few simple (but Sun supplies a few simple (but useful) useful) modalmodal dialogs for your use dialogs for your use
You can create your own dialogs You can create your own dialogs (with (with JDialogJDialog), but they are ), but they are nonmodalnonmodal by defaultby default
4747
Message dialogsMessage dialogs JOptionPane.showMessageDialog(parentJFrame,JOptionPane.showMessageDialog(parentJFrame,
"This is a JOptionPane \"message\" "This is a JOptionPane \"message\" dialog.");dialog.");
Notice that Notice that showMessageDialogshowMessageDialog is a is a static method of static method of JOptionPaneJOptionPane
The “The “parentJFrameparentJFrame” is typically your ” is typically your main GUI window (but it’s OK to use main GUI window (but it’s OK to use nullnull if you don’t have a main GUI window)if you don’t have a main GUI window)
4848
Confirm dialogsConfirm dialogs
int yesNo =int yesNo = JOptionPane.showConfirmDialog(parentJFrame,JOptionPane.showConfirmDialog(parentJFrame, "Is this what you wanted to "Is this what you wanted to see?");see?");
if (yesNo == JOptionPane.YES_OPTION) { ... }if (yesNo == JOptionPane.YES_OPTION) { ... }
4949
Input dialogsInput dialogs
String userName =String userName = JOptionPane.showInputDialog(parentJFrame, JOptionPane.showInputDialog(parentJFrame, "What is your "What is your name?")name?")
5050
Option dialogsOption dialogs Object[] options =Object[] options =
new String[] {"English", "Chinese", "French", "German" }; new String[] {"English", "Chinese", "French", "German" };int option =int option = JOptionPane.showOptionDialog(parentJFrame, JOptionPane.showOptionDialog(parentJFrame, "Choose an option:", "Choose an option:", "Option Dialog", "Option Dialog", JOptionPane.YES_NO_OPTION,JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,JOptionPane.QUESTION_MESSAGE, null, null, options, options, options[0]); options[0]); // use as default// use as default
Fourth argument could be Fourth argument could be JOptionPane.YES_NO_CANCEL_OPTIONJOptionPane.YES_NO_CANCEL_OPTION Fifth argument specifies which icon to use in the dialog; it could be Fifth argument specifies which icon to use in the dialog; it could be
one of one of ERROR_MESSAGEERROR_MESSAGE, , INFORMATION_MESSAGEINFORMATION_MESSAGE, , WARNING_MESSAGEWARNING_MESSAGE, or , or PLAIN_MESSAGEPLAIN_MESSAGE
Sixth argument (Sixth argument (nullnull above) can specify a custom icon above) can specify a custom icon
5151
Load file dialogsLoad file dialogs JFileChooser chooser = new JFileChooser();JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle("Load which file?");chooser.setDialogTitle("Load which file?"); int result = chooser.showOpenDialog(enclosingJFrame);int result = chooser.showOpenDialog(enclosingJFrame);
if (result == JFileChooser.APPROVE_OPTION) {if (result == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); File file = chooser.getSelectedFile(); // use file // use file}}
You could also test You could also test for for CANCEL_OPTIONCANCEL_OPTION oror ERROR_OPTIONERROR_OPTION
You will get back a You will get back a FileFile object; to use it, object; to use it, you must know how you must know how to do file I/Oto do file I/O
5252
Save file dialogsSave file dialogs JFileChooser chooser = new JFileChooser();JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle(“Save file as?");chooser.setDialogTitle(“Save file as?"); int result = chooser.showSaveDialog(enclosingJFrame);int result = chooser.showSaveDialog(enclosingJFrame);
if (result == JFileChooser.APPROVE_OPTION) {if (result == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); File file = chooser.getSelectedFile(); // use file // use file}}
You could also test You could also test for for CANCEL_OPTIONCANCEL_OPTION oror ERROR_OPTIONERROR_OPTION
You will get back a You will get back a FileFile object; to use it, object; to use it, you must know how you must know how to do file I/Oto do file I/O