JMU
Windowing: Some Advanced Topics
with Examples in Java


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Windows: A Review
Custom Dialog Boxes

A Panel for Entering Numbers

javaexamples/gui/SliderPanel.java
        package gui;

import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;

/**
 * A component that contains both a slider and a label
 * showing the current value of the slider.
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class SliderPanel extends JPanel implements ChangeListener
{
    private JLabel     maxLabel, minLabel, valueLabel;
    private JSlider    slider;


    /**
     * Explicit Value Constructor.
     *
     * @param min   The minimum value on the slider
     * @param max   The maximum value on the slider
     * @param step  The difference between tick marks
     */
    public SliderPanel(int min, int max, int step)
    {
       super();

       slider = new JSlider(min, max, min);
       slider.setMajorTickSpacing(step);
       slider.setSnapToTicks(true);
       slider.setPaintTicks(true);
       slider.addChangeListener(this);

       minLabel = new JLabel(""+min);
       maxLabel = new JLabel(""+max);
       valueLabel = new JLabel(""+slider.getValue());
       valueLabel.setHorizontalAlignment(JLabel.CENTER);

       setLayout(new BorderLayout());

       add(minLabel, BorderLayout.WEST);
       add(maxLabel, BorderLayout.EAST);

       add(slider, BorderLayout.CENTER);

       add(valueLabel, BorderLayout.NORTH);
    }

    /**
     * Get the current value on the slider.
     *
     * @return  The current value
     */
    public int getValue()
    {
       return slider.getValue();
    }

    /**
     * Handle stateChanged events (required by ChangeListener).
     *
     * @param evt   The ChangeEvent
     */
    public void stateChanged(ChangeEvent evt)
    {
       int    value;


       value = slider.getValue();

       valueLabel.setText(""+value);
       valueLabel.repaint();        
    }
}
        
javaexamples/usinggui/TextMessageDialog.java
        package usinggui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

import gui.*;
import inheritance.*;


/**
 * A dialog box that is used to enter a TextMessage
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class TextMessageDialog extends    JDialog
                               implements ActionListener
{
    private boolean        shouldReturnValue;
    private JButton        cancelButton, okButton;
    private JTextArea      ta;
    private SliderPanel    sp;

    /**
     * Constructor
     *
     * @param frame  The owner
     */
    public TextMessageDialog(Frame frame)
    {
        super(frame, true); // true so it is modal
        Container           contentPane;
        JPanel              southPanel;
        JScrollPane         scrollPane;


        shouldReturnValue = false;
        setTitle("Enter a priority and message:");

        contentPane = getContentPane();
        contentPane.setLayout(new BorderLayout());


        ta = new JTextArea();
        scrollPane = new JScrollPane(ta,
                         JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                         JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        contentPane.add(scrollPane, BorderLayout.CENTER);

        sp = new SliderPanel(0, 10, 1);
        contentPane.add(sp, BorderLayout.NORTH);

        southPanel = new JPanel();

          southPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));

          okButton = new JButton("OK");
          okButton.setMnemonic('O');
          okButton.addActionListener(this);

          cancelButton = new JButton("Cancel");
          cancelButton.setMnemonic('C');
          cancelButton.addActionListener(this);

          southPanel.add(okButton);
          southPanel.add(cancelButton);

        contentPane.add(southPanel, BorderLayout.SOUTH);

        setSize(400,200);
    }




    /**
     * Get the newly-entered TextMessage
     *
     * @return  A new TextMessage
     */
    public TextMessage getTextMessage()
    {
        TextMessage    message;

        message = null;
        if (shouldReturnValue) 
        {
            message = new TextMessage(ta.getText() + "  " + sp.getValue());
        }

        return message;
    }



    /**
     * Handle action events (required by ActionListener)
     *
     * @param evt   The event
     */
    public void actionPerformed(ActionEvent evt)
    {
        boolean   done;
        String    command;

        done = false;
        command = evt.getActionCommand();

        if (command.equals("OK")) 
        {
            shouldReturnValue = true;
            done = true;
        } 
        else if (command.equals("Cancel")) 
        {
            done = true;
        }

        if (done) setVisible(false);
    }
}
        
javaexamples/usinggui/TextMessageDialogDriver.java
        import java.awt.*;
import javax.swing.*;

import gui.*;
import inheritance.*;
import usinggui.TextMessageDialog;


/**
 * An example that uses a custom dialog box
 *
 * @version 1.0
 * @author  David Bernstein, James Madison University
 */
public class TextMessageDialogDriver
{

    /**
     * The entry point
     *
     * @param args   The command line arguments
     */
    public static void main(String[] args)
    {
        CloseableFrame       f;
        Container            contentPane;
        TextMessage          tm;
        TextMessageDialog    tmd;


        f = new CloseableFrame();
        f.setSize(400,200);

        contentPane = f.getContentPane();

        f.setVisible(true);

        tmd = new TextMessageDialog(f);
        tmd.setVisible(true);

        tm = tmd.getTextMessage();

        if (tm != null) 
        {
            System.out.println(tm.getMessage());
        }
        
    }

}
        
Custom Dialog Boxes (cont.)

A Custom Dialog that uses the SliderPanel

javaexamples/usinggui/TextMessageDialog.java
        package usinggui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

import gui.*;
import inheritance.*;


/**
 * A dialog box that is used to enter a TextMessage
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class TextMessageDialog extends    JDialog
                               implements ActionListener
{
    private boolean        shouldReturnValue;
    private JButton        cancelButton, okButton;
    private JTextArea      ta;
    private SliderPanel    sp;

    /**
     * Constructor
     *
     * @param frame  The owner
     */
    public TextMessageDialog(Frame frame)
    {
        super(frame, true); // true so it is modal
        Container           contentPane;
        JPanel              southPanel;
        JScrollPane         scrollPane;


        shouldReturnValue = false;
        setTitle("Enter a priority and message:");

        contentPane = getContentPane();
        contentPane.setLayout(new BorderLayout());


        ta = new JTextArea();
        scrollPane = new JScrollPane(ta,
                         JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                         JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        contentPane.add(scrollPane, BorderLayout.CENTER);

        sp = new SliderPanel(0, 10, 1);
        contentPane.add(sp, BorderLayout.NORTH);

        southPanel = new JPanel();

          southPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));

          okButton = new JButton("OK");
          okButton.setMnemonic('O');
          okButton.addActionListener(this);

          cancelButton = new JButton("Cancel");
          cancelButton.setMnemonic('C');
          cancelButton.addActionListener(this);

          southPanel.add(okButton);
          southPanel.add(cancelButton);

        contentPane.add(southPanel, BorderLayout.SOUTH);

        setSize(400,200);
    }




    /**
     * Get the newly-entered TextMessage
     *
     * @return  A new TextMessage
     */
    public TextMessage getTextMessage()
    {
        TextMessage    message;

        message = null;
        if (shouldReturnValue) 
        {
            message = new TextMessage(ta.getText() + "  " + sp.getValue());
        }

        return message;
    }



    /**
     * Handle action events (required by ActionListener)
     *
     * @param evt   The event
     */
    public void actionPerformed(ActionEvent evt)
    {
        boolean   done;
        String    command;

        done = false;
        command = evt.getActionCommand();

        if (command.equals("OK")) 
        {
            shouldReturnValue = true;
            done = true;
        } 
        else if (command.equals("Cancel")) 
        {
            done = true;
        }

        if (done) setVisible(false);
    }
}
        
Custom Dialog Boxes (cont.)

A Driver

javaexamples/usinggui/TextMessageDialogDriver.java
        import java.awt.*;
import javax.swing.*;

import gui.*;
import inheritance.*;
import usinggui.TextMessageDialog;


/**
 * An example that uses a custom dialog box
 *
 * @version 1.0
 * @author  David Bernstein, James Madison University
 */
public class TextMessageDialogDriver
{

    /**
     * The entry point
     *
     * @param args   The command line arguments
     */
    public static void main(String[] args)
    {
        CloseableFrame       f;
        Container            contentPane;
        TextMessage          tm;
        TextMessageDialog    tmd;


        f = new CloseableFrame();
        f.setSize(400,200);

        contentPane = f.getContentPane();

        f.setVisible(true);

        tmd = new TextMessageDialog(f);
        tmd.setVisible(true);

        tm = tmd.getTextMessage();

        if (tm != null) 
        {
            System.out.println(tm.getMessage());
        }
        
    }

}
        
Popup Menus
Popup Menus

An Example

javaexamples/usinggui/Editor.java
        package usinggui;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;


/**
 * A simple editor that uses a pop-up menu
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class Editor extends    JPanel
                    implements ActionListener, MouseListener
{
    Caret              caret;    
    JMenuItem          copyItem, cutItem, pasteItem;
    JPopupMenu         popup;
    JTextArea          ta;
    String             clipboard;


    /**
     * Constructor
     */
    public Editor()
    {
       super();

       setLayout(new BorderLayout());
       setSize(400,400);

       ta = new JTextArea();
       caret = ta.getCaret();
       ta.setLineWrap(true);
       ta.setWrapStyleWord(true);
       caret = ta.getCaret();

       constructControls();
       performLayout();       
       ta.addMouseListener(this); // To show the popup menu

       clipboard = null;
    }

    /**
     * Handle actionPerformed events
     *
     * @param evt   The event
     */
    public void actionPerformed(ActionEvent evt)
    {
       String     command;

       command = evt.getActionCommand();

       if (command.equals("Copy"))       copy();
       else if (command.equals("Cut"))   cut();
       else if (command.equals("Paste")) paste();
    }

    /**
     * Construct the JPopupMenu, JMenu, and JToolBar and
     * add an array of Action objects to them.
     */
    private void constructControls()
    {
       popup = new JPopupMenu();

       copyItem = new JMenuItem("Copy");
       copyItem.addActionListener(this);
       popup.add(copyItem);

       cutItem = new JMenuItem("Cut");
       cutItem.addActionListener(this);
       popup.add(cutItem);

       pasteItem = new JMenuItem("Paste");
       pasteItem.addActionListener(this);
       popup.add(pasteItem);
    }
    /**
     * Copy text to the "clipboard"
     */
    public void copy()
    {
        int  dot, mark;
        
        dot  = caret.getDot();        
        mark = caret.getMark();
        clipboard = ta.getSelectedText();
        ta.select(-1, -1);
        caret.setDot(mark); // Causes a CaretEvent to be fired
        caret.setDot(dot);  // Positions the Caret at the right position
        ta.requestFocus();
    }

    /**
     * Cut text to the "clipboard"
     */
    public void cut()
    {
        int dot;        

        dot = caret.getDot();        
        clipboard = ta.getSelectedText();
        ta.replaceSelection(null);
        ta.select(-1, -1);
        caret.setDot(dot);
        ta.requestFocus();
    }

    /**
     * Is there any text on the "clipboard"?
     *
     * @return true if yes; false otherwise
     */
    public boolean isClipping()
    {
        return (clipboard != null);
    }

    /**
     * Is there any text selected?
     *
     * @return true if yes; false otherwise
     */
    public boolean isSelection()
    {
        return (ta.getSelectedText() != null);
    }

    /**
     * Handle mouseClicked events (required by MouseListener)
     *
     * @param evt   The event
     */
    public void mouseClicked(MouseEvent evt)
    {
    }

    /**
     * Handle mouseEntered events (required by MouseListener)
     *
     * @param evt   The event
     */
    public void mouseEntered(MouseEvent evt)
    {
    }

    /**
     * Handle mouseExited events (required by MouseListener)
     *
     * @param evt   The event
     */
    public void mouseExited(MouseEvent evt)
    {
    }

    /**
     * Handle mousePressed events (required by MouseListener)
     *
     * @param evt   The event
     */
    public void mousePressed(MouseEvent evt)
    {
    }
    /**
     * Handle mouseReleased events (required by MouseListener)
     *
     * @param evt   The event
     */
    public void mouseReleased(MouseEvent evt)
    {
       if (evt.isPopupTrigger()) showPopup(evt.getPoint());
    }
    /**
     * Layout this Editor.
     */
    private void performLayout()
    {
        JScrollPane      scrollPane;

        setLayout(new BorderLayout());
        setSize(400,400);

        scrollPane = new JScrollPane(ta);
        scrollPane.setHorizontalScrollBarPolicy(
            JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS
            );
        scrollPane.setVerticalScrollBarPolicy(
            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS
            );
        add(scrollPane, BorderLayout.CENTER);
    }

    /**
     * Paste text from the "clipboard".
     */
    public void paste()
    {
        int dot, offset;        

        dot = caret.getDot();
        offset = clipboard.length();
        
        ta.replaceSelection(clipboard);
        clipboard = null;

        caret.setDot(dot + offset);
        ta.requestFocus();
    }
    /**
     * Show the pop-up menu
     *
     * @param point   The location of the pop-up menu
     */
    private void showPopup(Point point)
    {
       copyItem.setEnabled(false);
       cutItem.setEnabled(false);
       pasteItem.setEnabled(false);

       if (isSelection())
       { 
          copyItem.setEnabled(true);
          cutItem.setEnabled(true);
       }

       if (isClipping()) pasteItem.setEnabled(true);

       popup.show(this, point.x, point.y);
    }
}
        
Internal Windows
Internal Windows (cont.)

An Example

javaexamples/usinggui/InternalWindowDriver.java
        import java.awt.*;
import javax.swing.*;

import gui.JListEditor;
import usinggui.Editor;


/**
 * An example that uses internal windows
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class InternalWindowDriver
{

    /**
     * The entry point
     *
     * @param args   The command line arguments
     */
    public static void main(String[] args)
    {
        JFrame            f;
        Container         contentPane;
        JInternalFrame    i1, i2, i3;
        JDesktopPane      desk;


        f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(600,400);        

        desk = new JDesktopPane();
        desk.setSize(600,400);

            i1 = new JInternalFrame("Action/Adventure", 
                                    true, true, true, true);
            i1.setSize(200,100);
            i1.setBounds(0,0,200,100);
            i1.getContentPane().add(new Editor());
            i1.setVisible(true);

            i2 = new JInternalFrame("Comedy", 
                                    true, true, true, true);
            i2.setSize(200,100);
            i2.setBounds(200,100,200,100);
            i2.getContentPane().add(new JListEditor());
            i2.setVisible(true);
            

            i3 = new JInternalFrame("Romance", 
                                    true, true, true, true);
            i3.setSize(200,100);
            i3.setBounds(400,200,200,100);
            i3.getContentPane().add(new JButton("Click me"));
            i3.setVisible(true);

            desk.add(i1);
            desk.add(i2);
            desk.add(i3);

        f.setContentPane(desk);

        f.setVisible(true);
    }
}

        
Tool Tips
Tool Tips (cont.)

An Example

javaexamples/layout/JToolTipDriver.java
        import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;

/**
 * An example that uses JToolTip
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class JToolTipDriver
{

    public static void main(String[] args)
    {
        JFrame            f;
        Container         contentPane;
        JLabel            jl;
        JPanel            p1, p2;


        f = new JFrame();
        f.setSize(640,480);        
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        
        contentPane = f.getContentPane();

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

        p1 = new JPanel();
        p1.setToolTipText("I'm an empty JPanel!");
        contentPane.add(p1);

        p2 = new JPanel();
        p2.setBorder(
              BorderFactory.createBevelBorder(
                BevelBorder.RAISED
              )
            );

        jl = new JLabel("This JPanel has a raised "+ 
                        "BevelBorder");
        jl.setToolTipText("I'm a JLabel");

        p2.add(jl);
        p2.setToolTipText("I'm a JPanel too! ");

        contentPane.add(p2);
        f.setVisible(true);
    }


}