Title: GUI More Book Examples
Course: CPS 261: Advanced Java Concepts ~ DL & MM MASTER

GUI Other Examples from the book

In previous lectures, I covered the examples in chapter 17 of our textbook. These examples dealt with layout managers and menus. There are other examples in chapter 17 which you can read about, but I don't plan to cover in my lectures because we have already covered many of the topics associated with these examples. These examples include:

1. FirstSwingDemo, EndingListener, FirstWindow, EndingListener, DemoWindow:
covers Simple JFrame, JButton, ActionListener
2. ColoredWindow, DemoColoredWindow:
Provides 2 Window constructors, JLabel, setBackground
3. InnerListenersDemo and InnerListenersDemo2:
Demonstrates inner classes used for ActionListeners
4. TextFieldDemo and TextAreaDemo demonstrate JTextField and JTextArea JComponents:
Using JTextField and JTextArea using getText and setText methods
5. Calculator:
Another JButton, JTextField, ActionListener example

Chapter 18 of the textbook:

1. WindowListenerDemo.java and WindowListenerDemo2.java -
  - Other Listener Interfaces
  - Notice the possible calls:
dispose() merely eliminates everything in the current class such as the popup close frame
System.exit(int) eliminates the whole program.
  - WindowListenerDemo2.java uses the WindowAdapter class.
  - Replace the line:
private class CheckOnExit implements WindowListener
with
private class CheckOnExit extends WindowAdapter
  - Remove the unnecessary routines.
WindowListenerDemo.java


import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Color;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.WindowListener;
import java.awt.event.WindowEvent;

public class WindowListenerDemo extends JFrame
{
    public static final int WIDTH = 300; //for main window
    public static final int HEIGHT = 200; //for main window
    public static final int SMALL_WIDTH = 200; //for confirm window
    public static final int SMALL_HEIGHT = 100;//for confirm window

//******* Inner Class CheckOnExit
    private class CheckOnExit implements WindowListener
    {
        public void windowOpened(WindowEvent e)
        {}

        public void windowClosing(WindowEvent e)
        {
            ConfirmWindow checkers = new ConfirmWindow( );
            checkers.setVisible(true);
        }

        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)
        {}
    } //End of inner class CheckOnExit

// ****** End of CheckOnExit Inner Class

// ****** Another Inner class: ConfirmWindow

    private class ConfirmWindow extends JFrame implements ActionListener
    {
        public ConfirmWindow( )
        {
            setSize(SMALL_WIDTH, SMALL_HEIGHT);
            getContentPane( ).setBackground(Color.YELLOW);
            setLayout(new BorderLayout( ));

            JLabel confirmLabel = new JLabel(
                           "Are you sure you want to exit?");
            add(confirmLabel, BorderLayout.CENTER);

            JPanel buttonPanel = new JPanel( );
            buttonPanel.setBackground(Color.ORANGE);
            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);

            add(buttonPanel, BorderLayout.SOUTH);
        }

        public void actionPerformed(ActionEvent e)
        {
            String actionCommand = e.getActionCommand( );

            if (actionCommand.equals("Yes"))
                System.exit(0);
            else if (actionCommand.equals("No"))
                dispose( );//Destroys only the ConfirmWindow.
            else
                System.out.println("Unexpected Error in Confirm Window.");
        }
    } //End of inner class ConfirmWindow
// ****** End of ConfirmWindow Inner Class

    public static void main(String[] args)
    {
        WindowListenerDemo demoWindow = new WindowListenerDemo( );
        demoWindow.setVisible(true);
    }

    public WindowListenerDemo( )
    {
        setSize(WIDTH, HEIGHT);
        setTitle("Window Listener Demonstration");

        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        addWindowListener(new CheckOnExit( ));

        getContentPane( ).setBackground(Color.LIGHT_GRAY);
        JLabel aLabel = new JLabel("I like to be sure you are sincere.");
        add(aLabel);
    }
}



2. IconDemo.java
  - need the images: sad.gif, smiley.gif, duke_waving.gif
  - setText and setIcon can be used to change text and Icons on Labels, Buttons, and menu items.
  - Try out setHorizontalTextPostion, setVerticalTextPosition values are:
SwingConstants.LEFT - Horizontal
SwingConstants.RIGHT - Horizontal
SwingConstants.CENTER - Horizontal, Vertical
SwingConstants.TOP - Vertical
SwingConstants.BOTTOM - Vertical
  - For example add the following code near the end of your Constructor:

sadButton.setHorizontalTextPosition(SwingConstants.LEFT);
dukeLabel.setVerticalTextPosition(SwingConstants.TOP);
IconDemo.java


import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.ImageIcon;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Color;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;


public class IconDemo extends JFrame implements ActionListener
{
    public static final int WIDTH = 500;
    public static final int HEIGHT = 200;
    public static final int TEXT_FIELD_SIZE = 30;

    private JTextField message;

    public static void main(String[] args)
    {
        IconDemo iconGui = new IconDemo( );
        iconGui.setVisible(true);
    }


    public IconDemo( )
    {
        super("Icon Demonstration");
        setSize(WIDTH, HEIGHT);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        setBackground(Color.WHITE);
        setLayout(new BorderLayout( ));

        JLabel dukeLabel = new JLabel("Mood check");
        ImageIcon dukeIcon = new ImageIcon("duke_waving.gif");
        dukeLabel.setIcon(dukeIcon);

        add(dukeLabel, BorderLayout.NORTH);

        JPanel buttonPanel = new JPanel( );
        buttonPanel.setLayout(new FlowLayout( ));

        JButton happyButton = new JButton("Happy");
        ImageIcon happyIcon = new ImageIcon("smiley.gif");
        happyButton.setIcon(happyIcon);


        happyButton.addActionListener(this);
        buttonPanel.add(happyButton);

        JButton sadButton = new JButton("Sad");
        ImageIcon sadIcon = new ImageIcon("sad.gif");
        sadButton.setIcon(sadIcon);

        sadButton.addActionListener(this);
        buttonPanel.add(sadButton);
        add(buttonPanel, BorderLayout.SOUTH);

        message = new JTextField(TEXT_FIELD_SIZE);
        add(message, BorderLayout.CENTER);
    }


    public void actionPerformed(ActionEvent e)
    {
       String actionCommand = e.getActionCommand( );

       if (actionCommand.equals("Happy"))
           message.setText(
                   "Smile and the world smiles with you!");
       else if (actionCommand.equals("Sad"))
           message.setText(
                  "Cheer up. It can't be that bad.");
       else
            message.setText("Unexpected Error.");
    }
}




3. ScrollBarDemo-
  - Take a look at the constructor to JScrollPane(Component objectToBeScrolled); So what can be scrolled?
  - Note that the author is relying on the fact that the default layout manager is BorderLayout
  - Put the JScrollPane into the BorderLayout.CENTER and avoid the surrounding JPanel
  - Take a look at setHorizontalScrollBarPolicy and setVerticalScrollBarPolicy. Values are
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER
Similar values for VERTICAL
  - Add the following:
scrolledText.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrolledText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
ScrollBarDemo.java


import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;


public class ScrollBarDemo extends JFrame
                           implements ActionListener
{
    public static final int WIDTH = 600;
    public static final int HEIGHT = 400;
    public static final int LINES = 15;
    public static final int CHAR_PER_LINE = 30;


    private JTextArea memoDisplay;
    private String memo1;
    private String memo2;


    public static void main(String[] args)
    {
        ScrollBarDemo gui = new ScrollBarDemo( );
        gui.setVisible(true);
    }


    public ScrollBarDemo( )
    {
        super("Scroll Bars Demo");
        setSize(WIDTH, HEIGHT);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


        JPanel buttonPanel = new JPanel( );
        buttonPanel.setBackground(Color.LIGHT_GRAY);
        buttonPanel.setLayout(new FlowLayout( ));
        JButton memo1Button = new JButton("Save Memo 1");
        memo1Button.addActionListener(this);
        buttonPanel.add(memo1Button);

        JButton memo2Button = new JButton("Save Memo 2");
        memo2Button.addActionListener(this);
        buttonPanel.add(memo2Button);

        JButton clearButton = new JButton("Clear");
        clearButton.addActionListener(this);
        buttonPanel.add(clearButton);

        JButton get1Button = new JButton("Get Memo 1");
        get1Button.addActionListener(this);
        buttonPanel.add(get1Button);

        JButton get2Button = new JButton("Get Memo 2");
        get2Button.addActionListener(this);
        buttonPanel.add(get2Button);

        add(buttonPanel, BorderLayout.SOUTH);

        JPanel textPanel = new JPanel( );
        textPanel.setBackground(Color.BLUE);

        memoDisplay = new JTextArea(LINES, CHAR_PER_LINE);
        memoDisplay.setBackground(Color.WHITE);

        JScrollPane scrolledText = new JScrollPane(memoDisplay);
        scrolledText.setHorizontalScrollBarPolicy(
                    JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        scrolledText.setVerticalScrollBarPolicy(
                    JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

        textPanel.add(scrolledText);

        add(textPanel, BorderLayout.CENTER);
    }

    public void actionPerformed(ActionEvent e)
    {
        String actionCommand = e.getActionCommand( );


        if (actionCommand.equals("Save Memo 1"))
            memo1 = memoDisplay.getText( );
        else if (actionCommand.equals("Save Memo 2"))
            memo2 = memoDisplay.getText( );
        else if (actionCommand.equals("Clear"))
            memoDisplay.setText("");
        else if (actionCommand.equals("Get Memo 1"))
            memoDisplay.setText(memo1);
        else if (actionCommand.equals("Get Memo 2"))
            memoDisplay.setText(memo2);
        else
            memoDisplay.setText("Error in memo interface");
     }
}



4. VisibilityDemo
  - need 2 images (duke_standing.gif, duke_waving.gif)
  - Using setVisible to turn components change the visibility of components.
VisibilityDemo.java



import javax.swing.JFrame;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class VisibilityDemo extends JFrame
                            implements ActionListener
{
    public static final int WIDTH = 300;
    public static final int HEIGHT = 200;

    private JLabel wavingLabel;
    private JLabel standingLabel;

    public static void main(String[] args)
    {
        VisibilityDemo demoGui = new VisibilityDemo( );
        demoGui.setVisible(true);
    }

    public VisibilityDemo( )
    {
        setSize(WIDTH, HEIGHT);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("Visibility Demonstration");

        setLayout(new BorderLayout( ));

        JPanel picturePanel = new JPanel( );
        picturePanel.setBackground(Color.WHITE);
        picturePanel.setLayout(new FlowLayout( ));

        ImageIcon dukeStandingIcon =
                  new ImageIcon("duke_standing.gif");
        standingLabel = new JLabel(dukeStandingIcon);
        standingLabel.setVisible(true);
        picturePanel.add(standingLabel);

        ImageIcon dukeWavingIcon = new ImageIcon("duke_waving.gif");
        wavingLabel = new JLabel(dukeWavingIcon);
        wavingLabel.setVisible(false);
        picturePanel.add(wavingLabel);

        add(picturePanel, BorderLayout.CENTER);

        JPanel buttonPanel = new JPanel( );
        buttonPanel.setBackground(Color.LIGHT_GRAY);
        buttonPanel.setLayout(new FlowLayout( ));

        JButton waveButton = new JButton("Wave");
        waveButton.addActionListener(this);
        buttonPanel.add(waveButton);

        JButton stopButton = new JButton("Stop");
        stopButton.addActionListener(this);
        buttonPanel.add(stopButton);

        add(buttonPanel, BorderLayout.SOUTH);
    }

    public void actionPerformed(ActionEvent e)
    {
        String actionCommand = e.getActionCommand( );

        if (actionCommand.equals("Wave"))
        {
            wavingLabel.setVisible(true);
            standingLabel.setVisible(false);
        }
        else if (actionCommand.equals("Stop"))
        {
            standingLabel.setVisible(true);
            wavingLabel.setVisible(false);
        }
        else
            System.out.println("Unanticipated error.");
    }
}



5. JColorChooserDemo() - Note the 3 different ways to select color
JColorChooserDemo


import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Color;


public class JColorChooserDemo extends JFrame
                               implements ActionListener
{
    public static final int WIDTH = 400;
    public static final int HEIGHT = 200;

    private Color sampleColor = Color.LIGHT_GRAY;


    public static void main(String[] args)
    {
        JColorChooserDemo gui = new JColorChooserDemo( );
        gui.setVisible(true);
    }

    public JColorChooserDemo( )
    {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        getContentPane( ).setBackground(sampleColor);
        setLayout(new BorderLayout( ));
        setTitle("JColorChooser Demo");
        setSize(WIDTH, HEIGHT);
        JPanel buttonPanel = new JPanel( );
        buttonPanel.setBackground(Color.WHITE);
        buttonPanel.setLayout(new FlowLayout( ));
        JButton chooseButton = new JButton("Choose a Color");
        chooseButton.addActionListener(this);
        buttonPanel.add(chooseButton);
        add(buttonPanel, BorderLayout.SOUTH);
    }

    public void actionPerformed(ActionEvent e)
    {
        if (e.getActionCommand( ).equals("Choose a Color"))
        {
            sampleColor =
               JColorChooser.showDialog(this, "JColorChooser", sampleColor);
            if (sampleColor != null)//If a color was chosen
                getContentPane( ).setBackground(sampleColor);
        }
        else
            System.out.println("Unanticipated Error");
    }
}



6. Examples from the book that do with Graphics drawing- Face, HappyFace, ActionFace - Don't plan to go over this, ... we have already done a lot with paint and the Graphics class.

Last Updated: September 19, 2013 1:38 AM