Solved

How do I create a horizontal button group

Posted on 2006-06-16
3
295 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

691 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