09. Java GUI Examples (Part 3)

GUI Examples and Exercises

Exercise 9.1

Example Program for Exercise 9.1

// EXAMPLE 9.1 JAVA CODE AND EXERCISE 9.1 (SEE BELOW)  import java.awt.event.*; import java.awt.*; import javax.swing.*;  public class TryCheckBoxes extends JFrame  {  private JCheckBox chBoxA= new JCheckBox("A");  private JCheckBox chBoxB= new JCheckBox("B");  private JCheckBox chBoxC= new JCheckBox("C");  private JLabel labelA=new JLabel("A is ON ");  private JLabel labelB=new JLabel("B is ON ");  private JLabel labelC=new JLabel("C is ON");     public TryCheckBoxes(){      super("Try CheckBoxes"); // puts "Try CheckBoxes in title bar of JFrame      setLayout(new FlowLayout()); // sets JFrame layout   chBoxA.addItemListener(new CheckBoxAHandler());   chBoxB.addItemListener(new CheckBoxBHandler());   chBoxC.addItemListener(new CheckBoxCHandler());   labelA.setVisible(false); // make label invisible   labelB.setVisible(false); // make label invisible   labelC.setVisible(false); // make label invisible    // put all components into JFrame   add(chBoxA);   add(chBoxB);   add(chBoxC);   add(labelA);   add(labelB);    add(labelC);   } // end constructor   public static void main( String [] args ){        TryCheckBoxes tcb =new TryCheckBoxes();   tcb.setSize(155, 150);   tcb.setVisible(true);   tcb.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  } // end main  //  inner classes for listener classes  class CheckBoxAHandler implements ItemListener {   public void itemStateChanged( ItemEvent e ){    if( chBoxA.isSelected() )     labelA.setVisible(true);    else     labelA.setVisible(false);   } // end itemStateChanged for check box A  } // end CheckBoxAHandler listener class   class CheckBoxBHandler implements ItemListener {   public void itemStateChanged( ItemEvent e ){    if( e.getStateChange() == ItemEvent.SELECTED ) // another way to check if selected     labelB.setVisible(true);    else     labelB.setVisible(false);   } // end itemStateChanged  for check box B  } // end CheckBoxBHandler listener class   class CheckBoxCHandler implements ItemListener {   public void itemStateChanged( ItemEvent e ){    labelC.setVisible(chBoxC.isSelected()); // BEST WAY   } // end itemStateChanged for check box C  } // end CheckBoxCHandler listener class  } // end class TryCheckBoxes
/* EXERCISE 9.1 Run the program above.
    THEN change it to have another JCheckBox for "D", and another JLabel for "D is ON". 
    Be sure to put them in JFrame, and add another listener inner class for "D" which makes the "D" JLabel visible or 
    invisible depending on the check box.
*/
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class Exercise_9_1_TryCheckBoxes extends JFrame 
{
    private JCheckBox chBoxA = new JCheckBox("A");
    private JCheckBox chBoxB = new JCheckBox("B");
    private JCheckBox chBoxC = new JCheckBox("C");
    private JCheckBox chBoxD = new JCheckBox("D");
   
    private JLabel labelA = new JLabel("A is ON ");
    private JLabel labelB = new JLabel("B is ON ");
    private JLabel labelC = new JLabel("C is ON ");
    private JLabel labelD = new JLabel("D is ON");
    public Exercise_9_1_TryCheckBoxes()
    {
         super("Exercise 9.1: Try CheckBoxes");                                     // puts "Try CheckBoxes in title bar of JFrame
            setLayout(new FlowLayout());                                         // sets JFrame layout
           
            chBoxA.addItemListener(new CheckBoxAHandler());
            chBoxB.addItemListener(new CheckBoxBHandler());
            chBoxC.addItemListener(new CheckBoxCHandler());
            chBoxD.addItemListener(new CheckBoxDHandler());
           
            labelA.setVisible(false); // make label invisible
            labelB.setVisible(false); // make label invisible
            labelC.setVisible(false); // make label invisible
            labelD.setVisible(false); // make label invisible
   
            // put all components into JFrame
            add(chBoxA);
            add(chBoxB);
            add(chBoxC);
            add(chBoxD);
           
            add(labelA);
            add(labelB);   
            add(labelC);
            add(labelD);
     } // end constructor
    public static void main( String [] args )
    {
           Exercise_9_1_TryCheckBoxes tcb = new Exercise_9_1_TryCheckBoxes();
            tcb.setSize(200, 200);
            tcb.setVisible(true);
            tcb.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        // Important - always required
    } // end main
    // inner classes for listener classes
    class CheckBoxAHandler implements ItemListener
    {
        public void itemStateChanged( ItemEvent e )
        {
            if( chBoxA.isSelected() )                                // One way to check if selected
                labelA.setVisible(true);
            else
                labelA.setVisible(false);
        } // end itemStateChanged for check box A
    } // end CheckBoxAHandler listener class
    class CheckBoxBHandler implements ItemListener
    {
        public void itemStateChanged( ItemEvent e )
        {
            if( e.getStateChange() == ItemEvent.SELECTED )             // another way to check if selected
                labelB.setVisible(true);
            else
                labelB.setVisible(false);
        } // end itemStateChanged  for check box B
    } // end CheckBoxBHandler listener class
    class CheckBoxCHandler implements ItemListener
    {
        public void itemStateChanged( ItemEvent e )
        {
            labelC.setVisible(chBoxC.isSelected());                 // BEST WAY
        } // end itemStateChanged for check box C
    } // end CheckBoxCHandler listener class
   
    class CheckBoxDHandler implements ItemListener
    {
        public void itemStateChanged(ItemEvent e)
        {
            labelD.setVisible(chBoxD.isSelected());
        }
    }
} // end class Exercise_9_1_TryCheckBoxes

Exercise 9.2

Example Program for Exercise 9.2

// EXAMPLE 9.2 JAVA CODE AND EXERCISE 9.2 (BELOW)  import java.awt.*;// doesn't include sub-packages import java.awt.event.*;// need to import for events import javax.swing.*;  public class FrameProgram extends JFrame {  private static int TFSIZE = 30;  private static int TRIMSIZE = 20;  private JComboBox comboBox; // a drop-down menu  private JButton trimBtn;  private JButton clearBtn;  private JTextField outText;  private StringBuilder outSB= new StringBuilder();   public FrameProgram(String [] strArray){           super("Frame Program");     // create JComboBox, putting in strings from parameter          comboBox = new JComboBox(strArray);          comboBox.addActionListener(new JComboBoxHandler()); //make a listener object, register it                 outText=new JTextField(TFSIZE);// about 30 chars visible          outText.setEditable(false); // user can’t change it, program can    JButtonHandler jbh = new JButtonHandler(); // create listener object using inner class   trimBtn = new JButton("Trim"); // create a button with "Trim" written on it   trimBtn.addActionListener(jbh); // register the jbh object as listener on trimBtn   clearBtn = new JButton("Clear");// create a button with "Clear" written on it   clearBtn.addActionListener(jbh);// register the jbh object as listener on clearBtn           setLayout(new FlowLayout());//need layout for JFrame   add(comboBox); // adds JComboBox to JFrame   add(outText); // adds JTextfield to JFrame           add(trimBtn); // adds 1st JButton to JFrame   add(clearBtn); // adds 2nd JButton to JFrame         } // end constructor    public static void main( String[] args ){   FrameProgram fp =new FrameProgram(new String []{    "First", "Second", "Third", "Fourth", "Fifth"});   fp.setSize(400, 200);   fp.setVisible(true);   fp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  } // end main   class JComboBoxHandler implements ActionListener {   public void actionPerformed(ActionEvent e){           String chosenStr;     chosenStr = (String) comboBox.getSelectedItem();    outSB.insert(0, chosenStr);    outText.setText(outSB.toString());   } // end actionPerformed  } // end JComboBoxHandler inner class   class JButtonHandler implements ActionListener {//SAME FOR EACH BUTTON   // EXAMPLE OF USING ONE LISTENER FOR BOTH BUTTONS   public void actionPerformed(ActionEvent e){           Object source = e.getSource(); // get the object that triggered event     if( source == trimBtn ){ // if it's the trim button     outSB.setLength(TRIMSIZE);     outText.setText(outSB.toString());    }else // added another if to allow more buttons to handle     if( source == clearBtn ){ // if it's the clear button      outSB.setLength(0);      outText.setText("");     } // end if clearBtn   } // end actionPerformed  } // end JButtonHandler inner class } // end class FrameProgram

/* EXERCISE 9.2 Run the program shown above.

    - THEN change it to have another JButton with "Reverse" on the button, which will reverse the StringBuilder and
    - put back in the JTextField AND add a JComboBox with "10", "20", and "30" choices for changing the trim size to 10, 20 or 30. 
    Be sure to put them in the JFrame, change the JButtonHandler method to have another condition for the Reverse button
    - and add a new inner class for handling the JComboBox (see example 1 used in Exercise 1). 
    Hint: Use the parseInt static method in the Integer class to convert from a String to an int. 
    //EXAMPLE 9.2 JAVA CODE AND EXERCISE 9.2 (BELOW)
*/
import java.awt.*;// doesn't include sub-packages
import java.awt.event.*;// need to import for events
import javax.swing.*;
public class Exercise_9_2_FrameProgram extends JFrame
{
    private static int TFSIZE = 30;
    private static int TRIMSIZE = 20;            // Not needed any more - changed to dropdown selection from user
    private static final String [] A_TRIMSIZE = new String []{"10", "20", "30"};
   
    private JComboBox comboBox;                 // a drop-down menu
    private JComboBox comboBox_TrimSize;         // a second drop-down menu for Trim Size
   
    private JButton trimBtn;
    private JButton clearBtn;
    private JButton reverseBtn;
   
    private JTextField outText;
    private StringBuilder outSB = new StringBuilder();
    public Exercise_9_2_FrameProgram(String [] strArray)
    {
        super("Exercise 9.2: Frame Program");
         // create JComboBox, putting in strings from parameter
         comboBox = new JComboBox(strArray);
         comboBox.addActionListener(new JComboBoxHandler()); //make a listener object, register it
  
         comboBox_TrimSize = new JComboBox(A_TRIMSIZE);
         //comboBox_TrimSize.addActionListener(new JComboBox_TrimSizeHandler());            // Not needed since only want to trim string when user click Trim button, so no action is required
        
         outText = new JTextField(TFSIZE);// about 30 chars visible
         outText.setEditable(false); // user can’t change it, program can
        JButtonHandler jbh = new JButtonHandler(); // create listener object using inner class
        trimBtn = new JButton("Trim");             // create a button with "Trim" written on it
        trimBtn.addActionListener(jbh);         // register the jbh object as listener on trimBtn
        clearBtn = new JButton("Clear");        // create a button with "Clear" written on it
        clearBtn.addActionListener(jbh);        // register the jbh object as listener on clearBtn
        reverseBtn = new JButton("Reverse");
        reverseBtn.addActionListener(jbh);
        setLayout(new FlowLayout());    //need layout for JFrame
        add(comboBox);             // adds JComboBox to JFrame
        add(comboBox_TrimSize);
       
        add(outText);             // adds JTextfield to JFrame
         add(trimBtn);             // adds 1st JButton to JFrame
        add(clearBtn);             // adds 2nd JButton to JFrame
        add(reverseBtn);        // Reverse Button
     } // end constructor
    public static void main( String[] args )
    {
        Exercise_9_2_FrameProgram fp = new Exercise_9_2_FrameProgram(new String []{"First", "Second", "Third", "Fourth", "Fifth"});
       
        fp.setSize(400, 200);
        fp.setVisible(true);
        fp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    } // end main
    class JComboBoxHandler implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
             String chosenStr;
            chosenStr = (String) comboBox.getSelectedItem();
            outSB.insert(0, chosenStr);
            outText.setText(outSB.toString());
        } // end actionPerformed
    } // end JComboBoxHandler inner class
    class JComboBox_TrimSizeHandler implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            // No code is required here for this event
        } // end actionPerformed
    } // end JComboBoxHandler inner class
    class JButtonHandler implements ActionListener
    {    // SAME FOR EACH BUTTON
        // EXAMPLE OF USING ONE LISTENER FOR BOTH BUTTONS
        public void actionPerformed(ActionEvent e)
        {
             Object source = e.getSource();             // get the object that triggered event
            if( source == trimBtn )
            {     // if it's the trim button
                int i_TrimLength = Integer.parseInt((String)comboBox_TrimSize.getSelectedItem());
                outSB.setLength(i_TrimLength);
                outText.setText(outSB.toString());
            }
            else if(source == reverseBtn)
            {
                outSB.reverse();
                outText.setText(outSB.toString());
            }
            else // added another if to allow more buttons to handle
            {
                if( source == clearBtn )
                { // if it's the clear button
                    outSB.setLength(0);
                    outText.setText("");
                } // end if clearBtn
            }
        } // end actionPerformed
    } // end JButtonHandler inner class
} // end class Exercise_9_2_FrameProgram