An Overview of GUI Controls in Java Programming

 
Objectives
describe some of the GUI controls and their
listeners; more appear in part 13
12
. G
UI Examples I
 
DIN61-222 Adv. Prog. (Java)
 
Semester 1, 2019-2020
 
1
 
Contents
 
1
.
 
Three Step GUI
2
.
 
Swing 
GUI
 Overview
3
.
 
Swing Hierarchy
4
.
 
Listener Interfaces
5
.
 
Button Example
6
.
 
TextField Example
7. 
 
Check Boxes Example
8.
 
Radio Buttons Example
9.
 
Combo Box Example
 
2
 
1
.  Three Step GUI
 
There are three main steps to creating a GUI for a
Java 
application
:
1
. Declare the GUI 
components
;
2
. Implement the 
event handlers
 for the 
components
;
3
. Position the 
components
 on the screen by using
layout managers
 and/or 
containers
.
 
this part
and
part 13
 
3
 
2
. Swing 
GUI
 Overview
 
T
he Swing 
GUI
 
has
 six categories:
basic 
components
uneditable displays
interactive displays of
highly formatted info
general-purpose
 containers
top-level containers
special-purpose
 containers
We will look at code
examples using the GUI
components listed in bold.
 
4
 
2.1
.  Basic Co
mponents
 
Component
          
Swing Class Name
button
  
JButton
, 
JCheckBox
, 
JRadioButton
combo box
 
JComboBox
list
  
JList
menu
  
JMenu, JMenuBar, JMenuItem
slider
  
JSlider
text field
 
JTextField
, JPasswordField
 
5
 
These pictures are from the Java tutorial on Swing
 
also known as
a pop-down list
 
6
 
2.2
.  Uneditable Displays
 
Display
                  
Swing Class Name
label
  
JLabel
Tooltip
  
JToolTip
Progress bar
 
JProgressBar
 
7
 
2
.
3
.  
Interactive
 Displays
 
Display
                  
Swing Class Name
table
  
JTable
text
  
JTextPane, JTextArea,
   
JEditorPane
tree
  
JColorChooser
file chooser
 
JFileChooser
 
8
 
9
 
2
.
4
.  
General Purpose
 Containers
 
Container
 
Swing Class Name
panel
  
JPanel
scroll pane
 
JScrollPane
, JScrollBar
split pane
 
JSplitPane
tabbed pane
 
JTabbedPane
toolbar
  
JToolbar
 
10
 
11
 
2
.
5
.  Top-level Containers
 
Container
 
Swing Class Name
frame
  
JFrame
applet
  
JApplet
dialog
  
JDialog, 
JOptionPane
 
12
 
13
 
2
.
6
.  
Special-Purpose
 Containers
 
Container
             
Swing Class Name
internal frame   
 
 
JInternalFrame
layered pane
  
JLayeredPane
root pane
  
JRootPane
 
14
 
15
 
extends
 
abstract
classes
 
AWT
classes
 
most of the examples in
part 12 come from here
 
16
 
What is JComponent?
 
JComponent
 is the 
Swing 
ancestor of most things
that appear 
in a GUI.
 
It holds common information such as:
size (preferred, minimum, maximum)
accessibility, internationalization
keyboard control support
thickness of lines around controls
debugging features
 
17
 
4.  Listener Interfaces
 
I'll look at 4 listener interfaces
 that can handle events
from different GUI components
ActionListener
ItemListener
MouseListener
MouseMotionListener
 
There are several other listener interfaces.
 
I'll use these two
in this part
 
in part 13
 
18
 
4.1
. ActionListener
 
ActionListener
 
can 
deal with events from:
JButton
        (most common)
JMenu
, 
JMenuItem
, 
JRadioButton
, 
JCheckBox
when pressed
JTextField
when 
<e
nter
> 
is typed
 
The interface has one method:
 
public void actionPerformed(ActionEvent e)
 
19
 
Using the Listener
 
The GUI 
component
 must be linked to code which
implements the method in the listener.
button
 
GUI Window
 
the link
which
sends an
event e
public class Foo 
implements
  
  ActionListener
{
  public void actionPerformed(
  
ActionEvent 
e
)
  { // do something with 
e
    System.out.println("Ouch");
  }
}
 
20
 
4
.
2
.  ItemListener
 
ItemListener can
 deal with events from:
JMenu
, 
JMenuItem
, 
JRadioButton
, 
JCheckBox
(most common)
JButton
when an item
 
is selected
/pressed
 
The interface has one method:
 
public void itemStateChanged(ItemEvent e)
 
21
 
Using the Listener
 
The GUI 
component
 must be linked to code which
implements the method in the listener.
 
GUI Window
 
the
 
link
which
sends an
event e
public class Foo2 
implements
  
  ItemListener
{
  public void itemStateChanged(
  
ItemEvent 
e
)
  { // do something with 
e
    System.out.println("EEEk");
  }
}
 
22
 
5. Button Example
 
Output after three presses:
 
Pressed 
1
Pressed 
2
Pressed 
3
 
23
 
Event Model
Press me
 
GUI
 
int pressCount = 1;
methods
actionPerfomed()
 
anon class
 
press
event
 
24
 
Steps in GUI Creation
 
The GUI is initialised in the class' constructor
method.
Initialisation steps:
1
. get the container for the frame
2
. set the layout manager (
FlowLayout
)
3
. declare the 
GUI components
4
. add them to the container
5
. register the 
components
 with event handlers
6
. set 
window properties
 
25
 
ButtonTest.java
 
 
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ButtonTest extends JFrame
{ 
  private 
int pressCount = 
1
;
   public ButtonTest
()
   {
      super( "Testing JButton" );
      Container c = getContentPane();
      c.setLayout( new FlowLayout() );
  
:
step 
1
step 
2
 
26
 
 
     
   
// JButton with a string argument
     
   
JButton jb = new JButton( "Press me" );
     
   
c.add( jb );
      // Handle events from pressing the button
 
  
jb.addActionListener
(
 
new ActionListener() {
 
    public void actionPerformed(ActionEvent e)
 
    {  System.out.println("Pressed " +
     
pressCount++ ); }
 
 
} );
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
 
  
    
pac
k();
;
      
setVisible(
 
true
 
);
   } // end of LabelTest()
step 
3
step 
4
step 
6
step 
5
 
27
 
 
 public static void main( String args[] )
   {
  n
ew ButtonTest(); }
} // end of ButtonTest class
 
28
 
Notes
 
The global variable 
pressCount
 remembers the
number of presses between calls to
actionPerformed()
.
 
The only information passed as an argument to
actionPerformed()
 is the event object 
e
other information 
must
 be stored globally
 
29
 
6. TextField Example
 
After typing enter, the text disappears from the
field, and "
You entered andrew
" 
 is printed
.
 
30
 
Event Model
 
GUI
 
methods
actionPerfomed()
 
anon class
 
type
enter
event
 
Enter...:
 
jtf
 
31
 
TextFieldTest.java
 
 
// The JTextField GUI in a Java app
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TextFieldTest extends JFrame
{
   private JTextField jtf;
 
// global since used in actionPerformed()
   public TextFieldTest()
   {
      super( "Testing JTextField" );
      Container c = getContentPane();
      c.setLayout( new FlowLayout() );
  
:
 
32
 
  
  // label and text entry field
      JLabel jl = new JLabel("Enter your name:");
 
  jtf  = new JTextField(
25
);  // 
25
 ch
ars
 wide
      c.add( jl );
 
  c.add( jtf );
      // Handle events from pressing return
 
  jtf.addActionListener(
 
new ActionListener() {
 
    public void actionPerformed(ActionEvent e)
 
    {  System.out.println("You entered " +
   
e.getActionCommand() );
 
       jtf.setTex
t(
""
)
;
    // clear text field
 
    
   }
         } );
     
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      
      
setSize(
500,100
);
     setVisible(true);
   } // end of TextFieldTest()
 
33
 
 
 public static void main( String args[] )
   { 
 
new TextFieldTest();
 
}
} // end of TextFieldTest class
 
34
 
Notes
 
The 
JTextField
 object, 
jtf
, is global
this means that 
actionPerformed()
 can affect it
it sets the text to empty (
""
) after printing a message to
stdout
 
The text inside the text field is accessed through the
event object:
e.getActionCommand()
 
35
 
7. Check Boxes Example
 
Output to
window
when first two
boxes are
checked/
unchecked
 
36
 
Event Model
 
GUI
 
methods
actionPerfomed()
 
anon classes
itemStateChanged()
 
select/
deselect
event
 
press
event
 
I could use
itemStateChanged()
to process all the events
 
37
 
Features
 
creates 
4
 
JCheckBox
 objects in an application
an anonymous class implements 
actionListener
actionPerformed()
 is called when the user presses  the
"Pepperoni" check box
an anonymous class implements 
itemListener
itemStateChanged()
 is called when the "Mushroom" box
is 'ticked' or 'unticked'
 
38
 
CheckBoxTest.java
 
 
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class CheckBoxTest extends JFrame
{
   public CheckBoxTest()
   {
      super( "Testing JCheckBox" );
      Container c = getContentPane();
      c.setLayout( new FlowLayout() );
  
:
 
39
 
 
      // 4 checkboxes
      JCheckBox jck
1
 = new JCheckBox("Pepperoni");
      JCheckBox jck
2
 = new JCheckBox("Mushroom");
      JCheckBox jck
3
 = new JCheckBox("Black olives");
      JCheckBox jck
4
 = new JCheckBox("Tomato");
      c.add( jck
1
 ); c.add( jck
2
 );
      c.add( jck
3
 ); c.add( jck
4
 );
      // actionListener for pepperoni box
      
    
jck
1
.addActionListener
( new ActionListener() {
        public void 
actionPerformed
(ActionEvent e)
        {  System.out.println("event = " + e); }
      
    });
  
:
 
40
 
        // itemListener for mushroom box
      
     
jck
2
.
addItemListener
( new ItemListener() {
         public void 
itemStateChanged
(ItemEvent e)
         {  if (
e.getStateChange()
 == e.SELECTED)
              System.out.print("selected ");
            else System.out.print("de-selected ");
            System.out.print("Mushroom\n");
         
      
}
 
  
  });
      
    
setDefaultCloseOperation(
    
JFrame.EXIT_ON_CLOSE);
      setSize(
500,100
);
      setVisible(true);
   } // end of CheckBoxTest()
 
41
 
 
   public static void main( String args[] )
   {  new CheckBoxTest();  }
} // end of CheckBoxTest class
 
42
 
Notes
 
addItemListener()
 is used to register an
ItemListener
 with a control.
 
The anonymous class must implement
ItemListener
's 
itemStateChanged()
 method.
 
itemStateChanged()
 uses 
e.getStateChanged()
to see if the box was ticked or unticked.
 
continued
 
43
 
actionPerformed()
 shows that an event object can
be printed
sometimes useful for debugging
 
44
 
8.  Radio Buttons Example
 
click on
radio buttons
 
45
 
Event Model
 
methods
Watch the font...
 
RadioButtonHandler
inner class
itemStateChanged(...)
{ // alter t
}
 
46
 
Features
 
creates 
four
 
JRadioButton
 objects in 
the
application
a 
RadioButtonHandler
 
inner 
class
 implements
ItemListener
itemStateChanged()
 is called when the user
selects/deselects any of the radio buttons
a 
ButtonGroup
 object which forces only one radio
button to be 'on' at a time
 
47
 
RadioButtonTest.java
 
 
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class RadioButtonTest extends JFrame
{
   private JTextField t;
   private Font plainFont, boldFont,
                italicFont, boldItalicFont;
   private JRadioButton plain, bold,
    
  italic, boldItalic;
  
:
 
48
 
 
   public RadioButtonTest()
   {  super( "RadioButton Test" );
      Container c = getContentPane();
      c.setLayout( new FlowLayout() );
      t = new JTextField(
  
    "Watch the font style change", 
25
 );
      c.add( t );
      // Create radio buttons
      plain = new JRadioButton( "Plain", true );
      c.add( plain );
      bold = new JRadioButton( "Bold", false);
      c.add( bold );
      italic = new JRadioButton( "Italic", false );
      c.add( italic );
      boldItalic = new JRadioButton(
     
"Bold/Italic", false );
      c.add( boldItalic );
  
:
 
49
 
 
      // register all controls with 1 handler
      
    
RadioButtonHandler handler =
   
new RadioButtonHandler();
      plain.addItemListener( handler );
      bold.addItemListener( handler );
      italic.addItemListener( handler );
      boldItalic.addItemListener( handler );
      // create link between JRadioButtons
      
    
ButtonGroup radioGroup = new ButtonGroup();
      radioGroup.add( plain );
      radioGroup.add( bold );
      radioGroup.add( italic );
      radioGroup.add( boldItalic );
  
:
 
50
 
 
  
 
 
  
plainFont = new Font( "TimesRoman", Font.PLAIN, 
14
 );
    boldFont = new Font( "TimesRoman", Font.BOLD, 
14
 
);
    italicFont = new Font( "TimesRoman",
 
Font.ITALIC, 
14
 
);
    boldItalicFont = new Font( "TimesRoman",
   
       
Font.BOLD + Font.ITALIC, 
14
 
);
    t.setFont( plainFont );
            :
 
51
 
       
    
setDefaultCloseOperation(
    
JFrame.EXIT_ON_CLOSE);
     setSize(
300,100
);
     setVisible(true);
   }
 // end of 
RadioButtonTest
()
  public static void main( String args[] )
  {  new RadioButtonTest()  }
 
52
 
 
  
  
 
class RadioButtonHandler
 
     
implements ItemListener
   
{
      public void itemStateChanged( ItemEvent e )
      
    
{
          if (e.getStateChange() == ItemEvent.SELECTED) {
         if ( 
e.getSource()
 == plain )
            t.setFont( plainFont );
         else if ( e.getSource() == bold )
            t.setFont( boldFont );
         else if ( e.getSource() == italic )
            t.setFont( italicFont );
         else if ( e.getSource() == boldItalic )
            t.setFont( boldItalicFont );
         
       
t.repaint();
          }
    
    }
  
  
 }
 // end of RadioButtonHandler class
}
 // end of RadioButtonTest class
Still inside
RadioButtonTest
 
53
 
Notes
 
This example shows the
 use of an inner class to
implement event handl
ing
:
RadioButtonHandler
 implements
ItemListener
 
The other two approaches:
anonymous class
es
have the program implement the event listener
 itself
 
continued
 
54
 
This example shows that several controls can have the
same event handler
all 
4
 buttons use a single  
RadioButtonHandler
object
The 
ButtonGroup
 object is not visible on the screen.
 
55
 
9.  Combo Box Example
 
select
travelbug.gif
 
56
 
Event Model
 
methods
 
anon class
itemStateChanged()
 
select
item
event
 
57
 
Features
 
creates a 
JComboBox
 object in an application
(a combo box is a 
drop-down list
)
the selection updates an 
image
 inside a label
an anonymous class implements 
itemListener
itemStateChanged()
 is called when the user clicks on
one of the items on the list
 
58
 
ComboBoxTest.java
 
 
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ComboBoxTest extends JFrame
{
   private JComboBox
<String>
 
imNmsList
;
   private JLabel label;
   private String names[] =
     
      
 
{ "
bug
1
.gif
",
 
 
"bug
2
.gif
",
        
       "
travelbug.gif
",
 
"
buganim.gif
" };
   
  
private I
mageI
con icons
[];
  
:
 
59
 
  public ComboBoxTest()
  {
    super("Testing JComboBox");
 
    icons = new Icon[names.length];
    for(int i=0; i < names.length; i++)
      icons[i] = new ImageIcon(names[i]);
 
    Container c = getContentPane();
    c.setLayout(new FlowLayout());
 
    label = new JLabel(icons[0]);
    c.add(label);
            :
 
60
 
    
imNmsList = new JComboBox<String>(names);
    
imNmsList.setMaximumRowCount(3);
    c.add(imNmsList);
    imNmsList.addItemListener( 
new ItemListener()
 {
      public void 
itemStateChanged
(ItemEvent e)
      { label.setIcon(icons[ imNmsList.getSelectedIndex() ]); }
    });
 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(350, 100);
    setVisible(true);
  }  // end of ComboBoxTest()
 
  public static void main(String args[])
  { new ComboBoxTest();  }
}  // end of ComboBoxTest class
 
 
61
 
Notes
 
itemStateChanged()
 does not use the 
e
 event
object; it checks the 
imNmsList
 combo box
imNmsList
.getSelectedIndex()
returns the index of the item selected
 
The 
image
 filenames are stored in an 
icon[]
array,
and used to update the label:
label.setIcon( icon[...])
 
62
Slide Note
Embed
Share

Explore the different GUI controls in Java programming, including buttons, text fields, checkboxes, radio buttons, combo boxes, and more. Learn about the three main steps in creating a GUI, the Swing GUI overview, and various categories of Swing components with code examples.

  • Java
  • GUI controls
  • Swing
  • programming
  • user interface

Uploaded on Sep 12, 2024 | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. Download presentation by click this link. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

E N D

Presentation Transcript


  1. DIN61-222 Adv. Prog. (Java) Semester 1, 2019-2020 12. GUI Examples I Objectives describe some of the GUI controls and their listeners; more appear in part 13 1

  2. Contents 1. 2. 3. 4. 5. 6. 7. 8. 9. Three Step GUI Swing GUI Overview Swing Hierarchy Listener Interfaces Button Example TextField Example Check Boxes Example Radio Buttons Example Combo Box Example 2

  3. 1. Three Step GUI There are three main steps to creating a GUI for a Java application: 1. Declare the GUI components; this part and part 13 2. Implement the event handlers for the components; 3. Position the components on the screen by using layout managers and/or containers. 3

  4. 2. Swing GUI Overview The Swing GUIhas six categories: basic components uneditable displays We will look at code examples using the GUI components listed in bold. interactive displays of highly formatted info general-purpose containers top-level containers special-purpose containers 4

  5. 2.1. Basic Components Component Swing Class Name JButton, JCheckBox, JRadioButton JComboBox JList JMenu, JMenuBar, JMenuItem JSlider button combo box list menu slider text field JTextField, JPasswordField 5

  6. also known as a pop-down list These pictures are from the Java tutorial on Swing 6

  7. 2.2. Uneditable Displays Display Swing Class Name JLabel JToolTip JProgressBar label Tooltip Progress bar 7

  8. 2.3. Interactive Displays Display Swing Class Name JTable JTextPane, JTextArea, JEditorPane JColorChooser JFileChooser table text tree file chooser 8

  9. 9

  10. 2.4. General Purpose Containers Container Swing Class Name panel JPanel JScrollPane, JScrollBar JSplitPane scroll pane split pane tabbed pane toolbar JTabbedPane JToolbar 10

  11. 11

  12. 2.5. Top-level Containers Container Swing Class Name frame JFrame JApplet JDialog, JOptionPane applet dialog 12

  13. 13

  14. 2.6. Special-Purpose Containers Container Swing Class Name JInternalFrame JLayeredPane JRootPane internal frame layered pane root pane 14

  15. 15

  16. 3. Swing Hierarchy (partial) AWT classes extends abstract classes most of the examples in part 12 come from here 16

  17. What is JComponent? JComponent is the Swing ancestor of most things that appear in a GUI. It holds common information such as: size (preferred, minimum, maximum) accessibility, internationalization keyboard control support thickness of lines around controls debugging features 17

  18. 4. Listener Interfaces I'll look at 4 listener interfaces that can handle events from different GUI components ActionListener ItemListener MouseListener MouseMotionListener I'll use these two in this part in part 13 There are several other listener interfaces. 18

  19. 4.1. ActionListener ActionListenercan deal with events from: JButton (most common) JMenu, JMenuItem, JRadioButton, JCheckBox when pressed JTextField when <enter> is typed The interface has one method: public void actionPerformed(ActionEvent e) 19

  20. Using the Listener The GUI component must be linked to code which implements the method in the listener. public class Foo implements ActionListener { public void actionPerformed( ActionEvent e) { // do something with e System.out.println("Ouch"); } } button the link which sends an event e GUI Window 20

  21. 4.2. ItemListener ItemListener can deal with events from: JMenu, JMenuItem, JRadioButton, JCheckBox (most common) JButton when an item is selected/pressed The interface has one method: public void itemStateChanged(ItemEvent e) 21

  22. Using the Listener The GUI component must be linked to code which implements the method in the listener. public class Foo2 implements ItemListener { public void itemStateChanged( ItemEvent e) { // do something with e System.out.println("EEEk"); } } menu the link which sends an event e GUI Window 22

  23. 5. Button Example Output after three presses: Pressed 1 Pressed 2 Pressed 3 23

  24. Event Model GUI Press me int pressCount = 1; methods press event actionPerfomed() anon class 24

  25. Steps in GUI Creation The GUI is initialised in the class' constructor method. Initialisation steps: 1. get the container for the frame 2. set the layout manager (FlowLayout) 3. declare the GUI components 4. add them to the container 5. register the components with event handlers 6. set window properties 25

  26. ButtonTest.java import javax.swing.*; import java.awt.*; import java.awt.event.*; public class ButtonTest extends JFrame { private int pressCount = 1; public ButtonTest() { super( "Testing JButton" ); step 1 Container c = getContentPane(); c.setLayout( new FlowLayout() ); : step 2 26

  27. // JButton with a string argument JButton jb = new JButton( "Press me" ); c.add( jb ); step 3 step 4 // Handle events from pressing the button jb.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("Pressed " + } ); pressCount++ ); } step 5 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack();; setVisible( true ); } // end of LabelTest() step 6 27

  28. public static void main( String args[] ) { new ButtonTest(); } } // end of ButtonTest class 28

  29. Notes The global variable pressCount remembers the number of presses between calls to actionPerformed(). The only information passed as an argument to actionPerformed() is the event object e other information must be stored globally 29

  30. 6. TextField Example After typing enter, the text disappears from the field, and "You entered andrew" is printed. 30

  31. Event Model GUI Enter...: jtf methods type enter event actionPerfomed() anon class 31

  32. TextFieldTest.java // The JTextField GUI in a Java app import javax.swing.*; import java.awt.*; import java.awt.event.*; public class TextFieldTest extends JFrame { private JTextField jtf; // global since used in actionPerformed() public TextFieldTest() { super( "Testing JTextField" ); Container c = getContentPane(); c.setLayout( new FlowLayout() ); : 32

  33. JLabel jl = new JLabel("Enter your name:"); jtf = new JTextField(25); // 25 chars wide c.add( jl ); c.add( jtf ); // label and text entry field // Handle events from pressing return jtf.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("You entered " + e.getActionCommand() ); jtf.setText(""); } } ); // clear text field setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(500,100); setVisible(true); } // end of TextFieldTest() 33

  34. public static void main( String args[] ) { new TextFieldTest(); } } // end of TextFieldTest class 34

  35. Notes The JTextField object, jtf, is global this means that actionPerformed() can affect it it sets the text to empty ("") after printing a message to stdout The text inside the text field is accessed through the event object: e.getActionCommand() 35

  36. 7. Check Boxes Example Output to window when first two boxes are checked/ unchecked 36

  37. Event Model GUI methods press event actionPerfomed() select/ deselect event itemStateChanged() I could use itemStateChanged() to process all the events anon classes 37

  38. Features creates 4JCheckBox objects in an application an anonymous class implements actionListener actionPerformed() is called when the user presses the "Pepperoni" check box an anonymous class implements itemListener itemStateChanged() is called when the "Mushroom" box is 'ticked' or 'unticked' 38

  39. CheckBoxTest.java import javax.swing.*; import java.awt.*; import java.awt.event.*; public class CheckBoxTest extends JFrame { public CheckBoxTest() { super( "Testing JCheckBox" ); Container c = getContentPane(); c.setLayout( new FlowLayout() ); : 39

  40. // 4 checkboxes JCheckBox jck1 = new JCheckBox("Pepperoni"); JCheckBox jck2 = new JCheckBox("Mushroom"); JCheckBox jck3 = new JCheckBox("Black olives"); JCheckBox jck4 = new JCheckBox("Tomato"); c.add( jck1 ); c.add( jck2 ); c.add( jck3 ); c.add( jck4 ); // actionListener for pepperoni box jck1.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("event = " + e); } }); : 40

  41. // itemListener for mushroom box jck2.addItemListener( new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == e.SELECTED) System.out.print("selected "); else System.out.print("de-selected "); System.out.print("Mushroom\n"); } }); setSize(500,100); setVisible(true); } // end of CheckBoxTest() setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); 41

  42. public static void main( String args[] ) { new CheckBoxTest(); } } // end of CheckBoxTest class 42

  43. Notes addItemListener() is used to register an ItemListener with a control. The anonymous class must implement ItemListener's itemStateChanged() method. itemStateChanged() uses e.getStateChanged() to see if the box was ticked or unticked. continued 43

  44. actionPerformed() shows that an event object can be printed sometimes useful for debugging 44

  45. 8. Radio Buttons Example click on radio buttons 45

  46. Event Model Watch the font... methods RadioButtonHandler inner class itemStateChanged(...) { // alter t } 46

  47. Features creates fourJRadioButton objects in the application a RadioButtonHandlerinner class implements ItemListener itemStateChanged() is called when the user selects/deselects any of the radio buttons a ButtonGroup object which forces only one radio button to be 'on' at a time 47

  48. RadioButtonTest.java import java.awt.*; import java.awt.event.*; import javax.swing.*; public class RadioButtonTest extends JFrame { private JTextField t; private Font plainFont, boldFont, italicFont, boldItalicFont; private JRadioButton plain, bold, : italic, boldItalic; 48

  49. public RadioButtonTest() { super( "RadioButton Test" ); Container c = getContentPane(); c.setLayout( new FlowLayout() ); t = new JTextField( "Watch the font style change", 25 ); c.add( t ); // Create radio buttons plain = new JRadioButton( "Plain", true ); c.add( plain ); bold = new JRadioButton( "Bold", false); c.add( bold ); italic = new JRadioButton( "Italic", false ); c.add( italic ); boldItalic = new JRadioButton( c.add( boldItalic ); : "Bold/Italic", false ); 49

  50. // register all controls with 1 handler RadioButtonHandler handler = new RadioButtonHandler(); plain.addItemListener( handler ); bold.addItemListener( handler ); italic.addItemListener( handler ); boldItalic.addItemListener( handler ); // create link between JRadioButtons ButtonGroup radioGroup = new ButtonGroup(); radioGroup.add( plain ); radioGroup.add( bold ); radioGroup.add( italic ); radioGroup.add( boldItalic ); : 50

More Related Content

giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#