hello I'm haveing alot of trouble here, i couldnt figure out how to get the pie to reflect my amoritization output using on only 2 slices and I haev to hand in something today so I thought I would jsut color the 4 sections with representative colors. If a person chose option 1 and clicked on display pie then the corresponding chart woudl appear but when I click on display pie nothing happens. and advice woudl be greatly apprecaited by a novice.

import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.NumberFormat;

import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;


/**
 * This is code based on the layout design created by David Lilley
 * POS 407 student January 2006. He wanted this layout and could not
 * achieve it as he wanted. I wrote the code to show him how to do it in
 * return for me using the code as an example for future classes. I hope you
 * enjoy.
 * @author Chip Dickson
 */
public class LayoutExample1 extends JFrame implements ActionListener
{
	private static final long serialVersionUID = 4364582253350924044L;

	private Container jContentPane = null;
	private JSplitPane splitpane = null;
	private JPanel leftpanel = null;
	private JScrollPane rightpane = null;
	private JTextArea amortization_out = null;
	private JRadioButton option1 = null;
	private JRadioButton option2 = null;
	private JRadioButton option3 = null;
	private ButtonGroup btgroup_options;
	private ButtonGroup btgroup_plans;
	private JLabel lb_terms = null;
	private JTextField tf_terms = null;
	private JLabel lb_interest = null;
	private JTextField tf_interest = null;
	private JLabel lb_principal = null;
	private JTextField tf_principal = null;
	private JCheckBox plan_a = null;
	private JCheckBox plan_b = null;
	private JButton calc_button = null;
	private JButton exit_button = null;
	private JLabel lb_payment=null;
	private JTextField tf_payment = null;
	private JButton clear_button = null;
	private JButton show_pie = null;
	
    private String[] listItems;
	private NumberFormat fmt = NumberFormat.getInstance();
    
    String[] pieitems = {"5.35", "5.50", "7.50", "8.50"};
    Color uneasyBeingGreen = new Color(0xCC, 0xCC, 0x99);
    Color zuzusPetals = new Color(0xCC, 0x66, 0xFF);
    Color zootSuit = new Color(0x66, 0x66, 0x99);
    Color sweetHomeAvocado = new Color(0x66, 0x99, 0x66);
    Color shrinkingViolet = new Color(0x66, 0x66, 0x99);
    Color miamiNice = new Color(0x33, 0xFF, 0xFF);
    Color inBetweenGreen = new Color(0x00, 0x99, 0x66);
    Color norwegianBlue = new Color(0x33, 0xCC, 0xCC);
    Color purpleRain = new Color(0x66, 0x33, 0x99);
    Color freckle = new Color(0x99, 0x66, 0x33);
   
    /**
     * Constructor
     */
	public LayoutExample1()
	{
		super();
		initialize();
	}

	/**
	 * Initialize everyting.
	 *
	 */
	private void initialize()
	{
	    listItems = loadListItems("loadtest.txt");
		// set up the basics
		// set up the number formatter... BTW there is also a currency formatter
		fmt.setGroupingUsed(true);
		fmt.setMaximumFractionDigits(2);
		fmt.setMinimumFractionDigits(2);
		
		jContentPane = this.getContentPane();
		setTitle("Mcbride Financial Services Mortgage Calculator");   // I changed title
		setSize(800, 600);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		// Notice the top pane is just a simple BoxLayout
		jContentPane.setLayout(new BoxLayout(jContentPane, BoxLayout.X_AXIS));
		// create a splitpane to layout out code
		splitpane = new JSplitPane();
		// make the splitter up and down...
		splitpane.setOrientation(JSplitPane.VERTICAL_SPLIT);
		splitpane.setDividerSize(2);
		splitpane.setDividerLocation(200); // set the divider a little off from the middle
		//splitpane.setEnabled(false); // locks the divider bar
		// Call the method to load the left side of the split pane
		loadLeftSide();
		// load the right side of the split pane
		loadRightSide();
		// add the split pane to the content pane
		jContentPane.add(splitpane, null);
	}
	
    private String [] loadListItems(String filename)
    {
        // assumes you have 4 entries in your file
        String [] retval = new String [4];
        int index = 0;
        try
        {
        	// If you are not an applet, uncomment these two lines and comment out the other 2.
        	File fromFile = new File(filename);
            BufferedReader reader = new BufferedReader(new FileReader(fromFile));
                        String line = reader.readLine();
            while(line != null)
            {
                retval[index] = line;
                line = reader.readLine();
                index++;
            }
            return retval;
        }
        catch (IOException e)
        {
            System.err.println(e.getMessage());
            return null;
        }
    }


	/**
	 * 
	 */
	private void loadRightSide()
	{
		// Not much to the right side... just a JScrollPane and the textArea to go in it...
		rightpane = new JScrollPane();
		// make the scroll bars always be there
		rightpane.setHorizontalScrollBarPolicy(javax.swing.JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
		rightpane.setVerticalScrollBarPolicy(javax.swing.JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
		// give ourselves a nice boarder
		rightpane.setViewportBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
		amortization_out = new JTextArea();
		Font displayFont = new Font("Serif", Font.BOLD, 14);

		// don't want folks typing in here... so we better not let them.
		amortization_out.setEditable(false);
		amortization_out.setFont(displayFont);
		amortization_out.setText("This is some sample text.\nIt shows how this might look.");

		rightpane.setViewportView(amortization_out);
		splitpane.setRightComponent(rightpane);
	}

	/**
	 * 
	 */
	private void loadLeftSide()
	{
		leftpanel = new JPanel();
		leftpanel.setComponentOrientation(java.awt.ComponentOrientation.LEFT_TO_RIGHT);
		// add a nice boarder to the panel
		leftpanel.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.SoftBevelBorder.LOWERED));
		//		 we are using a grid bag layout for this... 
		leftpanel.setLayout(new GridBagLayout());
		// we want 2 button groups (one on top, one on the bottom)
		// this is how you make your radio buttons turn off when another is clicked on
		btgroup_options = new ButtonGroup();
		btgroup_plans = new ButtonGroup();

		// GridBagLayout Base constraints
		GridBagConstraints gridBagConstraints = new GridBagConstraints();
		gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 0);
		gridBagConstraints.gridy = 0;
		gridBagConstraints.ipadx = 0;
		gridBagConstraints.ipady = 0;
		gridBagConstraints.gridx = 0;
		// Create all our components
		option1 = new JRadioButton(listItems[0]);
		option1.addActionListener(this);
		option2 = new JRadioButton(listItems[1]);
		option2.addActionListener(this);
		option3 = new JRadioButton(listItems[2]);
		option3.addActionListener(this);
		// put the buttons in a group
		btgroup_options.add(option1);
		option1.setSelected(true); // sets the default button on
		btgroup_options.add(option2);
		btgroup_options.add(option3);
		lb_terms = new JLabel("Terms");
		lb_interest = new JLabel("Interest");
		lb_principal = new JLabel("Principal");
		lb_payment = new JLabel("Payment");
		// we are strtin with option 1 selected... so lets put the text in our fields
		String [] selection = listItems[0].split("% for "); // should leave us with the rate and the years
		tf_terms = new JTextField();
		tf_terms.setText(selection[1].substring(0,2).trim());
		tf_terms.setEditable(false); // can't edit because we are in preset mode.
		tf_interest = new JTextField(selection[0]);
		tf_interest.setEditable(false);
		tf_principal = new JTextField();
		tf_payment = new JTextField();
		tf_payment.setEditable(false);
		plan_a = new JCheckBox("Manual Entry");
		plan_a.addActionListener(this);
		plan_b = new JCheckBox("Prepared Plan");
		plan_b.addActionListener(this);
		plan_b.setSelected(true); // sets the default selection
		btgroup_plans.add(plan_a);
		btgroup_plans.add(plan_b);
		calc_button = new JButton("Calculate");
		// add the action listener
		calc_button.addActionListener(this);
		clear_button = new JButton("Clear");  // me
		// add the clear action command         me
		clear_button.addActionListener(this);// me
		exit_button = new JButton("Exit");
		// add the action listener
		exit_button.addActionListener(this);
		
		show_pie = new JButton("Show Pie");
		show_pie.addActionListener(this);
		
		// lay the components out
		// all of these are on the first row (y=0)
		leftpanel.add(option1, gridBagConstraints);
		gridBagConstraints.gridx = 1;
		leftpanel.add(option2, gridBagConstraints);
		gridBagConstraints.gridx = 2;
		leftpanel.add(option3, gridBagConstraints);
		// **** Second row
		gridBagConstraints.gridx = 0;
		gridBagConstraints.gridy = 1;
		leftpanel.add(lb_terms, gridBagConstraints);
		gridBagConstraints.gridx = 1;
		// we want the text fields to go across 2 cells
		gridBagConstraints.gridwidth = 2;
		// ... and we want it to fill the space
		gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
		leftpanel.add(tf_terms, gridBagConstraints);
		// set everything back to default
		gridBagConstraints.fill = java.awt.GridBagConstraints.NONE;
		gridBagConstraints.gridwidth = 1;
		//  **** Third row
		gridBagConstraints.gridx = 0;
		gridBagConstraints.gridy = 2;
		leftpanel.add(lb_interest, gridBagConstraints);
		gridBagConstraints.gridx = 1;
		// we want the text fields to go across 2 cells
		gridBagConstraints.gridwidth = 2;
		// ... and we want it to fill the space
		gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
		leftpanel.add(tf_interest, gridBagConstraints);
		// set everything back to default
		gridBagConstraints.fill = java.awt.GridBagConstraints.NONE;
		gridBagConstraints.gridwidth = 1;
		//  **** Fourth row
		gridBagConstraints.gridx = 0;
		gridBagConstraints.gridy = 3;
		leftpanel.add(lb_principal, gridBagConstraints);
		gridBagConstraints.gridx = 1;
		// we want the text fields to go across 2 cells
		gridBagConstraints.gridwidth = 2;
		// ... and we want it to fill the space
		gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
		leftpanel.add(tf_principal, gridBagConstraints);
		// set everything back to default
		gridBagConstraints.fill = java.awt.GridBagConstraints.NONE;
		gridBagConstraints.gridwidth = 1;
		//  **** Fith row
		gridBagConstraints.gridx = 0;
		gridBagConstraints.gridy = 4;
		leftpanel.add(lb_payment, gridBagConstraints);
		gridBagConstraints.gridx = 1;
		// we want the text fields to go across 2 cells
		gridBagConstraints.gridwidth = 2;
		// ... and we want it to fill the space
		gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
		leftpanel.add(tf_payment, gridBagConstraints);
		
		
		// set everything back to default
		gridBagConstraints.fill = java.awt.GridBagConstraints.NONE;
		gridBagConstraints.gridwidth = 1;
		// **** Sixth Row
		gridBagConstraints.gridx = 0;
		gridBagConstraints.gridy = 5;
		leftpanel.add(plan_a, gridBagConstraints);
		gridBagConstraints.gridx = 1;
		leftpanel.add(plan_b, gridBagConstraints);
		// Buttons are sort of funny, so we have to do a little extra work to get them to look right
		// in this layout. I will create individual contraints for each... you could create constrains
		// for every component, and in a more sophisticated layout, you probably would.
		// **** Seventh row
		GridBagConstraints calc_constraints = new GridBagConstraints();
		calc_constraints.insets = new java.awt.Insets(0, 0, 0, 0);
		calc_constraints.gridy = 6;
		calc_constraints.ipadx = 10;
		calc_constraints.ipady = 11;
		calc_constraints.gridx = 0;
		leftpanel.add(calc_button, calc_constraints);
		
		
		GridBagConstraints clear_constraints = new GridBagConstraints();   // me
		clear_constraints.insets = new java.awt.Insets(0, 0, 0, 0);        // me
		clear_constraints.gridy = 6;									   // me
		clear_constraints.ipadx = 20;									   // me
		clear_constraints.ipady = 11;                                      // me
		clear_constraints.gridx = 1;                                       // me
		leftpanel.add(clear_button, clear_constraints);                    // me
		
		GridBagConstraints pie_constraints = new GridBagConstraints();
		pie_constraints.insets = new java.awt.Insets(0, 0, 0, 0);
		pie_constraints.gridy = 6;
		pie_constraints.ipadx = 30;
		pie_constraints.ipady = 11;
		pie_constraints.gridx = 2;
		leftpanel.add(show_pie, pie_constraints);

		
		GridBagConstraints exit_constraints = new GridBagConstraints();
		exit_constraints.insets = new java.awt.Insets(0, 0, 0, 0);
		exit_constraints.gridy = 6;
		exit_constraints.ipadx = 40;
		exit_constraints.ipady = 11;
		exit_constraints.gridx = 3;
		leftpanel.add(exit_button, exit_constraints);

		// put the left hand side in the split pane
		splitpane.setLeftComponent(leftpanel);
	}

	/* (non-Javadoc)
	 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
	 */
	public void actionPerformed(ActionEvent e)
	{
		Object source = e.getSource();
		if(source == show_pie)
		{
			if (source == option1)
			{
			// this is totally useless, but you can put what ever you like in place of the pieitems
			// This would NOT meet the requirements... what you put in the pie, or a graph would need
			// to be related to a mortgage.
            PiePanel pie2 = new PiePanel(listItems.length);
            pie2.addSlice(purpleRain, Float.parseFloat(pieitems[0]));
            pie2.addSlice(inBetweenGreen, Float.parseFloat(pieitems[1]));
            pie2.addSlice(inBetweenGreen, Float.parseFloat(pieitems[2]));
            pie2.addSlice(inBetweenGreen, Float.parseFloat(pieitems[3]));
            final JFrame frame = new JFrame("Purple = interest, Green = Principal");   // added title as pie label
            frame.getContentPane().add(pie2);
            frame.pack();
            frame.setSize(500,500);
            frame.setVisible(true);
			}
			if (source == option2)
			{
				PiePanel pie2 = new PiePanel(listItems.length);
	            pie2.addSlice(purpleRain, Float.parseFloat(pieitems[0]));
	            pie2.addSlice(purpleRain, Float.parseFloat(pieitems[1]));
	            pie2.addSlice(inBetweenGreen, Float.parseFloat(pieitems[2]));
	            pie2.addSlice(inBetweenGreen, Float.parseFloat(pieitems[3]));
	            final JFrame frame = new JFrame("Purple = interest, Green = Principal");   // added title as pie label
	            frame.getContentPane().add(pie2);
	            frame.pack();
	            frame.setSize(500,500);
	            frame.setVisible(true);
				
			}
			if (source == option3)
			{
				PiePanel pie2 = new PiePanel(listItems.length);
	            pie2.addSlice(purpleRain, Float.parseFloat(pieitems[0]));
	            pie2.addSlice(purpleRain, Float.parseFloat(pieitems[1]));
	            pie2.addSlice(purpleRain, Float.parseFloat(pieitems[2]));
	            pie2.addSlice(inBetweenGreen, Float.parseFloat(pieitems[3]));
	            final JFrame frame = new JFrame("Purple = interest, Green = Principal");   // added title as pie label
	            frame.getContentPane().add(pie2);
	            frame.pack();
	            frame.setSize(500,500);
	            frame.setVisible(true);
			}

		}
		else
		{
			// no matter what the user has clicked, the ammortization table is dirty... So clear it:		
			amortization_out.setText("");
			tf_payment.setText("");
			
		}
		if (source == exit_button) 
		{
			System.exit(0);
		}
		if (source == clear_button)
		{
			 tf_terms.setText("");                          // clears the loan amount field
		 	 tf_interest.setText("");                       // clears the term field
		 	 tf_principal.setText("");                      // clears the payment field
		 	 amortization_out.setText("");                  // clears amortization output
		 	 tf_payment.setText("");
		}
		if (source == calc_button)
		{
			// YIPEE, call our MortgageCalc class.. but for now... lets do some error checking.
			try
			{
				double principle = Double.parseDouble(tf_principal.getText().trim()); // this throws a NumberFormatException if the text is not a number
				double rate = Double.parseDouble(tf_interest.getText().trim())/100;
				int terms = Integer.parseInt(tf_terms.getText().trim());
				MortgageCalculator cal = new MortgageCalculator(principle,rate,terms);
				tf_payment.setText("$"+fmt.format(cal.getMonthlypayment()));
				amortization_out.setText(cal.getAmortizationTableAsString());
				// set the text area back to the top..
				amortization_out.setCaretPosition(0);
				
			}
			catch (NumberFormatException nfe)
			{
				// Tell the user about the error... 
				JOptionPane.showMessageDialog(null, "Please make sure all your entries are numeric!", "USER INPUT ERROR", JOptionPane.ERROR_MESSAGE);
			}
		}
		if(source == option1)
		{
			String [] selection = listItems[0].split("% for "); // should leave us with the rate and the years
			tf_terms.setText(selection[1].substring(0,2));
			tf_interest.setText(selection[0]);			
		}
		if(source == option2)
		{
			String [] selection = listItems[1].split("% for "); // should leave us with the rate and the years
			tf_terms.setText(selection[1].substring(0,2));
			tf_interest.setText(selection[0]);			
		}
		if(source == option3)
		{
			String [] selection = listItems[2].split("% for "); // should leave us with the rate and the years
			tf_terms.setText(selection[1].substring(0,2));
			tf_interest.setText(selection[0]);						
		}
		if(source == plan_a)
		{
			// ok so we want to do this manually...
			option1.setEnabled(false);
			option1.setSelected(false);
			option2.setEnabled(false);
			option2.setSelected(false);
			option3.setEnabled(false);
			option3.setSelected(false);
			tf_terms.setText("");
			tf_terms.setEditable(true);
			tf_interest.setText("");
			tf_interest.setEditable(true);
		}
		if(source == plan_b)
		{
			// ok so we want to do this with presets...
			option1.setEnabled(true);
			option2.setEnabled(true);
			option3.setEnabled(true);
			//select 1 again
			option1.setSelected(true);
			String [] selection = listItems[0].split("% for "); // should leave us with the rate and the years
			tf_terms.setText(selection[1].substring(0,2));
			tf_interest.setText(selection[0]);			
			tf_terms.setEditable(false);
			tf_interest.setEditable(false);
		}
	}
	
	/**
	 * Inner class to limit the size of a text field.
	 * Could be in a seperate file, but since we are only using it for this class, it should be here.
	 * 
	 * NOTE: This is not the same as defining 2 classes in the same file. This class is part of the top class
	 * That is why it is consided an inner class. Other than this type of thing, you have no reason to have
	 * an inner class in your work.
	 * 
	 * Also, if you want to limit the input of a text field in your code, feel free to copy this as is and use it.
	 */
	public class JTextFieldLimit extends PlainDocument
	{
		private static final long serialVersionUID = -349808007443039827L;
		private int limit;
		// optional uppercase conversion
		private boolean toUppercase = false;

		JTextFieldLimit(int limit)
		{
			super();
			this.limit = limit;
		}
		/**
		 * Sets the limit, and if you pass in true here.. will force the 
		 * input to upper case before displaying it.
		 * @param limit
		 * @param upper
		 */
		JTextFieldLimit(int limit, boolean upper)
		{
			super();
			this.limit = limit;
			toUppercase = upper;
		}
		/**
		 * This is a callback method used by Java when text is entered into a text field. This is the
		 * place we can check the length before we actually place the character in the GUI. 
		 */
		public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException
		{
			if (str == null) 
				return;

			if ((getLength() + str.length()) <= limit)
			{
				if (toUppercase)
					str = str.toUpperCase();
				super.insertString(offset, str, attr);
			}
		}
	}

 

	/**
	 * MAIN... the entry point to this program
	 * @param args
	 */
	public static void main(String[] args)
	{
		LayoutExample1 example = new LayoutExample1();
		example.setVisible(true);
	}

}

most of it is my instructors code used with his permission I just have to modify the code to display a chart reflecting the different options

Thank you for using code tags but next time can you try to post just the relevant portion of the code? If we need more we will ask for it.

Edited 7 Years Ago by jasimp: n/a

This article has been dead for over six months. Start a new discussion instead.