Solved

How do I create a horizontal button group

Posted on 2006-06-16
3
252 Views
Last Modified: 2009-06-07
I have my mortgage calculator code below. I am already using a vertical radiogroup to allow the user to select a pre-defined loan. I want to use another radiogroup I have to allow the user to select the method of calculation they want to use. I have added it already as the choiceGroup. I would like t o display them horizontally rather than vertically. As a second question, I was also wondering if there is a way to customize the space between them.
How can I do this?
Any assistance would be appreciated.
Thanks,
Jon

 //week3 Jan Schab


/* Mortgage Monyhly Payment Calculator with graphical user interface
Programmer:  J.Schab
Date:        June 10,2006
Filename:    Mortgage.java
Purpose:     This project accepts the mortgage amountand allows  the user to select one of 3
pre-determined loans.The program then calculates the monthly mortgage payment and displays
it in currency format. The program then displays the payment number, the monthly principle
paid, the monthly interest paid, and the current loan balance.There is a quit button to
exit the application, and a clear button to clear user entered fields as well as the amortization table.
in order to calculate a new mortgage. The program will also clear the payment field should
the user press any key while positioned in the input textfield for amount.


 */



import javax.swing.*;
import javax.swing.border.*;
import javax.swing.JScrollPane.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import java.text.NumberFormat;
import java.util.Locale;
import java.text.*;
import java.text.DecimalFormat;



class Mortgage extends JFrame
{


    //Program variables

    double yearlyRate[] =
    {
        // array of interest rates
        5.35, 5.50, 5.75
    };
    int term[] =
    {
        //array of terms
        7, 15, 30
    };
    int termMonths[] =
    {
        //array of terms in months
        84, 180, 360
    };

    int payment = 0; // payment counter
    int i = 0; // used as index
    // initialize variable for monthly interest rate
    double monthlyInterest = 0.00;
    double principle = 0.00;
    // initialize mothly principle paid field
    double monthlyPrinciplePaid = 0.00;
    double interestRateMonthly = 0.00;
    double monthlyPayment;
    int amount = 0;



    private JLabel headerJLabel;

    Border rowborder = new EmptyBorder(3, 10, 3, 10);
    // Format output
    DecimalFormat currency = new DecimalFormat("$0.00");


    // JLabel and JTextField for the mortgage amount
    private JLabel amountJLabel;
    private JTextField amountJTextField;

    // JLabel for monthly mortgage payment
    private JLabel monthpayJLabel;

    // JTextArea for displaying payment
    private JTextArea outputJTextArea;


    // JButton to initiate calculations
    private JButton calculateJButton;

    // JButton to display amortization table
    private JButton displayJButton;

    // JButton to clear entries
    private JButton clearJButton;

    // JButton to quit
    private JButton quitJButton;

    // JLabel and JTextField for interest percentage rate
      private JLabel interestJLabel;
      private JTextField interestJTextField;

       // JLabel and JTextField for mortgage term
      private JLabel termJLabel;
    private JTextField termJTextField;



    // Create radio panel for pre-determined loans
    JPanel radioPanel = new JPanel();
    JRadioButton aButton = new JRadioButton("7 Years at 5.35%", true);
    JRadioButton bButton = new JRadioButton("15 Years at 5.50%", false);
    JRadioButton cButton = new JRadioButton("30 Years at 5.75%", false);

    JTextArea displayArea = new JTextArea(10, 75);
    JScrollPane scroll = new JScrollPane(displayArea);



    // Create radio panel for method choice
    JPanel choicePanel = new JPanel();
    JRadioButton predefButton = new JRadioButton("Pre-defined Loans", true);
    JRadioButton entryButton = new JRadioButton("User Supplied Parameters", false);






    // no-argument constructor
    public Mortgage()



    {
        createUserInterface();
    }

    // create and position the GUI components; register event handlers
    private void createUserInterface()
    {
        // get content pane for attaching GUI components
        Container contentPane = getContentPane();

        setTitle("Mortgage Calculator"); // set title bar text


        // enable specific positioning of GUI components
        contentPane.setLayout(null);

        // set up amountJLabel
        amountJLabel = new JLabel();
        amountJLabel.setBounds(76, 5, 104, 26); // set size and position
        amountJLabel.setText("Mortgage amount:");
        contentPane.add(amountJLabel);

        // set up amountJTextField
        amountJTextField = new JTextField();
        amountJTextField.setBounds(200, 5, 56, 26); // set size and position
        amountJTextField.setHorizontalAlignment(JTextField.RIGHT);
        contentPane.add(amountJTextField);
        amountJTextField.addKeyListener(

        new KeyAdapter() // anonymous inner class
        {
            // event handler for key pressed in amountJTextField
            public void keyPressed(KeyEvent event)
            {
                amountJTextFieldkeyPressed(event);
            }

        } // end anonymous inner class

        ); // end call to addKeyListener


// set up interestJLabel
        interestJLabel = new JLabel("Annual interest rate:");
        interestJLabel.setBounds(226, 170, 115, 26);
        interestJLabel.setText("Annual interest rate:");
        contentPane.add(interestJLabel);

        // set up interestJTextField
        interestJTextField = new JTextField();
        interestJTextField.setBounds(370, 170, 56, 26);
        interestJTextField.setHorizontalAlignment(JTextField.RIGHT);
        contentPane.add(interestJTextField);
        interestJTextField.addKeyListener(

        new KeyAdapter() // anonymous inner class
        {
            // evend handler for key pressed in interestJTextField
            public void keyPressed(KeyEvent event)
            {
                interestJTextFieldkeyPressed(event);
            }

        } // end anonymous inner class


        ); // end call to addKeyListener

        // set up termJLabel for term of loan
        termJLabel = new JLabel();
        termJLabel.setBounds(226, 130, 140, 26);
        termJLabel.setText("Mortgage length (Years):");
        contentPane.add(termJLabel);

        // set up termJTextField to receive term of loan
        termJTextField = new JTextField();
        termJTextField.setBounds(370, 130, 56, 26);
        termJTextField.setHorizontalAlignment(JTextField.RIGHT);
        contentPane.add(termJTextField);
        termJTextField.addKeyListener(

        new KeyAdapter() // anonymous inner class
        {
            // event handler for key pressed in termJTextField
            public void keyPressed(KeyEvent event)
            {
                termJTextFieldkeyPressed(event);
            }

        } // end anonymous inner class

        ); // end call to addKeyListener





        ButtonGroup bgroup = new ButtonGroup();
        bgroup.add(aButton);
        bgroup.add(bButton);
        bgroup.add(cButton);
        radioPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 4, 4));
        radioPanel.add(aButton);
        radioPanel.add(bButton);
        radioPanel.add(cButton);
        contentPane.add(radioPanel);
        radioPanel.setBorder(rowborder);
        radioPanel.setBounds(30, 120, 195, 95); // set size and position



        ButtonGroup choicegroup = new ButtonGroup();
        choicegroup.add(predefButton);
        choicegroup.add(entryButton);
        choicePanel.setLayout(new FlowLayout(FlowLayout.LEFT, 4, 4));
        choicePanel.add(predefButton);
        choicePanel.add(entryButton);
        contentPane.add(choicePanel);
        choicePanel.setBorder(rowborder);
        choicePanel.setBounds(130, 50, 195, 95); // set size and position


        // set up calculateJButton
        calculateJButton = new JButton();
        calculateJButton.setBounds(26, 220, 90, 26); // set size and position
        calculateJButton.setText("Calculate");
        contentPane.add(calculateJButton);
        calculateJButton.addActionListener(

        new ActionListener() // anonymous inner class
        {
            // event handler called when calculateJButton is pressed
            public void actionPerformed(ActionEvent event)
            {

                calculateJButtonActionPerformed(event);
            }

        } // end anonymous inner class

        ); // end call to addActionListener


        // set up displayJButton
        displayJButton = new JButton();
        displayJButton.setBounds(26, 280, 200, 26); // set size and position
        displayJButton.setText("Display Amortization Table");
        contentPane.add(displayJButton);
        displayJButton.addActionListener(

        new ActionListener() // anonymous inner class
        {
            // event handler called when clearJButton is pressed
            public void actionPerformed(ActionEvent event)
            {
                displayJButtonActionPerformed(event);
            }

        } // end anonymous inner class

        ); // end call to addActionListener




        // set up clearJButton
        clearJButton = new JButton();
        clearJButton.setBounds(120, 430, 90, 26); // set size and position
        clearJButton.setText("Clear");
        contentPane.add(clearJButton);
        clearJButton.addActionListener(

        new ActionListener() // anonymous inner class
        {
            // event handler called when clearJButton is pressed
            public void actionPerformed(ActionEvent event)
            {
                clearJButtonActionPerformed(event);
            }

        } // end anonymous inner class

        ); // end call to addActionListener


        // set up quitJButton
        quitJButton = new JButton();
        quitJButton.setBounds(270, 430, 90, 26); // set size and position
        quitJButton.setText("Quit");
        contentPane.add(quitJButton);
        quitJButton.addActionListener(

        new ActionListener() // anonymous inner class
        {
            // event handler called when quitJButton is pressed
            public void actionPerformed(ActionEvent event)
            {
                quitJButtonActionPerformed(event);
            }

        } // end anonymous inner class

        ); // end call to addActionListener


        // set up outputJTextArea
        outputJTextArea = new JTextArea();
        contentPane.add(outputJTextArea);
        outputJTextArea.setBounds(300, 220, 56, 26); // set size and position
        outputJTextArea.setEditable(false);

        //set up monthpayJLabel
        monthpayJLabel = new JLabel();
        monthpayJLabel.setBounds(176, 220, 156, 26); // set size and position
        monthpayJLabel.setText("Monthly Payment:");
        contentPane.add(monthpayJLabel);

        scroll.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        contentPane.add(scroll);
        scroll.setBounds(20, 300, 440, 130); // set size and position
        setVisible(true);





    } // end method createUserInterface

    // called when user presses key in amountJTextField
    private void amountJTextFieldkeyPressed(KeyEvent event)
    {
        outputJTextArea.setText(""); // clear outputJTextArea
        displayArea.setText(""); // clear display
        payment = 0; // reset payment counter
    }

    // method called when user clicks calculateJButton
    private void calculateJButtonActionPerformed(ActionEvent event)
    {
        try
        {
            // check which radio buttonis selected and set index
            if (aButton.isSelected())
            {
                i = 0;
            }


            if (bButton.isSelected())
            {
                i = 1;
            }


            if (cButton.isSelected())
            {
                i = 2;
            }





            //define display area titles
            String titles = "Month \t Principal\t Interest\tBalance\n";
            //put titles in display area
            displayArea.setText(titles);
            // initialize loan balance field
            double loanbalance = 0.00;

            // initialize payment counter

            // clear outputJTextArea
            outputJTextArea.setText("");
            // clear display area
            displayArea.setText("");
            // Calculate months from years
            int monthCount = (term[i] * 12);
            // get mortgage amount
            amount = Integer.parseInt(amountJTextField.getText());
            //create variable to store decreasing principle
            principle = amount;
            // Calculate monthly interest
            interestRateMonthly = (yearlyRate[i] / 12) / 100;


            // Calculate monthly payment
            monthlyPayment = (amount * interestRateMonthly) / (1-Math.pow(1 +
                interestRateMonthly,  - monthCount));




            // Output payment amount
            outputJTextArea.setText(currency.format(monthlyPayment));



        }

        catch (NumberFormatException ex){}
    }





    // method called when user clicks clearJButton
    private void clearJButtonActionPerformed(ActionEvent event)
    {
        try
        {

            monthlyPrinciplePaid = 0.00;
            outputJTextArea.setText(""); // clear outputJTextArea
            amountJTextField.setText(""); // clear amountJTextField
            displayArea.setText(""); // clear display area
            payment = 0; // reset payment counter




        }
        catch (NumberFormatException ex){}
    }


    // method called when user clicks displayJButton
    private void displayJButtonActionPerformed(ActionEvent event)
    {
        try
        {

            // reset values in case user presses display more than once
            principle = Integer.parseInt(amountJTextField.getText());
            monthlyPrinciplePaid = 0.00;
            displayArea.setText(""); // clear display
            payment = 0;
            monthlyPrinciplePaid = 0.00;

            //define display area titles
            String titles = "Month \t Principal\t Interest\tBalance\n";
            //put titles in display area
            displayArea.setText(titles);
            // initialize loan balance field


            // loop for creating amortization table
            for (int a = 0; a < termMonths[i]; a = a + 1)
            {
                //increment payment counter
                payment++;
                // calculate monthly interest
                monthlyInterest = principle * interestRateMonthly;
                // calculate monthly principle
                monthlyPrinciplePaid = monthlyPayment - monthlyInterest; //
                //save declining balance
                principle = principle - monthlyPrinciplePaid;


                // display amortization table
                displayArea.append(payment + "\t" + currency.format
                    (monthlyPrinciplePaid) + "\t" + currency.format
                    (monthlyInterest) + "\t" + currency.format(Math.abs
                    (principle)) + "\n");
                displayArea.setCaretPosition(0);


            }
        }

        catch (NumberFormatException ex){}
    }




    // method called when user clicks quitJButton
    private void quitJButtonActionPerformed(ActionEvent event)
    {
        try
        {
            System.exit(0);

        }
        catch (NumberFormatException ex){}
    }


    // called when user presses key in termJTextField
    private void termJTextFieldkeyPressed(KeyEvent event)
    {
        outputJTextArea.setText(""); // clear outputJTextArea
    }

    // called when user presses key in interestJTextField
    private void interestJTextFieldkeyPressed(KeyEvent event)
    {
        outputJTextArea.setText(""); // clear outputJTextArea
    }


    // main method
    public static void main(String[]args)
    {
        Mortgage application = new Mortgage();
        application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        application.setSize(480, 500);
        application.setVisible(true);
    } // end method main

} // end class Mortgage
0
Comment
Question by:ghost8067
  • 2
3 Comments
 
LVL 9

Expert Comment

by:matthew016
ID: 16924436
It's predefButton and entryButton that u want to align horizontally ?
If yes replace setBounds with this one for example choicePanel.setBounds(29, 50, 340, 95);
0
 
LVL 9

Accepted Solution

by:
matthew016 earned 500 total points
ID: 16924469
To have a space between them :

        choicePanel.setLayout(new FlowLayout(FlowLayout.LEFT, 4, 4));
        choicePanel.add(predefButton);
        choicePanel.add(Box.createRigidArea(new Dimension(50,0)));
        choicePanel.add(entryButton);

(U need a larger width bound according to the space between the components u add)
choicePanel.setBounds(29, 50, 500, 95);
0
 

Author Comment

by:ghost8067
ID: 16924737
Thanks a lot for the help. Everything now looks great.
Jon
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now