Chapter 14
Download
1 / 86

Chapter 14 - PowerPoint PPT Presentation


  • 73 Views
  • Uploaded on

Chapter 14. More Swing Objects. Menus Making GUIs Pretty (and More Functional) Box Containers and Box Layout Managers More on Events and Listeners Another Look at the Swing Class Hierarchy. AbstractButton. JMenuItem. JButton. JMenu. Menus.

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about ' Chapter 14' - nedaa


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
Chapter 14

Chapter 14

More Swing Objects

Menus

Making GUIs Pretty (and More Functional)

Box Containers and Box Layout Managers

More on Events and Listeners

Another Look at the Swing Class Hierarchy


Menus

AbstractButton

JMenuItem

JButton

JMenu

Menus

  • Three Swing classes used to put a menu in a program:

    • JMenuBar

    • JMenu

    • JMenuItem

  • Menu items behave in the same way as buttons


A gui with a menu
A GUI witha Menu

JMenu memoMenu = new JMenu("Memos");

JMenuItem m;

m = new JMenuItem("Save Memo 1");

m.addActionListener(this);

memoMenu.add(m);

m = new JMenuItem("Save Memo 2");

m.addActionListener(this);

memoMenu.add(m);

. . .

JMenuBar mBar = new JMenuBar();

mBar.add(memoMenu);

setJMenuBar(mBar);

Create a menu

Create a menu item

A menu item uses an action listener the same way a button does.


A gui with a menu1
A GUI witha Menu

JMenu memoMenu = new JMenu("Memos");

JMenuItem m;

m = new JMenuItem("Save Memo 1");

m.addActionListener(this);

memoMenu.add(m);

m = new JMenuItem("Save Memo 2");

m.addActionListener(this);

memoMenu.add(m);

. . .

JMenuBar mBar = new JMenuBar();

mBar.add(memoMenu);

setJMenuBar(mBar);

Each menu item is added to the menu.

The menu is added to the menu bar.

One way to add a menu bar to a JFrame


Display 14.1

GUI with a Menu (1/4)

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class MemoGUI extends JFrame implements ActionListener

{

public static final int WIDTH = 600;

public static final int HEIGHT = 300;

public static final int LINES = 10;

public static final int CHAR_PER_LINE = 40;

private JTextArea theText;

private String memo1 = "No Memo 1.";

private String memo2 = "No Memo 2.";


Display 14.1

GUI with a Menu (2/4)

public MemoGUI()

{

setSize(WIDTH, HEIGHT);

addWindowListener(new WindowDestroyer());

setTitle("Memo Saver");

Container contentPane = getContentPane();

contentPane.setLayout(new BorderLayout());

JMenu memoMenu = new JMenu("Memos");

JMenuItem m;

m = new JMenuItem("Save Memo 1");

m.addActionListener(this);

memoMenu.add(m);

m = new JMenuItem("Save Memo 2");

m.addActionListener(this);

memoMenu.add(m);

m = new JMenuItem("Get Memo 1");

m.addActionListener(this);

memoMenu.add(m);


Display 14.1

GUI with a Menu (3/4)

m = new JMenuItem("Get Memo 2");

m.addActionListener(this);

memoMenu.add(m);

m = new JMenuItem("Clear");

m.addActionListener(this);

memoMenu.add(m);

m = new JMenuItem("Exit");

m.addActionListener(this);

memoMenu.add(m);

JMenuBar mBar = new JMenuBar();

mBar.add(memoMenu);

setJMenuBar(mBar);

JPanel textPanel = new JPanel();

textPanel.setBackground(Color.blue);

theText = new JTextArea(LINES, CHAR_PER_LINE);

theText.setBackground(Color.white);

textPanel.add(theText);

contentPane.add(textPanel, BorderLayout.CENTER);

}


public void actionPerformed(ActionEvent e)

{

String actionCommand = e.getActionCommand();

if (actionCommand.equals("Save Memo 1"))

memo1 = theText.getText();

else if (actionCommand.equals("Save Memo 2"))

memo2 = theText.getText();

else if (actionCommand.equals("Clear"))

theText.setText("");

else if (actionCommand.equals("Get Memo 1"))

theText.setText(memo1);

else if (actionCommand.equals("Get Memo 2"))

theText.setText(memo2);

else if (actionCommand.equals("Exit"))

System.exit(0);

else

theText.setText("Error in memo interface");

}

public static void main(String[] args)

{

MemoGUI gui = new MemoGUI();

gui.setVisible(true);

}

}

Display 14.1

GUI with a Menu (4/4)


Nested menus

AbstractButton

JMenuItem

JButton

JMenu

Nested Menus

  • JMenu is a descendant of JMenuItem

  • Every JMenu object is also a JMenuItem

  • A JMenu can be a menu item in another menu

  • This allows nested menus

  • Clicking on a nested menu shows the items in the nested menu and allows them to be selected.


Making guis pretty and more functional
Making GUIs Pretty(and More Functional)

  • Adding Icons

  • The JScrollPane Class for Scroll Bars

  • Adding Borders

  • Changing the Look and Feel


Using icons
Using Icons

  • Icons are (small) pictures

  • Icons may be added to labels, buttons, and menu items.

  • The ImageIcon class can be used to convert a picture to an icon:

    ImageIcon SmileyFaceIcon = new ImageIcon(“smiley.gif”);

  • The setIcon method can be used to add an icon to a component:

    JLabel helloLabel = new JLabel(“Hello”);

    ImageIcon dukeWavingIcon =

    new ImageIcon(“duke_waving.gif”);

    helloLabel.setIcon(dukeWavingIcon);


Display 14.2

Using Icons (1/4)

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class IconDemo extends JFrame implements ActionListener

{

public static final int WIDTH = 400;

public static final int HEIGHT = 200;

private JTextField message;


Display 14.2

Using Icons (2/4)

public IconDemo()

{

setSize(WIDTH, HEIGHT);

addWindowListener(new WindowDestroyer());

setTitle("Icon Demonstration");

Container content = getContentPane();

content.setBackground(Color.white);

content.setLayout(new BorderLayout());

JLabel niceLabel = new JLabel("Nice day!");

ImageIcon smileyIcon = new ImageIcon("smiley.gif");

niceLabel.setIcon(smileyIcon);

content.add(niceLabel, BorderLayout.NORTH);


Display 14.2

Using Icons (3/4)

JPanel buttonPanel = new JPanel();

buttonPanel.setLayout(new FlowLayout());

JButton helloButton = new JButton("Hello");

ImageIcon dukeWavingIcon = new ImageIcon("duke_waving.gif");

helloButton.setIcon(dukeWavingIcon);

helloButton.addActionListener(this);

buttonPanel.add(helloButton);

JButton byeButton = new JButton("Good bye");

ImageIcon dukeStandingIcon =

new ImageIcon("duke_standing.gif");

byeButton.setIcon(dukeStandingIcon);

byeButton.addActionListener(this);

buttonPanel.add(byeButton);

content.add(buttonPanel, BorderLayout.SOUTH);

message = new JTextField(30);

content.add(message, BorderLayout.CENTER);

}


Display 14.2

Using Icons (4/4)

public void actionPerformed(ActionEvent e)

{

if (e.getActionCommand().equals("Hello"))

message.setText("Glad to meet you!");

else if (e.getActionCommand().equals("Good bye"))

message.setText(

"OK, click the upper right button. I'll miss you.");

else

System.out.println("Error in button interface.");

}

public static void main(String[] args)

{

IconDemo iconGui = new IconDemo();

iconGui.setVisible(true);

}

}


Some methods in the classes jbutton and jlabel 1 3
Some Methods in the ClassesJbutton and Jlabel (1/3)

  • public JButton(), public JLabel()

    - Creates a button or label with no text or icon on it.

    - You will later use setText and setIcon with the button or menu item.

  • public JButton(String text)

  • public JLabel(String text)

    - Creates a button or label with the text on it.

  • public JButton(ImageIcon picture)

  • public JLabel(ImageIcon picture)

    - Creates a button or label with the icon picture on it.

  • public JButton(String text, ImageIcon picture)

  • public JLabel(String text, ImageIcon picture,

    int horizontalAlignment)

    - Creates a button or label with both the text and the icon picture on it.

    - horizontalAlignment is one of the constants SwingConstants.LEFT, SwingConstants.CENTER, SwingConstants.RIGHT, SwingConstants.LEADING, or SwingConstants.TRAILING.


Some methods in the classes jbutton and jlabel 2 3
Some Methods in the ClassesJbutton and Jlabel (2/3)

  • public void setText(String text)

    - Makes text the only text on the button or label.

  • public void setIcon(ImageIcon picture)

    - Makes picture the only icon on the button or label.

  • public void setMargin(Insets margin)

    - JButton has the method setMargin, but JLabel does not.

    - The method setMargin sets the size of the margin around the text and icon in the button.

    - public void setMargin(new Insets(int top, int left,

    int bottom, int right))

  • public void setPreferredSize(

    Dimension preferredSize)

    - Sets the preferred size. The layout manager is not required to use the preferred size.

    - public void setPreferredSize(new Dimension(int width,

    int height))


Some methods in the classes jbutton and jlabel 3 3
Some Methods in the ClassesJbutton and Jlabel (3/3)

  • public void setMaximumSize(Dimension maximumSize)

    - Sets the maximum size.

    - public void setMaximumSize(new Dimension(int width,

    int height))

  • public void setMinimumSize(Dimension minimumSize)

    - Sets the minimum size.

    - public void setMinimumSize(new Dimension(int width,

    int height))

  • public void setVerticalTextPosition(int textPosition)

    - Sets the vertical position of the text relative to the icon.

    - The textPosition should be one of the constants SwingConstants.TOP, SwingConstants.CENTER or SwingConstants.BOTTOM.

  • public void setHorizontalTextPosition(int textPosition)

    - Sets the horizontal position of the text relative to the icon.

    - The textPosition should be one of the constants SwingConstants.RIGHT, SwingConstants.LEFT, SwingConstants.CENTER, or SwingConstants.LEADING, SwingConstants.TRAILING.


The jscrollpane class for scroll bars
The JScrollPane Class for Scroll Bars

  • A view port is used when not all information can be displayed on screen at once.

  • Scroll bars move a view port around to show different parts of the information.

  • JScrollPane is a class that can provide a view port with scroll bars.

  • An example using JScrollPane with a JTextArea called theText and a JPanel called textPanel:

    JScrollPane scrolledText = new JScrollPane(theText);

    textPanel.add(scrolledText);



Some methods and constants in the class jscrollpane
Some Methods and Constantsin the Class JScrollPane

  • public JScrollPane(Component objectToBeScrolled)

    - Creates a new JScrollPane for the objectToBeScrolled.

  • public void setHorizontalScrollBarPolicy(int policy)

    - Sets the policy for showing the horizontal scroll bar.

    - The policy should be one of JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS

    JScrollPane.HORIZONTAL_SCROLLBAR_NEVER

    JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED

  • public void setVerticalScrollBarPolicy(int policy)

    - Sets the policy for showing the vertical scroll bar.

  • JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED

  • JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED

    - Constants in the class JScrollPane.

    - The phrase “AS_NEEDED” means the scroll bar is only shown when it is needed.


Display 14.5

TextArea with

Scroll Bars(1/4)

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class ScrollBarDemo extends JFrame implements ActionListener

{

public static final int WIDTH = 600;

public static final int HEIGHT = 300;

public static final int LINES = 10;

public static final int CHAR_PER_LINE = 40;

private JTextArea theText;

private String memo1 = "No Memo 1.";

private String memo2 = "No Memo 2.";


Display 14.5

TextArea with

Scroll Bars(2/4)

public ScrollBarDemo()

{

setSize(WIDTH, HEIGHT);

addWindowListener(new WindowDestroyer());

setTitle("Scrolling Memo Saver");

Container contentPane = getContentPane();

contentPane.setLayout(new BorderLayout());

JMenu memoMenu = new JMenu("Memos");

JMenuItem m;

m = new JMenuItem("Save Memo 1");

m.addActionListener(this);

memoMenu.add(m);

m = new JMenuItem("Save Memo 2");

m.addActionListener(this);

memoMenu.add(m);

m = new JMenuItem("Get Memo 1");

m.addActionListener(this);

memoMenu.add(m);


Display 14.5

TextArea with

Scroll Bars(3/4)

m = new JMenuItem("Get Memo 2");

m.addActionListener(this);

memoMenu.add(m);

m = new JMenuItem("Clear");

m.addActionListener(this);

memoMenu.add(m);

m = new JMenuItem("Exit");

m.addActionListener(this);

memoMenu.add(m);

JMenuBar mBar = new JMenuBar();

mBar.add(memoMenu);

setJMenuBar(mBar);

JPanel textPanel = new JPanel();

textPanel.setBackground(Color.blue);

theText = new JTextArea(LINES, CHAR_PER_LINE);

theText.setBackground(Color.white);

JScrollPane scrolledText = new JScrollPane(theText);

scrolledText.setHorizontalScrollBarPolicy(

JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

scrolledText.setVerticalScrollBarPolicy(

JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

textPanel.add(scrolledText);

contentPane.add(textPanel, BorderLayout.CENTER);

}


public void actionPerformed(ActionEvent e)

{

String actionCommand = e.getActionCommand();

if (actionCommand.equals("Save Memo 1"))

memo1 = theText.getText();

else if (actionCommand.equals("Save Memo 2"))

memo2 = theText.getText();

else if (actionCommand.equals("Clear"))

theText.setText("");

else if (actionCommand.equals("Get Memo 1"))

theText.setText(memo1);

else if (actionCommand.equals("Get Memo 2"))

theText.setText(memo2);

else if (actionCommand.equals("Exit"))

System.exit(0);

else

theText.setText("Error in memo interface");

}

public static void main(String[] args)

{

ScrollBarDemo guiMemo = new ScrollBarDemo();

guiMemo.setVisible(true);

}

}

Display 14.5

TextArea with

Scroll Bars(4/4)


Execution result of scrollbardemo java
Execution Result ofScrollBarDemo.java


Adding borders

testButton.setBorder(new BevelBorder(BevelBorder.LOWERED));

Adding Borders

  • A border is an area that frames a component.

  • Swing provides several different types of borders:

    • BevelBorder—makes component look raised or lowered

    • EtchedBorder—similar to BevelBorder but can’t set size

    • EmptyBorder—extra space around the component

    • LineBorder—colored border of a given thickness

    • MatteBorder—similar to LineBorder but can adjust thickness on each side of the component

  • An example of adding a bevel border to a button:


Display 14.7

Different Borders

(1/4)

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

import javax.swing.border.*;

public class BorderDemo extends JFrame implements ActionListener

{

public static final int WIDTH = 400;

public static final int HEIGHT = 300;

private JTextField name;


Display 14.7

Different Borders

(2/4)

public BorderDemo()

{

setTitle("Name Tester with Borders");

setSize(WIDTH, HEIGHT);

addWindowListener(new WindowDestroyer());

Container content = getContentPane();

content.setLayout(new GridLayout(2, 1));

JPanel namePanel = new JPanel();

namePanel.setLayout(new BorderLayout());

namePanel.setBackground(Color.white);

name = new JTextField(20);

//The following border is not as dramatic as others,

//but look closely and you will see it.

name.setBorder(new EtchedBorder(Color.green, Color.blue));

namePanel.add(name, BorderLayout.SOUTH);

JLabel nameLabel = new JLabel("Enter your name here:");

//The following does insert space around the label.

//To see the difference, comment out the following line:

nameLabel.setBorder(new EmptyBorder(20, 10, 0, 0));

namePanel.add(nameLabel, BorderLayout.CENTER);


Display 14.7

Different Borders

(3/4)

namePanel.setBorder(new LineBorder(Color.black, 10));

content.add(namePanel);

JPanel buttonPanel = new JPanel();

buttonPanel.setLayout(new FlowLayout());

JButton testButton = new JButton("Test");

testButton.addActionListener(this);

testButton.setBorder(

new BevelBorder(BevelBorder.LOWERED));

buttonPanel.add(testButton);

JButton clearButton = new JButton("Clear");

clearButton.addActionListener(this);

clearButton.setBorder(

new BevelBorder(BevelBorder.RAISED));

buttonPanel.add(clearButton);

buttonPanel.setBorder(

new MatteBorder(60, 40, 30, 20, Color.pink));

content.add(buttonPanel);

}


Display 14.7

Different Borders

(4/4)

public void actionPerformed(ActionEvent e)

{

if (e.getActionCommand().equals("Test"))

name.setText("A very good name!");

else if (e.getActionCommand().equals("Clear"))

name.setText("");

else

name.setText("Error in window interface.");

}

public static void main(String[] args)

{

BorderDemo w = new BorderDemo();

w.setVisible(true);

}

}


Execution result of borderdemo java
Execution Result ofBorderDemo.java


Changing the look and feel
Changing the Look and Feel

  • Look and feel refers to the general appearance of the GUI, including:

    • Shape and exact placement of buttons

    • Default colors

  • Three standard choices for look and feel:

    • Metal—considered the standard Java look and feel

    • Motif—often considered the standard Unix look and feel

    • Windows—looks like the windows you get with the Windows operating system

  • A Macintosh look and feel is also available


Class names for three looks and feels
Class Names forThree Looks and Feels

  • Metal

    - “javax.swing.plaf.metal.MetalLookAndFeel”

  • Motif

    - “com.sun.java.swing.plaf.motif.MotifLookAndFeel”

  • Windows

    - “com.sun.java.swing.plaf.windows.

    WindowsLookAndFeel”


An example of changing the look and feel of a gui
An Example of Changing the Look and Feel of a GUI

try

{

UIManager.setLookAndFeel(

“com.sun.java.swing.plaf.motif.MotifLookAndFeel”);

SwingUtilities.updateComponentTreeUI(this);

}

catch (Exception e)

{

System.out.println(

“Could not load the Motif look and feel”);

}

Fully qualified class name— includes directory path

Try and catch necessary because any one of four exceptions could be thrown


Display 14.11

Looks and Feels

(1/3)

import javax.swing.*;

import java.awt.*;

public class LookNFeelSample extends JFrame

{

public static final int WIDTH = 300;

public static final int HEIGHT = 200;


Display 14.11

Looks and Feels

(2/3)

public LookNFeelSample(String lookNFeelClassName, String title)

{

setSize(WIDTH, HEIGHT);

addWindowListener(new WindowDestroyer());

setTitle(title);

Container content = getContentPane();

content.setLayout(new FlowLayout());

JButton aButton = new JButton("A Button");

content.add(aButton);

JLabel aLabel = new JLabel("This is a label.");

content.add(aLabel);

try

{

UIManager.setLookAndFeel(lookNFeelClassName);

SwingUtilities.updateComponentTreeUI(this);

}

catch (Exception e)

{

System.out.println("Look and feel problem.");

}

}


Display 14.11

Looks and Feels

(3/3)

public static void main(String[] args)

{

LookNFeelSample metalGUI = new LookNFeelSample(

"javax.swing.plaf.metal.MetalLookAndFeel",

"Metal Look and Feel");

metalGUI.setVisible(true);

LookNFeelSample motifGUI = new LookNFeelSample(

"com.sun.java.swing.plaf.motif.MotifLookAndFeel",

"Motif Look and Feel");

motifGUI.setVisible(true);

LookNFeelSample windowsGUI = new LookNFeelSample(

"com.sun.java.swing.plaf.windows.WindowsLookAndFeel",

"Windows Look and Feel");

windowsGUI.setVisible(true);

}

}


Execution result of looknfeelsample java
Execution Result ofLookNFeelSample.java


Box layout manager
Box Layout Manager

  • Useful for a single column or single row of components

  • Specify X_AXIS (horizontal) or Y_AXIS (vertical) layout as second parameter to constructor for layout manager

  • Provides a means of separating components in a row or column

    • Strut—allocates a fixed amount of space between two components

    • Glue—allocates a variable amount of space between two components

  • A Box container is a container that is automatically given a BoxLayout manager.


Box layout versus other layouts
Box Layout Versus Other Layouts

  • Horizontal box layout is similar to flow layout.

  • Vertical box layout is similar to grid layout with only one column.

  • Big advantage of box layout is control over spacing using struts and glue.

  • Note that struts and glue should not be used with other layout managers.


Box layout demo program
Box Layout Demo Program

Specifies a horizontal layout

JPanel horizontalPanel = new JPanel();

horizontalPanel.setLayout(

new BoxLayout(horizontalPanel, BoxLayout.X_AXIS));

Component horizontalStrut =

Box.createHorizontalStrut(HORIZONTAL_STRUT_SIZE);

horizontalPanel.add(horizontalStrut);

JButton hStopButton = new JButton("Red");

hStopButton.addActionListener(this);

horizontalPanel.add(hStopButton);

Static method in Box class used to create a strut of a particular size for spacing


Display 14.13

BoxLayout

(1/5)

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class BoxLayoutDemo extends Jframe implements ActionListener

{

public static final int WIDTH = 300;

public static final int HEIGHT = 200;

public static final int HORIZONTAL_STRUT_SIZE = 15;

public static final int VERTICAL_STRUT_SIZE = 10;

private JPanel colorPanel;


Display 14.13

BoxLayout

(2/5)

public BoxLayoutDemo()

{

setSize(WIDTH, HEIGHT);

addWindowListener(new WindowDestroyer());

setTitle("Box Demonstration");

Container content = getContentPane();

content.setLayout(new BorderLayout());

colorPanel = new JPanel();

colorPanel.setBackground(Color.blue);

content.add(colorPanel, BorderLayout.CENTER);

//Horizontal buttons at bottom of frame:

JPanel horizontalPanel = new JPanel();

horizontalPanel.setLayout(

new BoxLayout(horizontalPanel, BoxLayout.X_AXIS));

Component horizontalStrut = Box.createHorizontalStrut(HORIZONTAL_STRUT_SIZE);

horizontalPanel.add(horizontalStrut);


Display 14.13

BoxLayout

(3/5)

JButton hStopButton = new JButton("Red");

hStopButton.addActionListener(this);

horizontalPanel.add(hStopButton);

Component horizontalStrut2 = Box.createHorizontalStrut(HORIZONTAL_STRUT_SIZE);

horizontalPanel.add(horizontalStrut2);

JButton hGoButton = new JButton("Green");

hGoButton.addActionListener(this);

horizontalPanel.add(hGoButton);

content.add(horizontalPanel, BorderLayout.SOUTH);

//Vertical buttons on right side of frame:

JPanel verticalPanel = new JPanel();

verticalPanel.setLayout(

new BoxLayout(verticalPanel, BoxLayout.Y_AXIS));

Component verticalStrut =

Box.createVerticalStrut(VERTICAL_STRUT_SIZE);

verticalPanel.add(verticalStrut);


Display 14.13

BoxLayout

(4/5)

JButton vStopButton = new JButton("Red");

vStopButton.addActionListener(this);

verticalPanel.add(vStopButton);

Component verticalStrut2 =

Box.createVerticalStrut(VERTICAL_STRUT_SIZE);

verticalPanel.add(verticalStrut2);

JButton vGoButton = new JButton("Green");

vGoButton.addActionListener(this);

verticalPanel.add(vGoButton);

content.add(verticalPanel, BorderLayout.EAST);

}


Display 14.13

BoxLayout

(5/5)

public void actionPerformed(ActionEvent e)

{

if (e.getActionCommand().equals("Red"))

colorPanel.setBackground(Color.red);

else if (e.getActionCommand().equals("Green"))

colorPanel.setBackground(Color.green);

else

System.out.println("Error in button interface.");

}

public static void main(String[] args)

{

BoxLayoutDemo gui = new BoxLayoutDemo();

gui.setVisible(true);

}

}


Execution result of boxlayoutdemo java
Execution Result ofBoxLayoutDemo.java


Display 14.14

Box Container Class

(1/4)

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class BoxClassDemo extends JFrame implements ActionListener

{

public static final int WIDTH = 300;

public static final int HEIGHT = 200;

public static final int HORIZONTAL_STRUT_SIZE = 15;

public static final int VERTICAL_STRUT_SIZE = 10;

private JPanel colorPanel;


Display 14.14

Box Container Class

(2/4)

public BoxClassDemo()

{

setSize(WIDTH, HEIGHT);

addWindowListener(new WindowDestroyer());

setTitle("Box Demonstration");

Container content = getContentPane();

content.setLayout(new BorderLayout());

colorPanel = new JPanel();

colorPanel.setBackground(Color.blue);

content.add(colorPanel, BorderLayout.CENTER);

//Horizontal buttons at bottom of frame:

Box horizontalBox = Box.createHorizontalBox();

Component horizontalStrut =

Box.createHorizontalStrut(HORIZONTAL_STRUT_SIZE);

horizontalBox.add(horizontalStrut);

JButton hStopButton = new JButton("Red");

hStopButton.addActionListener(this);

horizontalBox.add(hStopButton);

Component horizontalStrut2 =

Box.createHorizontalStrut(HORIZONTAL_STRUT_SIZE);

horizontalBox.add(horizontalStrut2);


Display 14.14

Box Container Class

(3/4)

JButton hGoButton = new JButton("Green");

hGoButton.addActionListener(this);

horizontalBox.add(hGoButton);

content.add(horizontalBox, BorderLayout.SOUTH);

//Vertical buttons on right side of frame:

Box verticalBox = Box.createVerticalBox();

Component verticalStrut = Box.createVerticalStrut(VERTICAL_STRUT_SIZE);

verticalBox.add(verticalStrut);

JButton vStopButton = new JButton("Red");

vStopButton.addActionListener(this);

verticalBox.add(vStopButton);

Component verticalStrut2 = Box.createVerticalStrut(VERTICAL_STRUT_SIZE);

verticalBox.add(verticalStrut2);

JButton vGoButton = new JButton("Green");

vGoButton.addActionListener(this);

verticalBox.add(vGoButton);

content.add(verticalBox, BorderLayout.EAST);

}


Display 14.14

Box Container Class

(4/4)

public void actionPerformed(ActionEvent e)

{

if (e.getActionCommand().equals("Red"))

colorPanel.setBackground(Color.red);

else if (e.getActionCommand().equals("Green"))

colorPanel.setBackground(Color.green);

else

System.out.println("Error in button interface.");

}

public static void main(String[] args)

{

BoxClassDemo gui = new BoxClassDemo();

gui.setVisible(true);

}

}


Execution result of boxclassdemo java
Execution Result ofBoxClassDemo.java


Some methods in the cardlayout manager class
Some Methods in theCardLayout Manager Class

  • public void first(Container theContainer)

    - Causes the first “card” in theContainer to be displayed.

  • public void last(Container theContainer)

    - Causes the last “card” in theContainer to be displayed.

  • public void next(Container theContainer)

    - Causes the next “card” in theContainer to be displayed.

    - The next card is the one that was added after the currently displayed “card” was added.

  • public void previous(Container theContainer)

    - Causes the previous “card” in theContainer to be displayed.

  • public void show(Container theContainer,

    String cardName)

    - Displays the “card” that was added with the StringcardName as its name.


Display 14.15

CardLayout

(1/4)

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class CardLayoutDemo extends JFrame implements ActionListener

{

public static final int WIDTH = 300;

public static final int HEIGHT = 200;

private CardLayout dealer;

private JPanel deckPanel;

public CardLayoutDemo()

{

setSize(WIDTH, HEIGHT);

addWindowListener(new WindowDestroyer());

setTitle("CardLayout Demonstration");

Container contentPane = getContentPane();

contentPane.setLayout(new BorderLayout());

deckPanel = new JPanel();

dealer = new CardLayout();

deckPanel.setLayout(dealer);


Display 14.15

CardLayout

(2/4)

JPanel startCardPanel = new JPanel();

startCardPanel.setLayout(new FlowLayout());

startCardPanel.setBackground(Color.lightGray);

JLabel startLabel = new JLabel("Hello");

startCardPanel.add(startLabel);

deckPanel.add("start", startCardPanel);

JPanel greenCardPanel = new JPanel();

greenCardPanel.setLayout(new FlowLayout());

greenCardPanel.setBackground(Color.green);

JLabel goLabel = new JLabel("Go");

greenCardPanel.add(goLabel);

deckPanel.add("green", greenCardPanel);

JPanel redCardPanel = new JPanel();

redCardPanel.setLayout(new FlowLayout());

redCardPanel.setBackground(Color.red);

JLabel stopLabel = new JLabel("Stop");

redCardPanel.add(stopLabel);

deckPanel.add("red", redCardPanel);

contentPane.add(deckPanel, BorderLayout.CENTER);


Display 14.15

CardLayout

(3/4)

JPanel buttonPanel = new JPanel();

buttonPanel.setBackground(Color.white);

buttonPanel.setLayout(new FlowLayout());

JButton stopButton = new JButton("Red");

stopButton.addActionListener(this);

buttonPanel.add(stopButton);

JButton goButton = new JButton("Green");

goButton.addActionListener(this);

buttonPanel.add(goButton);

JButton resetButton = new JButton("Reset");

resetButton.addActionListener(this);

buttonPanel.add(resetButton);

contentPane.add(buttonPanel, BorderLayout.SOUTH);

dealer.first(deckPanel);//Optional

}


Display 14.15

CardLayout

(4/4)

public void actionPerformed(ActionEvent e)

{

String actionCommand = e.getActionCommand();

if (actionCommand.equals("Red"))

dealer.show(deckPanel, "red");

else if (actionCommand.equals("Green"))

dealer.show(deckPanel, "green");

else if (actionCommand.equals("Reset"))

dealer.show(deckPanel, "start");

else

System.out.println("Error in CardLayout Demo.");

}

public static void main(String[] args)

{

CardLayoutDemo demoGui = new CardLayoutDemo();

demoGui.setVisible(true);

}

}


Execution result of cardlayoutdemo java
Execution Result ofCardLayoutDemo.java


Display 14.17

Inner Class

(1/2)

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class InnerClassDemo extends JFrame

{

public static final int WIDTH = 300;

public static final int HEIGHT = 200;

public static void main(String[] args)

{

InnerClassDemo sampleGUI = new InnerClassDemo();

sampleGUI.setVisible(true);

}


Display 14.17

Inner Class

(2/2)

public InnerClassDemo()

{

setSize(WIDTH, HEIGHT);

setTitle("Inner Class Demo");

Container contentPane = getContentPane();

contentPane.setLayout(new BorderLayout());

JLabel label = new JLabel(

"Please don't click that button!");

contentPane.add(label, BorderLayout.CENTER);

addWindowListener(new InnerDestroyer());

}

//An inner class with the same functionality

//as the class WindowDestroyer.

private class InnerDestroyer extends WindowAdapter

{

public void windowClosing(WindowEvent e)

{

System.exit(0);

}

}

}


Execution result of innerclassdemo java
Execution Result ofInnerClassDemo.java


The windowlistener interface
The WindowListener Interface

  • For a class to be a listener for window events, it must implement the WindowListener interface.

  • By implementing the WindowListener interface, a window can be its own listener.

  • The advantage of making a window its own listener is that it is easy to call methods from the listener since they are in the same object.


The windowlistener interface1
The WindowListener Interface

  • Implementation of the WindowListener interface requires these seven methods to be defined:

    • public void windowOpened(WindowEvent e)

    • public void windowClosing(WindowEvent e)

    • public void windowClosed(WindowEvent e)

    • public void windowIconified(WindowEvent e)

    • public void windowDeiconified(WindowEvent e)

    • public void windowActivated(WindowEvent e)

    • public void windowDeactivated(WindowEvent e)

  • If a method will be not be used, it should be defined with an empty body

  • WindowAdapter is a class that implements all seven methods of the WindowListener with empty bodies.


Display 14.19

WindowListener

(1/3)

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class WindowListenerDemo extends JFrame

implements ActionListener, WindowListener

{

public static final int WIDTH = 300;

public static final int HEIGHT = 200;

public static void main(String[] args)

{

WindowListenerDemo demoWindow = new WindowListenerDemo();

demoWindow.setVisible(true);

}

public WindowListenerDemo()

{

setSize(WIDTH, HEIGHT);

addWindowListener(this);

setTitle("Window Listener Demonstration");

Container content = getContentPane();

content.setBackground(Color.blue);


Display 14.19

WindowListener

(2/3)

content.setLayout(new FlowLayout());

JButton stopButton = new JButton("Red");

stopButton.addActionListener(this);

content.add(stopButton);

JButton goButton = new JButton("Green");

goButton.addActionListener(this);

content.add(goButton);

}

public void actionPerformed(ActionEvent e)

{

Container content = getContentPane();

if (e.getActionCommand().equals("Red"))

content.setBackground(Color.red);

else if (e.getActionCommand().equals("Green"))

content.setBackground(Color.green);

else

System.out.println("Error in WindowListenerDemo.");

}


Display 14.19

WindowListener

(3/3)

public void windowOpened(WindowEvent e)

{}

public void windowClosing(WindowEvent e)

{

this.dispose();

System.exit(0);

}

public void windowClosed(WindowEvent e)

{}

public void windowIconified(WindowEvent e)

{}

public void windowDeiconified(WindowEvent e)

{}

public void windowActivated(WindowEvent e)

{}

public void windowDeactivated(WindowEvent e)

{}

}


Execution result of windowlistenerdemo java
Execution Result ofWindowListenerDemo.java


Programming the close window button
Programming the Close-Window Button

  • The WindowListener interface can be used to program the close-window button.

  • If the close-window button is not programmed, by default it will close the window but not exit the program.

  • For a window that does not close when the close-window button is clicked, use a method call like this:

    setDefaultCloseOperation(

    WindowConstants.DO_NOTHING_ON_CLOSE);

  • The CloseWindowDemo uses this method call

  • When the close-window button is clicked, the program displays a confirmation dialog instead of closing the window.


Closewindowdemo program
CloseWindowDemo Program

Prevents window from closing so that user can confirm or cancel before window is closed.

public CloseWindowDemo()

{

setSize(WIDTH, HEIGHT);

setDefaultCloseOperation(

WindowConstants.DO_NOTHING_ON_CLOSE);

addWindowListener(new InnerDestroyer());

setTitle("Close Window Demo");

Container contentPane = getContentPane();

contentPane.setLayout(new BorderLayout());

. . .

}

Defined on next slide

Constructor for the CloseWindowDemo class, which inherits from JFrame.


Closewindowdemo program1
CloseWindowDemo Program

Definition of inner class used as listener for the CloseWindowDemo class.

Inherits from WindowAdapter so it does not have to define all seven window event methods.

private class InnerDestroyer extends WindowAdapter

{

public void windowClosing(WindowEvent e)

{

ConfirmWindow askWindow = new ConfirmWindow();

askWindow.setVisible(true);

}

}

ConfirmWindow closes window and exits program if user confirms close.


Closewindowdemo program2
CloseWindowDemo Program

actionPerformed method from the ConfirmWindow inner class

public void actionPerformed(ActionEvent e)

{

if (e.getActionCommand().equals("Yes"))

System.exit(0);

else if (e.getActionCommand().equals("No"))

dispose(); //Destroys only the ConfirmWindow.

else

System.out.println("Error in Confirm Window.");

}

The main window will only be closed if the user clicks the “Yes” button in the ConfirmWindow


Display 14.20

CloseWindowDemo

(1/4)

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class CloseWindowDemo extends JFrame

{

public static final int WIDTH = 300;

public static final int HEIGHT = 200;

public static void main(String[] args)

{

CloseWindowDemo gui = new CloseWindowDemo();

gui.setVisible(true);

}

public CloseWindowDemo()

{

setSize(WIDTH, HEIGHT);

setDefaultCloseOperation(

WindowConstants.DO_NOTHING_ON_CLOSE);

addWindowListener(new InnerDestroyer());

setTitle("Close Window Demo");

Container contentPane = getContentPane();

contentPane.setLayout(new BorderLayout());

JLabel message = new JLabel(

"Please don't click that button.");

contentPane.add(message, BorderLayout.CENTER);

}


//Displays a window that checks if the user wants to exit.

private class InnerDestroyer extends WindowAdapter

{

public void windowClosing(WindowEvent e)

{

ConfirmWindow askWindow = new ConfirmWindow();

askWindow.setVisible(true);

}

}

//Designed to be used with the inner class InnerDestroyer in

//the class CloseWindowDemo. Checks if the user wants to exit.

private class ConfirmWindow extends JFrame

implements ActionListener

{

public static final int WIDTH = 200;

public static final int HEIGHT = 100;

Display 14.20

CloseWindowDemo

(2/4)


Display 14.20

CloseWindowDemo

(3/4)

public ConfirmWindow()

{

setSize(WIDTH, HEIGHT);

Container confirmContent = getContentPane();

confirmContent.setBackground(Color.white);

confirmContent.setLayout(new BorderLayout());

JLabel msgLabel = new JLabel(

"Are you sure you want to exit?");

confirmContent.add(msgLabel, BorderLayout.CENTER);

JPanel buttonPanel = new JPanel();

buttonPanel.setLayout(new FlowLayout());

JButton exitButton = new JButton("Yes");

exitButton.addActionListener(this);

buttonPanel.add(exitButton);

JButton cancelButton = new JButton("No");

cancelButton.addActionListener(this);

buttonPanel.add(cancelButton);

confirmContent.add(buttonPanel, BorderLayout.SOUTH);

}


Display 14.20

CloseWindowDemo

(4/4)

public void actionPerformed(ActionEvent e)

{

if (e.getActionCommand().equals("Yes"))

System.exit(0);

else if (e.getActionCommand().equals("No"))

dispose();//Destroys only the ConfirmWindow.

else

System.out.println("Error in Confirm Window.");

}

}

}


Execution result of closewindowdemo java
Execution Result ofCloseWindowDemo.java


Changing components
Changing Components

  • A program can add or remove components after a GUI has been displayed, but that is beyond the scope of the book.

  • Making components visible or not visible gives a similar effect.

  • The setVisible method is used in the VisibleDemo program to make only one of the red and green labels visible at a time.

    (code on next slide)


Changing components1
Changing Components

The actionPerformed method from the VisibleDemo program

public void actionPerformed(ActionEvent e)

{

if (e.getActionCommand().equals(“Red”))

{

colorPanel.setBackground(Color.red);

stopLabel.setVisible(false);

goLabel.setVisible(true);

validate();

}

. . .

}

There is similar code for when the Green button is pressed, which turns the background green and hides the go label.

Visibility changes won’t occur until the validate method is called.


Display 14.21

Invisible Labels

(1/3)

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class VisibilityDemo extends JFrame

implements ActionListener

{

public static final int WIDTH = 300;

public static final int HEIGHT = 200;

private JLabel upLabel;

private JLabel downLabel;

public VisibilityDemo()

{

setSize(WIDTH, HEIGHT);

addWindowListener(new WindowDestroyer());

setTitle("Visibility Demonstration");

Container contentPane = getContentPane();

contentPane.setLayout(new BorderLayout());

contentPane.setBackground(Color.white);


upLabel = new JLabel("Here I am up here!");

contentPane.add(upLabel, BorderLayout.NORTH);

upLabel.setVisible(false);

downLabel = new JLabel("Here I am down here!");

contentPane.add(downLabel, BorderLayout.SOUTH);

downLabel.setVisible(false);

JPanel buttonPanel = new JPanel();

buttonPanel.setBackground(Color.white);

buttonPanel.setLayout(new FlowLayout());

JButton upButton = new JButton("Up");

upButton.addActionListener(this);

buttonPanel.add(upButton);

JButton downButton = new JButton("Down");

downButton.addActionListener(this);

buttonPanel.add(downButton);

contentPane.add(buttonPanel, BorderLayout.CENTER);

}

Display 14.21

Invisible Labels

(2/3)


Display 14.21

Invisible Labels

(3/3)

public void actionPerformed(ActionEvent e)

{

if (e.getActionCommand().equals("Up"))

{

upLabel.setVisible(true);

downLabel.setVisible(false);

validate();

}

else if (e.getActionCommand().equals("Down"))

{

downLabel.setVisible(true);

upLabel.setVisible(false);

validate();

}

else

System.out.println("Error in VisibilityDemo interface.");

}

public static void main(String[] args)

{

VisibilityDemo demoGui = new VisibilityDemo();

demoGui.setVisible(true);

}

}


Execution result of visibilitydemo java
Execution Result ofVisibilityDemo.java


Another look at the swing class hierarchy

Swing

JComponent

AbstractButton

JLabel

JMenuBar

Abstract Class

JMenuItem

JButton

Class

JMenu

Another Look at the Swing Class Hierarchy

  • All of the basic properties of JButton and JMenuItem are inherited from AbstractButton.

  • JButton and JMenuItem are similar because they are derived from the same abstract class.

  • Since AbstractButton is an abstract class, no objects of that class can be made.

  • The purpose of the AbstractButton class is to provide a place for code that is common to JButton and JMenuItem and avoid repeated code.


Another look at the swing class hierarchy1

Swing

JComponent

AbstractButton

JLabel

JMenuBar

Abstract Class

JMenuItem

JButton

Class

JMenu

Another Look at the Swing Class Hierarchy

  • JLabel and JButton inherit from a common ancestor, namely Jcomponent, so they have some similarities.

  • Notice, however, that JLabel and JButton are not derived from the same class, even though they have a common ancestor.

  • The hierarchy reflects the fact that JButton and JMenuItem are more similar than JLabel and JButton.

  • Also notice that JMenu inherits from JMenuItem, so it can be used anywhere a JMenuItem can. This allows nested menus.


Summary
Summary

  • You can add icons to JButtons, JLabels, and JMenuItems.

  • A JMenuBar can be added to a JFrame with the method setJMenuBar or with the usual add method.

  • Both buttons and menu items fire action events and so should have an ActionListener registered with them.

  • You can use the class JScrollPane to add scroll bars to a text area.

  • You can define a window listener class by having it implement the WindowListener interface.

  • When you define a GUI using Swing you can specify the look and feel for the GUI.

  • If you want a close-button to do something other than close the window, you must use SetDefaultCloseOperation.

  • If you change the visibility of a component you should use the validate method to update the GUI.


ad