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

GUI: Additional Examples

Selection Components

We are going to look at check boxes, and radio buttons in the next example:

- JCheckBox responds to ActionListener
- JCheckBox has methods setSelected, isSelected.
- To group together radio buttons, you need to create a ButtonGroup container and add the radio buttons to this group that are part of one radio button group.
- JRadioButton also responds to ActionListener and responds to setSelected and isSelected.
- JRadioButtons need to be added to their ButtonGroup as well as their Container (like JFrame) .

Check.java


import java.awt.*;
import java.awt.event.*; // New Import for Events
import javax.swing.*;

public class Check extends JFrame
    implements ActionListener
{
   JTextArea toutput = new JTextArea(6,40);

   // Regular Check Boxes
   JCheckBox chkCar = new JCheckBox("Own Car?");
   JCheckBox chkStudent = new JCheckBox("Student at WCC?");

   // Radio Button Classes
   ButtonGroup generation = new ButtonGroup();
   JRadioButton[] genChk= new JRadioButton[5];

   String endline;
   String genName[] = {"Senior", "Boomer", "X", "Adolescent", "Infant"};

   public Check(String name) {
        super(name);
        // Default the following checkbox to checked
        setLayout(new FlowLayout());
        chkStudent.setSelected(true);
        add(chkCar);
        add(chkStudent);
        chkCar.addActionListener(this);
        chkStudent.addActionListener(this);

        for (int i=0; i < genName.length; i++)
        {
            JRadioButton rb = new JRadioButton(genName[i],false);
            genChk[i] = rb;
            generation.add(rb); // Add radio button to the generation grouping
            add(rb);
            rb.addActionListener(this);
        }
        // Set default radio button selection
        genChk[2].setSelected(true); // Set generation X by default


        add(toutput);

        endline= System.getProperty("line.separator");
     }

    public void actionPerformed(ActionEvent evt) {

        toutput.append("**********************************" + endline);
        toutput.append("Student at WCC? " +
            chkStudent.isSelected()  + endline);
        toutput.append("Own Car? " +
            chkCar.isSelected()  + endline);

        for (int i=0; i < genChk.length; i++)
            if (genChk[i].isSelected())
            {
                toutput.append("generation: " + genName[i] + endline);
                // Could put a break here and get the same answer
            }


       }


  public static void main(String[] args) {
    Check aFrame = new Check("Check Boxes");

    aFrame.setSize(600,380);
    aFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
    aFrame.setVisible(true);
  } // end of main
}



Optional but Interesting Examples

JList -

- JList is a class that can house a list of items.
- JList can run such that only one item can be selected (left list), or they can be set to allow multiple selections (holding the shift key on the right list)
- You can use JScrollPane to make a JList scrollable
- You can dynamically add or remove items from the JList

Selection.java





import java.awt.*;
import java.awt.event.*; // New Import for Events
import javax.swing.*;

public class Selection extends JFrame
    implements ActionListener
{
   JTextArea toutput = new JTextArea(4,40);
   JTextField tadd = new JTextField(40);

   // Selection List allowing only one selection
   java.util.Vector<String> vList = new java.util.Vector<String>();
   JList myList;

   // Selection List allowing multiple selections
   JList myMultList ;

   String endline;
   String strlist[] ={"zero", "one", "two", "three", "four", "five"};

   public  Selection(String name) {
        super(name);
        setLayout(new FlowLayout());
        for (int i = 0; i < strlist.length; i++)
            vList.add(strlist[i]);

        myList= new JList(vList);
        myList.setVisibleRowCount(3);
        myList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        JScrollPane scrollPane = new JScrollPane(myList);
        myMultList = new JList(vList);

        add (scrollPane);

        add (myMultList);

        add(new Label("********String to add to lists (- in front will remove)***********"));
        add(tadd);
        JButton b = new JButton(
            "--         Click here to get something done       --");
        add(b);
        add(toutput);

        b.addActionListener(this);
        endline= System.getProperty("line.separator");
     }

    public void actionPerformed(ActionEvent evt) {
        String str;
        toutput.setText("");
        toutput.append(" myList selected index = " + myList.getSelectedIndex() +
                        " item = "  + myList.getSelectedValue() + endline);

        int[] indices = myMultList.getSelectedIndices();
        Object[] values = myMultList.getSelectedValues();
        for (int i=0; i < indices.length; i++)
        {
            toutput.append(" myMultList index="+indices[i]+ " value="+ values[i] +endline);
        }

        str = tadd.getText();
        str = str.trim();

        // If any string is found in the tadd TextField, we will either try
        // to add a string to the choice, list and multiple list components
        // or remove a string.  Removing happens if the string starts with a "-"

        if (str.length() > 0)
        {
            if (str.charAt(0) != '-')
                {
                    vList.add(str);
                    myList.setListData(vList);
                    myMultList.setListData(vList);
                    toutput.append("Successfully added " + str +
                        " to lists " + endline);

                }
             else
                {
                    // Remove from lists

                    str = str.substring(1); // remove - sign
                    if (vList.remove(str))
                        toutput.append("Successfully removed " + str +
                                " from lists " + endline);


                }
        }
       }


  public static void main(String[] args) {
    Selection aFrame = new Selection("Selection");
    aFrame.setSize(600,480);
    aFrame.setVisible(true);
  } // end of main
}



GridBagLayout Manager

So the GridLayout is simple but very constraining --- each component is displayed with the same width and height. You need something more flexible. Well you got it, but flexibility is usually associated with complexity, and that is the biggest problem with the GridBagLayout manager.

For those of you who understand how to use all of the flexibility in HTML tables to control how your HTML page is laid out, you might appreciate GridBagLayout, because it has many of the same features as you find in HTML table commands.

How does it work?

1. The first step is to create an instance of GridBagLayout and call setLayout just like we did with all of the other Layout managers above.
2. The next step is to recognize that each component added can have its own unique constraints specified. So to do this we need an instance of a new class called the GridBagConstraints class.
3. The GridBagConstraints class has many constraints that can be specified. See the following table:
GridBagConstraints Table . We will only use a few of these features here.
4. Once you have the constraints class setup (note that anything not specified has a default) and you have created your component, you tell the GridBagLayout manager with a call that looks like:
gblay.setConstraints(c, gbc);
where gblay is the instance of the GridBagLayout manager, c is the component of interest and gbc is the GridBagConstraints class containing the values of all the applicable constraints.
5. Then you just add the component to the Container just like any of the previous Layout Managers.

Note that because of the flexibility, the GridBagLayout allows each column to have its own width, and each row can have its own height.

To hide most of the complexity below we create a method called gbadd that takes care of all of the constraint stuff. Also note that we are mostly using the width constraint (there are many other constraints). The gbadd routine takes a parameter to specify the width. A 1 implies one column width, while a 2 indicates that component spans two columns. A -1 on the other hand indicates that this component marks the end of a row.

We do set a few constraints for all components added to the GridBagLayout.

CalcGridBag.java


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


public class CalcGridBag extends JFrame
        implements ActionListener {
    JButton bdigit[] = new JButton[10];
    JButton clear = new JButton("clear");
    JButton minus = new JButton("   -   ");
    JButton plus =  new JButton("   +   ");

    JButton equals = new JButton("   =   ");

    JTextField display = new JTextField(30);
    GridBagLayout gblay = new GridBagLayout();
    GridBagConstraints gbc = new GridBagConstraints();
    final int numCols = 4;
    int colCount = 0;
//******************************************

    // GridBag add routine to take care
    // of some of the ugly details.

    void gbAdd(Component c, int width)
    {
        if (width < 0)
        {
            // Make this component the end of the row
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            colCount = 0;
        }
        else
        {
            colCount += width;
            if (colCount >= numCols)
            {
                // Make this component the end of the row
                gbc.gridwidth =  GridBagConstraints.REMAINDER;
                colCount = 0;
            }
            else
            {
                // Provide the requested Width
                gbc.gridwidth = width;
            }
        }

        // Finally tell Gridbaglayout about the constraints
        // associated with this Component
        gblay.setConstraints(c, gbc);

        add(c); // add to the container
    }
  //**************************************

    public CalcGridBag() {
        super("Grid Bag Layout");
        setSize(300,250);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        // Fill in a few constraints
        gbc.weightx = gbc.weighty =1.0;
        gbc.fill = GridBagConstraints.BOTH;
        gbc.insets = new Insets(3,3,3,3);

        setLayout(gblay);
        setBackground(Color.yellow);

        gbAdd(display, -1); // Line by itself

        Color buttonColor = new Color(180,180,255);
        for (int i=0; i < bdigit.length; i++)
        {
            bdigit[i] = new JButton("" + i);
            bdigit[i].addActionListener(this);
            bdigit[i].setBackground(buttonColor);
            gbAdd(bdigit[i], 1); // normal button size
        }

        clear.addActionListener(this);
        gbAdd(clear, 1); // normal button size

        minus.addActionListener(this);
        gbAdd(minus, 1); // normal button size

        gbAdd(plus, 2); // double  button size
        plus.addActionListener(this);

        gbAdd(equals, 2); // double  button size
        equals.addActionListener(this);
    }

    public void actionPerformed(ActionEvent e) {
       if (e.getSource() == clear)
       {
            display.setText("");
       }
       else if (e.getSource() == plus)
       {

       }
       else if (e.getSource() == minus)
       {

       }

       else if (e.getSource() == equals)
       {

       }

       else
       {    // Must be a digit
            String str = e.getActionCommand();
            String str_display = display.getText();
            display.setText( str_display + str);
       }

    }


  public static void main(String[] args) {
    CalcGridBag calc = new CalcGridBag();
    calc.setVisible(true);
  } // end of main
}




CardLayout Manager

The CardLayout manager lets you have different views of your screen that are like independant Cards that can be displayed. For example, in the following example, we have 3 Cards (or Panels of Gui stuff). At any point in time, we only display one Card at a time.

A Card is defined to be a Component, but it is more likely to be a Panel (remember a Panel is derived from Component).

In the example below we create 3 cards with names. The cards are added to the container along with their associated names. The 3 cards contain:

- Panel panelFor3Buttons - contains 3 buttons
- Panel panelForText - contains a TextField and a button
- Single Button Component

When we want to show a specific card, we call the show method. The first parameter to show is a pointer to the container, which is our Applet itself. The second parameter is the name of the card to show.

Wizard.java - A Card Layout



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


public class Wizard extends JFrame
                        implements ActionListener {

   CardLayout cardLayoutMgr = new CardLayout();
   JPanel panelForText = new JPanel();
   Panel panelFor3Buttons = new Panel();
   String BUTTONPANEL="ButtonPanel";
   String TEXTPANEL="TextPanel";
   String SINGLE_BUTTON="ButtonComponent";

   JButton next1 = new JButton("Next 1");
   JButton next2 = new JButton("Next 2");
   JButton next3 = new JButton("Next 3");

  public Wizard() {
       super("Wizard");
       setSize(300,150);
       setDefaultCloseOperation(EXIT_ON_CLOSE);
       setLayout(cardLayoutMgr);
       setBackground(Color.yellow);

       next1.setBackground(Color.red);
       next2.setBackground(Color.red);
       next3.setBackground(Color.red);

       next1.addActionListener(this);
       next2.addActionListener(this);
       next3.addActionListener(this);

   // Build up Panel : panelFor3Buttons
       panelFor3Buttons.add(new JButton("Button 1"));
       panelFor3Buttons.add(new JButton("Button 2"));
       panelFor3Buttons.add(next1);
       panelFor3Buttons.setBackground(Color.green);

   // Build up Panel : panelForText
       panelForText.add(new JTextField("TextField", 20));
       panelForText.add(next2);
       panelForText.setBackground(Color.orange);

     // Finally add the 3 "Cards" to the CardLayout Manager
     // Note that each card only needs to be a Component.
     // A Button is OK, and a Panel is OK too.

       add(BUTTONPANEL, panelFor3Buttons);
       add(TEXTPANEL, panelForText);
       add(SINGLE_BUTTON, next3);

       setBackground(Color.pink);

       // Tell the cardLayout Manager to start with the 3 button panel
       cardLayoutMgr.show(this.getContentPane(), BUTTONPANEL);

    }

  public void actionPerformed(ActionEvent evt) {
       if (evt.getSource() == next1)
           cardLayoutMgr.show(this.getContentPane(), TEXTPANEL);
        if (evt.getSource() == next2)
                cardLayoutMgr.show(this.getContentPane(), SINGLE_BUTTON);
        if (evt.getSource() == next3)
                cardLayoutMgr.show(this.getContentPane(), BUTTONPANEL);


    }

  public static void main(String[] args) {
    Wizard w = new Wizard();
    w.setVisible(true);
  } // end of main


}


Null Layout Manager Approach

In general, Container classes have default layout managers. The JFrame class defaults to a BorderLayout if nothing is specified.

When you want to create a different layout manager, you use the setLayout method from the Container class. If you pass a null to setLayout, you are basically saying you want to take complete control of positioning your Components within the Container.

In order to position your Components, you call setBounds with the desired coordinates for each Component that needs to be positioned. You can call setBounds in the paint method or in some initialization routine such as init in the case of an Applet.

When you do, you have to specify the locations for each of your components. Normally, this is not recommended because of the different platforms that you may want to be running on. If you take this approach, you have to figure out the pixel locations for each of your components. Keep in mind these Components can have different sizes on different platforms.

None.java


public class None extends JFrame {
    private JButton b1, b2, b3;
    int count = 0;

    public None() {
        super("None");
        setSize(400,450);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(null);

        b1 = new JButton("one");
        add(b1);
        b2 = new JButton("two");
        add(b2);
        b3 = new JButton("three");
        add(b3);

        b1.setBounds(50,  5,  100, 20);
        b2.setBounds(70,  35, 100, 20);
       // b3.setBounds(130, 45, 100, 50);
    }

    public void paint(Graphics g) {
         super.paint(g);
         // Note that I can also do the setBounds in the paint method.
         b3.setBounds(130, 45, 100, 50);
         System.out.println("paint called, count = " + count++);
    }
    public static void main(String[] args)
    {
        None none = new None();
        none.setVisible(true);
    }

}


MyButtonClass: Creating your own Button class


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


public class MyButtonClassDemo extends JFrame implements ActionListener{
    MyButtonClass b1 , b2;
    MyButtonClassDemo()
    {
        setLayout(new FlowLayout());
        setSize(500, 300);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        b1 = new MyButtonClass("A long string to place on a button");
        b2 = new MyButtonClass("Somewhat long string");
        b1.addActionListener(this);
        b2.addActionListener(this);
        add(b1);
        add(b2);
    }
    public void actionPerformed(ActionEvent e)
    {
        System.out.println("actionPerformed called: "+ e.getActionCommand());
        if (e.getSource() == b1)
            System.out.println("b1 is the source");
        if (e.getSource() == b2)
            System.out.println("b2 is the source");
    }
    public static void main(String[] args)
    {
        MyButtonClassDemo mb = new MyButtonClassDemo();
        mb.setVisible(true);
    }

}


//*********************************************************
//*********************************************************


import java.awt.*;
import java.awt.event.*;
// Note NO SWING import

class MyButtonClass extends Canvas implements MouseListener {

    static final int    GC_BUTTON_BORDER_THICKNESS=8;
    static final int    GC_BUTTON_HORIZ_PAD=3;
    static final int    GC_BUTTON_VERT_PAD=2;

    static final int    GC_CANVAS_HORIZ_GAP=10;
    static final int    GC_CANVAS_VERT_GAP=10;

    String ButtonName;
    Color ButtonColor=Color.yellow;
    boolean raised=true;
    int    fontMaxAscent;
    Rectangle gRectangle=new Rectangle();
    Font                buttonFont ;
    ActionListener   actionListener=null;


//Constructor:

public MyButtonClass(String name)
{
    ButtonName = name;
    int nameTextWidth, nameTextHeight;
    FontMetrics            buttonFontMetrics;

    buttonFont = new Font("Courier", Font.BOLD, 12);
    System.out.println("Default font= " +buttonFont);
    buttonFontMetrics = getFontMetrics(buttonFont);
    nameTextWidth = buttonFontMetrics.stringWidth(name) ;
    nameTextHeight=buttonFontMetrics.getHeight() ;
    fontMaxAscent = buttonFontMetrics.getMaxAscent();

// Create a Rectangle with the size of the Center Text Area
    gRectangle.setBounds(GC_CANVAS_HORIZ_GAP, GC_CANVAS_VERT_GAP,
            nameTextWidth+2*(GC_BUTTON_HORIZ_PAD + GC_BUTTON_BORDER_THICKNESS),
            nameTextHeight+2*(GC_BUTTON_VERT_PAD + GC_BUTTON_BORDER_THICKNESS));

    addMouseListener(this);

}

// Need to tell the layout manager how big our button is

public Dimension getPreferredSize()
{
    Dimension d=new Dimension(gRectangle.width+2*GC_CANVAS_HORIZ_GAP,
        gRectangle.height+2*GC_CANVAS_VERT_GAP);
    return d;
}

public Dimension getMinimumSize()
{
    Dimension d=new Dimension(gRectangle.width, gRectangle.height);
    return d;
}

public void mouseEntered(MouseEvent e) {
    }
    public void mouseExited(MouseEvent e) {
    }
    public void mouseClicked(MouseEvent e) {
    }
    public void mouseReleased(MouseEvent e) {
    }
public void mousePressed(MouseEvent e) {
    e.consume();
    int x= e.getX();
    int y=e.getY();
    System.out.println("MouseDown x = "+ x + " y= " + y);

    if (gRectangle.contains(x,y))
        {
             System.out.println("Click inside " + ButtonName);
             if (raised)
                 raised = false;
              else
                  raised = true;

             if (actionListener!=null)
                actionListener.actionPerformed(new ActionEvent(this, 1, ButtonName));
            repaint();
         }
        else
            {
            System.out.println("Click NOT inside " + ButtonName);
            }

}
public void addActionListener(ActionListener actionListener)
{
    this.actionListener = actionListener;
}
// --------------------------------------------------------------------------
// The following routine draws a 3D button.  Normal Java 3D buttons
// only have borders of 1 pixel.  This routine uses brute force to make
// a larger border by drawing multiple rectangles to get the big 3D effect.
// --------------------------------------------------------------------------
public void paint(Graphics g)
{
    int i;
    int x=gRectangle.x;
    int y = gRectangle.y;
    int width=gRectangle.width;
    int height=gRectangle.height;

    g.setColor(ButtonColor);
   // Clickable Button
       // Unfortunately Java doesn't seem to have the concept of thickness
       // for borders.  To get a border of a certain thickness, we have to
       // draw multiple rectangles having slightly different sizes

       for (i=0; i < GC_BUTTON_BORDER_THICKNESS; i++)
       {
          g.draw3DRect(x+i, y+i, width - 2*i+1, height - 2*i+1, raised);
       }
       g.fillRect(x+GC_BUTTON_BORDER_THICKNESS,
                   y+GC_BUTTON_BORDER_THICKNESS,
                   width -2* GC_BUTTON_BORDER_THICKNESS+2,
                   height - 2*GC_BUTTON_BORDER_THICKNESS+2);

    // Put the label on the button

    g.setColor(Color.black);
    g.setFont(buttonFont);
    g.drawString(ButtonName, x+GC_BUTTON_BORDER_THICKNESS+GC_BUTTON_HORIZ_PAD,
          y+GC_BUTTON_BORDER_THICKNESS+GC_BUTTON_VERT_PAD+fontMaxAscent);


    // The following was added to see how big the alloted Canvas area was that was
    // made available to our MyButtonClass

    g.drawRect(0,0, gRectangle.width+2*GC_CANVAS_HORIZ_GAP-1,
         gRectangle.height+2*GC_CANVAS_VERT_GAP-1);

   }
	
   class Rectangle
   {
    int x, y, width, height;

    void setBounds(int x, int y, int width, int height)
    {
        this.x =x;
        this.y =y;
        this.width = width;
        this.height = height;
    }
    boolean contains(int px, int py)
    {
        if (px >= x && px <= (px+width) && py >= y && py <= (y+height))
            return true;
        else
            return false;
    }
  }
 }












Custom Layout Manager



// CustomLayout.java

import javax.swing.*;



public class CustomLayout extends JFrame {
  public CustomLayout() {
    super("CustomLayout");
    setSize(400, 500);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setLayout(new DiagonalLayout());
    add (new JButton ("Button 1"));
    add (new JButton ("Button 2"));
    add (new JButton ("Extra Long Long Button 3"));
    add (new JButton ("Button 4"));
    add (new JButton ("Button 5"));
    add (new JButton ("Button 6"));
    add (new JButton ("Button 7"));
    add (new JButton ("Button 8"));
    add (new JButton ("Button 9"));
    }


// A main() for the application:
  public static void main(String[] args) {
    CustomLayout cl = new CustomLayout();
    cl.setVisible(true);
  }

}





import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.LayoutManager;

public class DiagonalLayout implements LayoutManager {
    private int vgap;
    private int minWidth = 0, minHeight = 0;
    private int preferredWidth = 0, preferredHeight = 0;
    private boolean sizeUnknown = true;

    public DiagonalLayout() {
        this(5);
    }

    public DiagonalLayout(int v) {
        vgap = v;
    }

    /* Required by LayoutManager. */
    public void addLayoutComponent(String name, Component comp) {
    }

    /* Required by LayoutManager. */
    public void removeLayoutComponent(Component comp) {
    }

    private void setSizes(Container parent) {
        int nComps = parent.getComponentCount();
        Dimension d = null;

        //Reset preferred/minimum width and height.
        preferredWidth = 0;
        preferredHeight = 0;
        minWidth = 0;
        minHeight = 0;

        for (int i = 0; i < nComps; i++)
        {
            Component c = parent.getComponent(i);
            if (c.isVisible())
            {
                d = c.getPreferredSize();

                if (i > 0) {
                    preferredWidth += d.width/2;
                    preferredHeight += vgap;
                }
                else
                {
                    preferredWidth = d.width;
                }
                preferredHeight += d.height;

                minWidth = Math.max(c.getMinimumSize().width,
                                    minWidth);
                minHeight = preferredHeight;
            }
        }
        System.out.println("preferredWidth = "+preferredWidth + " preferredHeight =" +
                    preferredHeight);
        System.out.println("minWidth = "+minWidth + " minHeight =" +
                    minHeight);


    }


    /* Required by LayoutManager. */
    public Dimension preferredLayoutSize(Container parent)
    {
        Dimension dim = new Dimension(0, 0);

        if (sizeUnknown)  setSizes(parent);
        sizeUnknown=true;

        //Always add the container's insets!
        Insets insets = parent.getInsets();
        dim.width = preferredWidth
                    + insets.left + insets.right;
        dim.height = preferredHeight
                     + insets.top + insets.bottom;

        return dim;
    }

    /* Required by LayoutManager. */
    public Dimension minimumLayoutSize(Container parent)
    {
        Dimension dim = new Dimension(0, 0);

        if (sizeUnknown)  setSizes(parent);
        sizeUnknown=true;

        //Always add the container's insets!
        Insets insets = parent.getInsets();
        dim.width = minWidth
                    + insets.left + insets.right;
        dim.height = minHeight
                     + insets.top + insets.bottom;


        return dim;
    }

    /* Required by LayoutManager. */
    /*
     * This is called when the panel is first displayed,
     * and every time its size changes.
     * Note: You CAN'T assume preferredLayoutSize or
     * minimumLayoutSize will be called --
     */
    public void layoutContainer(Container parent)
    {
        Insets insets = parent.getInsets();
        int maxWidth = parent.getSize().width
                       - (insets.left + insets.right);
        int maxHeight = parent.getSize().height
                        - (insets.top + insets.bottom);
        int nComps = parent.getComponentCount();
        int previousWidth = 0, previousHeight = 0;
        int x = 0, y = insets.top;
        int xFudge = 0, yFudge = 0;
        boolean oneColumn = false;

        // Go through the components' sizes, if neither
        // preferredLayoutSize nor minimumLayoutSize has
        // been called.
        if (sizeUnknown)  setSizes(parent);
        sizeUnknown=true;


        if (maxWidth <= minWidth) {
            oneColumn = true;
        }

        if (maxWidth != preferredWidth) {
            xFudge = (maxWidth - preferredWidth)/(nComps - 1);
        }

        if (maxHeight > preferredHeight) {
            yFudge = (maxHeight - preferredHeight)/(nComps - 1);
        }

        for (int i = 0 ; i < nComps ; i++)
        {
            Component c = parent.getComponent(i);
            if (c.isVisible()) {
                Dimension d = c.getPreferredSize();

                 // increase x and y, if appropriate
                if (i > 0)
                {
                    if (!oneColumn) {
                        x += previousWidth/2 + xFudge;
                    }
                    y += previousHeight + vgap + yFudge;
                }

                // If x is too large,
                if ((!oneColumn) && (x + d.width) > (parent.getSize().width - insets.right))
                {
                    // reduce x to a reasonable number.
                    x = parent.getSize().width - insets.right - d.width;
                }

                // If y is too large,
                if ((y + d.height) > (parent.getSize().height - insets.bottom))
                {
                    // do nothing.
                    // Another choice would be to do what we do to x.
                }

                // Set the component's size and position.
                c.setBounds(x, y, d.width, d.height);

                previousWidth = d.width;
                previousHeight = d.height;
            }
        }
    }
}





The following are not assigned exercises. However, if you have extra time and want something to do to practice your GUI skills, the following are some options.

Exercises:

1. Create a GUI Tic-Tac-Toe game. Use a BorderLayout. In the NORTH, put a Reset button and a JTextField to store results of the game. In the CENTER, create a JPanel with a GridLayout of a 3x3 of JButton. Initially have all of the JButtons contain a String of "". When JButton containing "" is clicked, put either an "X" or "O". The reset button should reset all JButtons back to "". Note that setText and getText work for JButtons the same as for JTextField. You may want to create a larger Font for the 3x3 JButtons.
2. Go back to the Drawing program we left on the discussion board with Scribble in it. Create a drawing program using a BorderLayout. In the CENTER, place the program we last did (we will need to have it derived from JPanel instead of JFrame). In the South, create 3 buttons to control whether we are drawing an Oval, Rectangle or Scribble. In the North create Buttons for the desired colors like Red, Green, Blue. We will try to do this in class, but I have a discussion board entry that is completed in case we run out of time.
3. Change this program to use Menus instead of buttons.

Job Application Form

Create a job application form applet that utilizes most of the Components we have covered so far. When you click an Apply button, the results of the application form should be written to System.out.println. Your applet should demonstrate at least the following Components:

1. Textfield
2. List
3. Choice
4. Checkbox (both flavors : radiobutton type, versus checkbox type)
5. Label

You can put any fields you want in your application, but here are some recommendations:

You could have the following textfields:
Name, address, Social Security number

For a List box, you might have your applicant pick from a list of skills that you provide. For example,
C++, Java, Html, MFC, Visual Basic, Oracle, etc.

For a choice box, you might have a list of states. You might only want to put in a few of the local states. I.e.:
Michigan, Indiana, Ohio, Wisconsin, Illinois

For a Checkbox (non-radio type), you could choose something like:
Married, Veteran, Own Car

For a radio button you could choose,
Sex: Male/Female , Eye Color: Blue/Brown/Green/Other

Use the Label component to properly label the input fields of your application.

Calculator Example

Create a Command Line Form Based Calculator Program.

Your program should at least implement the first 2 items in the following list. The last 2 items are for an extra challenge.
- Your programs provide simple calculator functionality. Your program should have the name Calculator. You only need to handle 10 digit buttons (0,1, ... 9), the "+" button, the "=" button a clear button and a text field for the result. Don't worry about the button layouts for now. We will deal with that later.
- Add additional buttons for multiply and divide. Don't let a user divide by zero and blow up your calculator
- Add additional buttons for sin, cos, tan. You can find out about these functions in the language Math class. You might want to have some option to select between degrees or radians for the input angle.
- Add a choice drop-down box for storing intermediate results. You might want a button to add an intermediate result to your drop-down list, and perhaps some other button to delete one or more intermediate results.

Last Updated: September 19, 2013 10:09 AM