Results 1 to 17 of 17
Like Tree1Likes
  • 1 Post By camickr

Thread: Change value of combobox value

  1. #1
    swilliams236 is offline Member
    Join Date
    Nov 2011
    Posts
    13
    Rep Power
    0

    Default Change value of combobox value

    I am extremely new to programming and am having a really hard time with what I believe to be a very basic function.

    I have a combobox with defined values, however, I want the respective selection to pass through different values to specified variables. How do I do this?

    Here is the code for my combobox

    Java Code:
    jComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "7 Years at 5.35%", "15 Years at 5.5%", "30 Years at 5.75%" }));
    	jComboBox.addActionListener(new java.awt.event.ActionListener() {
    	    public void actionPerformed(java.awt.event.ActionEvent evt) {
    	        jComboBoxActionPerformed(evt);
    Basically what I want to do is take the value "7 Years at 5.35%" and pass through a value of 7 to a variable "term" and take the value "5.35%" and set a variable "APR" to 5.35. Also, the values for both variables need to be double.

    I can't find anywhere how to do this function, I'm sure it can be done, but I am way to new to understand how or where to even look.

    Your help is very much appreciated.

  2. #2
    SRaith is offline Member
    Join Date
    Oct 2011
    Posts
    14
    Rep Power
    0

    Default Re: Change value of combobox value

    Here's a fast solution, it will work, if you will keep the format of the text.

    I commented my quellcode, if you still have any question, just ask :).

    Window.java
    Java Code:
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.*;
    
    public class Window implements ActionListener
    {
    	String[] jComboBoxContent;	// Content of the ComboBox
    	String[] splittedContent;	// Splitted content of the selected item
    	double term, apr;	// Your variables
    
    	JFrame jFrame;
    	JComboBox<String> jComboBox; // The ComboBox with Content
    	JLabel jTerm;	// To show the content of the Variable term
    	JLabel jApr; // To show the content of the Variable apr
    	JButton jButton; // Click to get the Information of the ComboBox
    	
    	public Window()
    	{
    		this.jComboBoxContent = new String[]{"7 Years at 5.35%", "15 Years at 5.5%", "30 Years at 5.75%"};
    		
    		this.jTerm = new JLabel("");	// To show the content of the Variable term
    		this.jApr = new JLabel(""); // To show the content of the Variable apr
    		
    		this.jButton = new JButton("Get Information"); // Click to get the Information of the ComboBox
    		
    		this.jFrame = new JFrame();
    		this.jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    		this.jFrame.setSize(300, 300);	// Size of Frame
    		this.jFrame.setLayout(null);	// No Layout
    		
    		this.jComboBox = new JComboBox<String>(jComboBoxContent); // The ComboBox with Content
    		this.jComboBox.setBounds(60, 120, 150, 25);	// Position and Size of ComboBox
    		
    		this.jTerm.setBounds(20, 200, 100, 25);	// Position and Size of the Label
    		this.jApr.setBounds(230, 200, 100, 25); // Position and Size of the Label
    		
    		this.jButton.setBounds(60, 165, 200, 25); // Position and Size of the Button
    		
    		this.jButton.addActionListener(this);
    		
    		this.jFrame.add(jButton);
    		this.jFrame.add(jTerm);
    		this.jFrame.add(jApr);
    		this.jFrame.add(jComboBox);
    		this.jFrame.setVisible(true);
    	}
    
    	@Override
    	public void actionPerformed(ActionEvent e)
    	{
    		// Button clicked?
    		if(e.getActionCommand().equals("Get Information"))
    		{
    			// Split the selected Item
    			splittedContent = jComboBox.getSelectedItem().toString().split(" ");
    			
    			// Array index 0 = term
    			// Array index 3 = arp (substring cause of the %)
    			
    			// Has to be parsed, because the information are Strings
    			this.term = Double.parseDouble(splittedContent[0]);
    			this.apr = Double.parseDouble(splittedContent[3].substring(0, splittedContent[3].length() - 1));
    			
    			// Just set the Label to see the results ;)
    			this.jApr.setText(Double.toString(this.apr));
    			this.jTerm.setText(Double.toString(this.term));
    		}
    	}
    }
    Test.java
    Java Code:
    public class Test
    {
    	public static void main(String[] args)
    	{
    		Window w = new Window();
    	}
    }
    Short explanation: I just splitted the selected item at space, so i have the single Strings in an array. So the term is at index 0 and arp at 3.
    Thats the reason, why this solution just works with the current format of the ComboBox text.
    Anyway, i dont think it's a good solution, but for the moment its okay :P.

  3. #3
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,798
    Rep Power
    7

    Default Re: Change value of combobox value

    1. Get the selected index and use an if statement to set the variables to hard coded values.

    2. Get the selected index and use it to access corresponding elements of an array.

    3. Get selected item and parse out the values. You can use a regular expression or more simpler use indexOf and substring.

  4. #4
    camickr is offline Senior Member
    Join Date
    Jul 2009
    Posts
    1,236
    Rep Power
    7

    Default Re: Change value of combobox value

    Anyway, i dont think it's a good solution
    Agreed, its not a good solution :)

    A better solution is to store a custom object in the ComboBoxModel. This object will contain two properties, the duration and rate. Then you can create a custom toString() method to display the data in the format your want.

    Here is a simple example to get you started:
    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.plaf.basic.*;
    
    public class ComboBoxItem extends JFrame implements ActionListener
    {
    	public ComboBoxItem()
    	{
    		Vector model = new Vector();
    		model.addElement( new Item(1, "car" ) );
    		model.addElement( new Item(2, "plane" ) );
    		model.addElement( new Item(4, "boat" ) );
    		model.addElement( new Item(3, "train" ) );
    		model.addElement( new Item(5, "boat" ) );
    
    		JComboBox comboBox;
    
    		//  Easiest approach is to just override toString() method
    		//  of the Item class
    
    		comboBox = new JComboBox( model );
    		comboBox.setEditable(true);
    //		comboBox.setSelectedIndex(-1);
    
    		comboBox.addActionListener( this );
    		getContentPane().add(comboBox, BorderLayout.NORTH );
    
    		//  Most flexible approach is to create a custom render
    		//  to diplay the Item data
    		//  Note this approach will break keyboard navigation if you don't
    		//  implement a default toString() method.
    
    		comboBox = new JComboBox( model );
    //		comboBox.setSelectedIndex(-1);
    		comboBox.setRenderer( new ItemRenderer() );
    		comboBox.addActionListener( this );
    		getContentPane().add(comboBox, BorderLayout.SOUTH );
    	}
    
    	public void actionPerformed(ActionEvent e)
    	{
    		JComboBox comboBox = (JComboBox)e.getSource();
    		Item item = (Item)comboBox.getSelectedItem();
    		System.out.println( item.getId() + " : " + item.getDescription() );
    	}
    
    	class ItemRenderer extends BasicComboBoxRenderer
    	{
    		public Component getListCellRendererComponent(
    			JList list, Object value, int index,
    			boolean isSelected, boolean cellHasFocus)
    		{
    			super.getListCellRendererComponent(list, value, index,
    				isSelected, cellHasFocus);
    
    			if (value != null)
    			{
    				Item item = (Item)value;
    				setText( item.getDescription().toUpperCase() );
    			}
    
    			return this;
    		}
    	}
    
    	class Item
    	{
    		private int id;
    		private String description;
    
    		public Item(int id, String description)
    		{
    			this.id = id;
    			this.description = description;
    		}
    
    		public int getId()
    		{
    			return id;
    		}
    
    		public String getDescription()
    		{
    			return description;
    		}
    
    		public String toString()
    		{
    			return description;
    		}
    	}
    
    	public static void main(String[] args)
    	{
    		JFrame frame = new ComboBoxItem();
    		frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
    		frame.pack();
    		frame.setVisible( true );
    	 }
    }
    You would change the "id" and "description" properties to be your "duration" and "rate" properties. Then implement the custom toString() method.
    Last edited by camickr; 11-07-2011 at 03:49 AM.
    DarrylBurke likes this.

  5. #5
    swilliams236 is offline Member
    Join Date
    Nov 2011
    Posts
    13
    Rep Power
    0

    Default Re: Change value of combobox value

    Quote Originally Posted by Junky View Post
    1. Get the selected index and use an if statement to set the variables to hard coded values.

    2. Get the selected index and use it to access corresponding elements of an array.

    3. Get selected item and parse out the values. You can use a regular expression or more simpler use indexOf and substring.
    I think I got the split correct, but now I am getting an error that states "cannot find symbol"

    Java Code:
    import java.text.*;
    public class MultiOptionCalc extends javax.swing.JFrame {
    
        /** Creates new form MultiOptionCalc */
        public MultiOptionCalc() {
            initComponents();
        }
    
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
         */
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
    
            jPanel1 = new javax.swing.JPanel();
            jLabel1 = new javax.swing.JLabel();
            jTextField1 = new javax.swing.JTextField();
            jLabel2 = new javax.swing.JLabel();
            jComboBox = new javax.swing.JComboBox();
            jButton1 = new javax.swing.JButton();
            jTextField2 = new javax.swing.JTextField();
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    
            jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Mortgage Calculator", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 12), new java.awt.Color(0, 0, 255))); // NOI18N
    
            jLabel1.setText("Loan Amount:");
    
            jTextField1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jTextField1ActionPerformed(evt);
                }
            });
    
            jLabel2.setText("Terms of Loan:");
    
            jComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "7 Years at 5.35%", "15 Years at 5.5%", "30 Years at 5.75%" }));
            jComboBox.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jComboBoxActionPerformed(evt);
                }
            });
    
            jButton1.setText("Calculate");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
                }
            });
    
            jTextField2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jTextField2ActionPerformed(evt);
                }
            });
    
            javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
            jPanel1.setLayout(jPanel1Layout);
            jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addComponent(jLabel1)
                            .addGap(10, 10, 10)
                            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addComponent(jLabel2)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(jComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addGap(55, 55, 55)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(jTextField2, javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jButton1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                    .addContainerGap())
            );
            jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel2)
                        .addComponent(jComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(39, 39, 39)
                    .addComponent(jButton1)
                    .addGap(18, 18, 18)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(26, Short.MAX_VALUE))
            );
    
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            );
    
            pack();
        }// </editor-fold>
    
    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    }
    
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
            // Float Variables
            double balance, monthlyPayment, rateToUse;
            int yearToUse;
            //Set declarations
            double monthlyPrincipal = 0;
            double monthlyInterest = 0;
            yearToUse = years(jComboBox.getSelectedIndex());
            rateToUse = rate(jComboBox.getSelectedIndex());
            NumberFormat nf = NumberFormat.getCurrencyInstance();
            // Parse text
            balance = Double.parseDouble(jTextField1.getText());
            double monthlyRate = ((rateToUse/100)/12);
            //Calculate payment
            monthlyPayment = balance*(monthlyRate/(1-Math.pow((1+monthlyRate),-1*
                        (yearToUse*12))));
            
            //Loop for amorization
            for(int counter=1; counter<=yearToUse*12; counter++);{
            monthlyInterest = (balance*monthlyRate);
            balance = (balance - monthlyPrincipal);
            monthlyPrincipal = (monthlyPayment - monthlyInterest);
            jTextField2.setText(nf.format(monthlyPayment));
            }
    }
    
    private void jComboBoxActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
            int[] years = {7, 15, 30};
            double[] rate = {5.35, 5.5, 5.75};
        for(int i=0; i<years.length; ++i)
            jComboBox.addItem(years[i] +  " years at " + rate[i] + "%");
    }
    
    private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    }
    
        /**
         * @param args the command line arguments
         */
        public static void main(String args[]) {
            /* Set the Nimbus look and feel */
            //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
            /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
             * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
             */
            try {
                for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        javax.swing.UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
            } catch (ClassNotFoundException ex) {
                java.util.logging.Logger.getLogger(MultiOptionCalc.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(MultiOptionCalc.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(MultiOptionCalc.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(MultiOptionCalc.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
            //</editor-fold>
    
            /* Create and display the form */
            java.awt.EventQueue.invokeLater(new Runnable() {
    
                public void run() {
                    new MultiOptionCalc().setVisible(true);
                }
            });
        }
        // Variables declaration - do not modify
        private javax.swing.JButton jButton1;
        private javax.swing.JComboBox jComboBox;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JPanel jPanel1;
        private javax.swing.JTextField jTextField1;
        private javax.swing.JTextField jTextField2;
        // End of variables declaration
    }
    Its happening to me on these two lines...

    Java Code:
            yearToUse = years(jComboBox.getSelectedIndex());
            rateToUse = rate(jComboBox.getSelectedIndex());

  6. #6
    swilliams236 is offline Member
    Join Date
    Nov 2011
    Posts
    13
    Rep Power
    0

    Default Re: Change value of combobox value

    Thanks for everyones help!

    I found the issue. I was using a ( instead of a [, and I had the declarations for the array in the wrong location.

  7. #7
    swilliams236 is offline Member
    Join Date
    Nov 2011
    Posts
    13
    Rep Power
    0

    Default Re: Change value of combobox value

    I got the values extracted. But now everytime I hit the action button, it duplicates the set of terms defined in the combobox.

    Any idea what I did wrong?

    Java Code:
    import java.awt.*;
    import javax.swing.*;
    import java.text.*;
    public class MultiOptionCalc extends javax.swing.JFrame {
    
        /** Creates new form MultiOptionCalc */
        public MultiOptionCalc() {
            initComponents();
        }
    
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
         */
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
    
            jPanel1 = new javax.swing.JPanel();
            jLabel1 = new javax.swing.JLabel();
            jTextField1 = new javax.swing.JTextField();
            jLabel2 = new javax.swing.JLabel();
            jComboBox = new javax.swing.JComboBox();
            jButton1 = new javax.swing.JButton();
            jTextField2 = new javax.swing.JTextField();
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    
            jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Mortgage Calculator", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 12), new java.awt.Color(0, 0, 255))); // NOI18N
    
            jLabel1.setText("Loan Amount:");
    
            jTextField1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jTextField1ActionPerformed(evt);
                }
            });
    
            jLabel2.setText("Terms of Loan:");
    
            jComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "7 Years at 5.35%", "15 Years at 5.5%", "30 Years at 5.75%" }));
            jComboBox.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jComboBoxActionPerformed(evt);
                }
            });
    
            jButton1.setText("Calculate");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
                }
            });
    
            jTextField2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jTextField2ActionPerformed(evt);
                }
            });
    
            javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
            jPanel1.setLayout(jPanel1Layout);
            jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addComponent(jLabel1)
                            .addGap(10, 10, 10)
                            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addComponent(jLabel2)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(jComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addGap(55, 55, 55)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(jTextField2, javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jButton1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                    .addContainerGap())
            );
            jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel2)
                        .addComponent(jComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(39, 39, 39)
                    .addComponent(jButton1)
                    .addGap(18, 18, 18)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(26, Short.MAX_VALUE))
            );
    
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            );
    
            pack();
        }// </editor-fold>
    
    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    }
    
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
            // Float Variables
            double balance, monthlyPayment, rateToUse;
            int yearToUse;
            
            //Set declarations
            double monthlyPrincipal = 0;
            double monthlyInterest = 0;
            int[] years = {7, 15, 30};
            double[] rate = {5.35, 5.5, 5.75};
            
            //Array for loan terms
            for(int i=0; i<years.length; ++i)
                jComboBox.addItem(years[i] +  " years at " + rate[i] + "%");
            yearToUse = years[jComboBox.getSelectedIndex()];
            rateToUse = rate[jComboBox.getSelectedIndex()];
            //Set Curreny Number Format
            NumberFormat nf = NumberFormat.getCurrencyInstance();
            
            // Parse text
            balance = Double.parseDouble(jTextField1.getText());
            double monthlyRate = ((rateToUse/100)/12);
            
            //Calculate payment
            monthlyPayment = balance*(monthlyRate/(1-Math.pow((1+monthlyRate),-1*
                        (yearToUse*12))));
            jTextField2.setText(nf.format(monthlyPayment));
            
            //Loop for amorization
            int counter;
            for(counter=1; counter<=yearToUse*12; counter++){
            monthlyInterest = (balance*monthlyRate);
            //Final Payment
            if(counter == yearToUse*12){
                monthlyPayment = balance+monthlyInterest;}
            monthlyPrincipal = (monthlyPayment - monthlyInterest);
            balance = (balance - monthlyPrincipal);        
            System.out.println("Payment #: " + counter + " Interest: " + 
                (nf.format(monthlyInterest)) + " Principal: " + (nf.format(monthlyPrincipal)) + " Balance: " + 
                (nf.format(balance)));
            }
    }
    
    private void jComboBoxActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    }
    
    private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    }
    
        /**
         * @param args the command line arguments
         */
        public static void main(String args[]) {
            /* Set the Nimbus look and feel */
            //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
            /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
             * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
             */
            try {
                for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        javax.swing.UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
            } catch (ClassNotFoundException ex) {
                java.util.logging.Logger.getLogger(MultiOptionCalc.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(MultiOptionCalc.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(MultiOptionCalc.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(MultiOptionCalc.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
            //</editor-fold>
    
            /* Create and display the form */
            java.awt.EventQueue.invokeLater(new Runnable() {
    
                public void run() {
                    new MultiOptionCalc().setVisible(true);
                }
            });
        }
        // Variables declaration - do not modify
        private javax.swing.JButton jButton1;
        private javax.swing.JComboBox jComboBox;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JPanel jPanel1;
        private javax.swing.JTextField jTextField1;
        private javax.swing.JTextField jTextField2;
        // End of variables declaration
    }

  8. #8
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,798
    Rep Power
    7

    Default Re: Change value of combobox value

    Posting a butt-load of code and not providing much information is not going to get you much help. Try and debug the problem yourself. If you are using an IDE you can add breakpoints. Or add print statements/popup messages at very locations to output the value of variables to see if they actually hold the value you think they should.

  9. #9
    swilliams236 is offline Member
    Join Date
    Nov 2011
    Posts
    13
    Rep Power
    0

    Default Re: Change value of combobox value

    I did try and debug the code.

    I don't post until I don't have any idea where to look. I worked on this issue for at least 2 hours before I moved onto other issues and then came back to it for another hour.

    I just don't understand why it keeps duplicating the combobox values. I'm assuming it is from the for statement, but without it I don't know anyway to extract the data from the combobox I need.

    I'm not asking anyone to do this for me, I'm asking for direction. On this simple program I have spent more than 15 hours.

  10. #10
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: Change value of combobox value

    Not sure about others, but you've posted way too much code for me to go through, and most of it unrelated to your problem. Why not simplify the problem to its bare minimum. That way you can understand what you're doing and what you may be doing wrong, and if not, you can post a reasonable amount of code to ask a volunteer to spend his free time going through and trying to understand.

  11. #11
    swilliams236 is offline Member
    Join Date
    Nov 2011
    Posts
    13
    Rep Power
    0

    Default Re: Change value of combobox value

    Quote Originally Posted by Fubarable View Post
    Not sure about others, but you've posted way too much code for me to go through, and most of it unrelated to your problem. Why not simplify the problem to its bare minimum. That way you can understand what you're doing and what you may be doing wrong, and if not, you can post a reasonable amount of code to ask a volunteer to spend his free time going through and trying to understand.
    I agree, I just didn't know how much code was needed to get good info...

    Java Code:
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
            // Float Variables
            double balance, monthlyPayment, rateToUse;
            int yearToUse;
            
            //Set declarations
            double monthlyPrincipal = 0;
            double monthlyInterest = 0;
            int[] years = {7, 15, 30};
            double[] rate = {5.35, 5.5, 5.75};
            
            //Array for loan terms
            for(int i=0; i<years.length; ++i)
                jComboBox.addItem(years[i] +  " years at " + rate[i] + "%");
            yearToUse = years[jComboBox.getSelectedIndex()];
            rateToUse = rate[jComboBox.getSelectedIndex()];
            //Set Curreny Number Format
            NumberFormat nf = NumberFormat.getCurrencyInstance();
            
            // Parse text
            balance = Double.parseDouble(jTextField1.getText());
            double monthlyRate = ((rateToUse/100)/12);
            
            //Calculate payment
            monthlyPayment = balance*(monthlyRate/(1-Math.pow((1+monthlyRate),-1*
                        (yearToUse*12))));
            jTextField2.setText(nf.format(monthlyPayment));
    I'm pretty certain it's in my "Array for loan Terms" for statement at line 12. I just can't figure out if it is the value I gave the counter, or if I placed it in the wrong place. I placed it under my button actionPerformed and I suspect this is the problem, but I couldn't find any other way to extract the data from the combo button that would work. I had to place it here to get it to work, I may have just done something wrong, but this is all I could gather.

    I really appreciate everyones help on this matter and hope I can get this ironed out.

  12. #12
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: Change value of combobox value

    Why are you adding items to the combo box in the button's action performed method? Aren't the items already in the combobox? If so what need is there to add them in again?
    Last edited by Fubarable; 11-08-2011 at 02:53 AM.

  13. #13
    swilliams236 is offline Member
    Join Date
    Nov 2011
    Posts
    13
    Rep Power
    0

    Default Re: Change value of combobox value

    Thats where I'm lost at. I'm pretty sure they should be in the combobox, but I'm not quite sure how to put them in there properly. Right now I just have a generic code in combobox

    Java Code:
            jComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "7 Years at 5.35%", "15 Years at 5.5%", "30 Years at 5.75%" }));
            jComboBox.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jComboBoxActionPerformed(evt);
                }
            });
    I just can't figure out how to get the coding right. I would think the for statement would replace the new string statement, but its not working.

  14. #14
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: Change value of combobox value

    There are two concepts that need to be straightening out: 1) putting stuff into the combobox and 2) checking what's selected. You would do #1 at program start up, perhaps in the init method, but for your program, that's it. Once those things are in the combobox, leave it alone and don't try to add any more items into it. For number 2) checking what's selected, just use the getSelectedIndex or getSelectedItem methods, but don't try to add any more items when doing this check as it's not only unnecessary, it will mess things up.

  15. #15
    camickr is offline Senior Member
    Join Date
    Jul 2009
    Posts
    1,236
    Rep Power
    7

    Default Re: Change value of combobox value

    I'm asking for direction.
    I gave you direction along with working code that demonstrated the suggestion. You completely ignored it.

    Your solution has duplicate data, unnecessary parsing of this data and does not follow OO principles. Good luck.

  16. #16
    DarrylBurke's Avatar
    DarrylBurke is online now Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,257
    Rep Power
    19

    Default Re: Change value of combobox value

    Also, stop ignoring camickr's response at #4. Java is an object oriented language; it just doesn't make sense to try parsing a String where a custom class with an appropriate toString() override would provide you the data you need.

    Don't misuse Strings as data objects.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  17. #17
    swilliams236 is offline Member
    Join Date
    Nov 2011
    Posts
    13
    Rep Power
    0

    Default Re: Change value of combobox value

    I wasn't ignoring camikr's post, there was just so much there it overwhelmed me and I didn't know what I was looking at. I 'm not only new to Java, I'm new to programming in general and that was too much for me. The direction that Junky gave me made since to me so I went with it.

    I ended up resolving the duplicating problem by taking Fuburable's advice in his last post. The for statement that I used was completly unecessary and when I removed it everything worked perfect.

    I appreciate everyones help and didn't mean any disrespect to anyone. Now that I have struggled with it and learned a lot about what I was doing I can go over camickr's code and understand what it is saying, before now it didn't make since to me.

Similar Threads

  1. combobox
    By dina in forum AWT / Swing
    Replies: 7
    Last Post: 05-11-2011, 05:31 PM
  2. combobox
    By leader in forum New To Java
    Replies: 2
    Last Post: 02-12-2011, 09:30 PM
  3. add combobox for jtable row
    By anilkumar_vist in forum Advanced Java
    Replies: 1
    Last Post: 11-18-2009, 11:19 AM
  4. Need Help combobox
    By kwink in forum AWT / Swing
    Replies: 3
    Last Post: 03-21-2009, 10:05 AM
  5. combobox
    By chandu.v in forum New To Java
    Replies: 2
    Last Post: 07-02-2008, 08:36 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •