Results 1 to 16 of 16
- 08-05-2011, 06:50 AM #1
Member
- Join Date
- Aug 2011
- Posts
- 8
- Rep Power
- 0
adding elements to a multidimentional Object array for a Jtable
I am creating an JTable to display monthly payments for a mortgage. I have been able to get all the calculations to work and to display everything n a GUI but unless I set the Object array = to data upfront it will not display. I need to find a way to fill the array form the equation loop then display it in my Jtable. Here is an example of my code so far.
//calculate monthly payment
int t =0;
double p = Double.parseDouble(loan.getText()); //used to get the principle entered by the user in the text box
double r = Double.parseDouble(interestRate.getText())/12; //used to get the interest rate set in the text box by the radio buttons.
//if else statmenst to check the status of the active radio button and set the term for the loan
if(low.isSelected()){
t = 7*12;
}
else if(medium.isSelected()) {
t = 15*12;
}
else if(high.isSelected()) {
t = 30*12;
}
double monthlyPayment = p*Math.pow(1+r, t)*r/(Math.pow(1+r,t)-1); //Math equation to get monthly payment
DecimalFormat df = new DecimalFormat("###,###.00"); //use to format the output
payment.setText(df.format(monthlyPayment));
// Calculat the loan schedule
double principal = p;
int month;
data = new Object[t][4];
//StringBuilder buffer = new StringBuilder();
//buffer.append("Month \t Amount \t Interest \t\t Balance\n");
for (int i=0; i<t; i++) {
month=i+1;
double interest = principal*r;
double balance = principal + interest - monthlyPayment;
data[i][0]=month;
data[i][1]=principal;
data[i][2]=interest;
data[i][3]=balance;
principal = balance;
this is just the section for calculations and entering info into the array. I get nothing but errors can anyone help.
- 08-05-2011, 06:57 AM #2
- 08-05-2011, 07:50 AM #3
Scrap all your code (not really, keep a copy around somewhere) and start again.I get nothing but errors can anyone help.
Add a little code at a time and compile/run frequently. Eliminate any errors before you move on. That way, each time you get an error you know where to look: in the last little bit of code you added.
db
- 08-05-2011, 12:28 PM #4
Member
- Join Date
- Aug 2011
- Posts
- 8
- Rep Power
- 0
Exception in thread "main" java.lang.NullPointerException
at javax.swing.JTable$1.getRowCount(JTable.java:666)
at javax.swing.JTable.getRowCount(JTable.java:2631)
at javax.swing.plaf.basic.BasicTableUI.createTableSiz e(BasicTableUI.java:1646)
at javax.swing.plaf.basic.BasicTableUI.getPreferredSi ze(BasicTableUI.java:1687)
at javax.swing.JComponent.getPreferredSize(JComponent .java:1634)
at javax.swing.JViewport.getViewSize(JViewport.java:1 018)
at javax.swing.ScrollPaneLayout.preferredLayoutSize(S crollPaneLayout.java:476)
at java.awt.Container.preferredSize(Container.java:15 99)
at java.awt.Container.getPreferredSize(Container.java :1584)
at javax.swing.JComponent.getPreferredSize(JComponent .java:1636)
at java.awt.GridBagLayout.GetLayoutInfo(GridBagLayout .java:1092)
at java.awt.GridBagLayout.getLayoutInfo(GridBagLayout .java:893)
at java.awt.GridBagLayout.ArrangeGrid(GridBagLayout.j ava:2048)
at java.awt.GridBagLayout.arrangeGrid(GridBagLayout.j ava:2008)
at java.awt.GridBagLayout.layoutContainer(GridBagLayo ut.java:789)
at java.awt.Container.layout(Container.java:1421)
at java.awt.Container.doLayout(Container.java:1410)
at java.awt.Container.validateTree(Container.java:150 7)
at java.awt.Container.validateTree(Container.java:151 3)
at java.awt.Container.validateTree(Container.java:151 3)
at java.awt.Container.validateTree(Container.java:151 3)
at java.awt.Container.validate(Container.java:1480)
at java.awt.Window.show(Window.java:861)
at java.awt.Component.show(Component.java:1584)
at java.awt.Component.setVisible(Component.java:1536)
at java.awt.Window.setVisible(Window.java:842)
at mortgagecalculator2.MortgageCalculator2.main(Mortg ageCalculator2.java:277)
- 08-05-2011, 12:35 PM #5
Member
- Join Date
- Aug 2011
- Posts
- 8
- Rep Power
- 0
I did build this a little at a time and as mentioned it all worked until I needed to add an Object Array. If I add and Object array and set it equal to mock data it works find it only when I wait and try to fill it with my calculations that I have an error. I am not sure how to add code tags but I have put comments throughout the program. Here are my error messages and my entire program to date.
Exception in thread "main" java.lang.NullPointerException
at javax.swing.JTable$1.getRowCount(JTable.java:666)
at javax.swing.JTable.getRowCount(JTable.java:2631)
at javax.swing.plaf.basic.BasicTableUI.createTableSiz e(BasicTableUI.java:1646)
at javax.swing.plaf.basic.BasicTableUI.getPreferredSi ze(BasicTableUI.java:1687)
at javax.swing.JComponent.getPreferredSize(JComponent .java:1634)
at javax.swing.JViewport.getViewSize(JViewport.java:1 018)
at javax.swing.ScrollPaneLayout.preferredLayoutSize(S crollPaneLayout.java:476)
at java.awt.Container.preferredSize(Container.java:15 99)
at java.awt.Container.getPreferredSize(Container.java :1584)
at javax.swing.JComponent.getPreferredSize(JComponent .java:1636)
at java.awt.GridBagLayout.GetLayoutInfo(GridBagLayout .java:1092)
at java.awt.GridBagLayout.getLayoutInfo(GridBagLayout .java:893)
at java.awt.GridBagLayout.ArrangeGrid(GridBagLayout.j ava:2048)
at java.awt.GridBagLayout.arrangeGrid(GridBagLayout.j ava:2008)
at java.awt.GridBagLayout.layoutContainer(GridBagLayo ut.java:789)
at java.awt.Container.layout(Container.java:1421)
at java.awt.Container.doLayout(Container.java:1410)
at java.awt.Container.validateTree(Container.java:150 7)
at java.awt.Container.validateTree(Container.java:151 3)
at java.awt.Container.validateTree(Container.java:151 3)
at java.awt.Container.validateTree(Container.java:151 3)
at java.awt.Container.validate(Container.java:1480)
at java.awt.Window.show(Window.java:861)
at java.awt.Component.show(Component.java:1584)
at java.awt.Component.setVisible(Component.java:1536)
at java.awt.Window.setVisible(Window.java:842)
at mortgagecalculator2.MortgageCalculator2.main(Mortg ageCalculator2.java:277)
Java Code:/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package mortgagecalculator2; /* * This is a mortgage calculator designed with a GUI interface * allowing the user to enter amount of the mortgage, the term of the mortgage, * and the interest rate of the mortgage. * The program will contain a loop allowing the user to calculate different * senarios and combinations until they select to quit. */ //import all necessary components import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import java.io.*; import java.text.*; /** * * @author Burlison */ // class to build GUI components public class MortgageCalculator2 extends JFrame { //Create Lables and Text fields for user input on the GUI private JLabel loanLabel, interestLabel,payLabel, space; //Create Radio Buttons to select term private JRadioButton low, medium, high; private ButtonGroup group; //used to put the radio buttons in a single group so they can see each other //Create Buttons for Calculating the payment,clearing information, and exiting program private JButton calculate, clear, exit; //Text field to allow input of loan amount private JTextField loan, interestRate,payment; //string items to pass into radio button Item listener private String lrate = "0.0535"; private String mrate = "0.055"; private String hrate = "0.0575"; //Table for results of calculation JTable table; //Arrays to hold the headers of a JTable and Mortgage Information String[] interestRates = {"5.35", "5.50", "5.75"}; String[] term = {"7", "15", "30"}; String[] columnNames = {"Month", "Principle", "Interest", "Balance"}; Object[][] data = {{"","","",""}}; public MortgageCalculator2() { setLayout(new GridBagLayout()); //layout style for display GridBagConstraints c = new GridBagConstraints(); //used to give infomation on where component is placed on JFrame //Actual Grapic layout for the GUI loanLabel = new JLabel("Loan Amount: "); // creates grapic label to display on JFrame c.fill = GridBagConstraints.HORIZONTAL; // Label runs horizonal in display c.gridx = 0; // gives the x cordinant of the label c.gridy = 0; // gives the y cordinant of the label add(loanLabel, c); // adds the label at the specified cordinants loan = new JTextField(8); // creates new text box with max of 8 charactors c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 1; c.gridy = 0; c.gridwidth = 3; // set the with of the text box on the screen add(loan, c); low = new JRadioButton("7 years", true); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridy = 1; c.gridwidth = 1; add(low, c); medium = new JRadioButton("15 years", false); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 1; c.gridy = 1; add(medium, c); high = new JRadioButton("30 years", false); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 2; c.gridy = 1; add(high, c); group = new ButtonGroup(); //not graphic display item this is used to allow the radio buttons to group.add(low); //know each others status so only one can be filled at a time. group.add(medium); group.add(high); interestLabel = new JLabel("Interest Rate: "); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridy = 2; add(interestLabel, c); interestRate = new JTextField(lrate); //creats an empty lable to display the interest rate when number of years selected. interestRate.setEditable(false); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 1; c.gridy = 2; c.gridwidth = 3; add(interestRate, c); space = new JLabel(" "); //needed to add space after interest rate before buttons c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridy = 3; add(space, c); payLabel = new JLabel("Payment: "); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridy = 4; add(payLabel, c); payment = new JTextField(10); payment.setEditable(false); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 1; c.gridy = 4; add(payment, c); space = new JLabel(" "); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridy = 5; add(space, c); calculate = new JButton("Calculate"); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridy = 6; c.gridwidth = 1; add(calculate, c); clear = new JButton("clear"); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 1; c.gridy = 6; add(clear, c); exit = new JButton("Exit"); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 2; c.gridy = 6; add(exit, c); space = new JLabel(" "); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridy = 7; add(space, c); table = new JTable(data, columnNames); table.setPreferredScrollableViewportSize(new Dimension(800, 100)); table.setFillsViewportHeight(true); JScrollPane scrollpane = new JScrollPane(table); scrollpane.setMinimumSize(new Dimension(810,110 )); c.fill = GridBagConstraints.CENTER; c.gridx = 0; c.gridy = 8; c.gridheight = 10; c.gridwidth = 10; add(scrollpane, c); //add item listener for radio buttons low.addItemListener(new HandlerClass(lrate)); medium.addItemListener(new HandlerClass(mrate)); high.addItemListener(new HandlerClass(hrate)); //add action listener for JButtons Calculator handler1 = new Calculator(); calculate.addActionListener(handler1); Clear handler2 = new Clear(); clear.addActionListener(handler2); Exit handler3 = new Exit(); exit.addActionListener(handler3); } //Item listener for the radio buttons. private class HandlerClass implements ItemListener { private String irate; //String item get variable rate public HandlerClass(String ir) { irate = ir; } @Override public void itemStateChanged(ItemEvent event) { interestRate.setText(irate); } } private class Calculator implements ActionListener { //Action Listener for calculate button @Override public void actionPerformed(ActionEvent event1) { try { //calculate monthly payment int t =0; double p = Double.parseDouble(loan.getText()); //used to get the principle entered by the user in the text box double r = Double.parseDouble(interestRate.getText())/12; //used to get the interest rate set in the text box by the radio buttons. //if else statmenst to check the status of the active radio button and set the term for the loan if(low.isSelected()){ t = 7*12; } else if(medium.isSelected()) { t = 15*12; } else if(high.isSelected()) { t = 30*12; } double monthlyPayment = p*Math.pow(1+r, t)*r/(Math.pow(1+r,t)-1); //Math equation to get monthly payment DecimalFormat df = new DecimalFormat("###,###.00"); //use to format the output payment.setText(df.format(monthlyPayment)); // Calculat the loan schedule double principal = p; int month; data = new Object[t][4]; //StringBuilder buffer = new StringBuilder(); //buffer.append("Month \t Amount \t Interest \t\t Balance\n"); for (int i=0; i<t; i++) { month=i+1; double interest = principal*r; double balance = principal + interest - monthlyPayment; data[i][0]=month; data[i][1]=principal; data[i][2]=interest; data[i][3]=balance; principal = balance; } }catch (Exception er) { System.out.println(er); JOptionPane.showMessageDialog(null, "Invalid input: click clear and try again"); } } } //Listens Clear button and clears all information when button is pressed private class Clear implements ActionListener { @Override public void actionPerformed(ActionEvent event2) { loan.setText(""); payment.setText(""); data = null; } } //Listens for exti button and exits the program when button is pressed. private class Exit implements ActionListener { @Override public void actionPerformed(ActionEvent event3){ System.exit(1); } } public static void main(String[] args) { // used to create the GUI window MortgageCalculator2 gui = new MortgageCalculator2(); gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); gui.setVisible(true); gui.setSize(900, 600); gui.setTitle("My Mortgage Calculator"); } }Last edited by sunde887; 08-06-2011 at 04:03 PM. Reason: Added code tags, [code]...[/code] for future reference.
- 08-06-2011, 08:26 AM #6
Why are you using double dimensional array for displaying data in JTable? Try using TableModel.
Some steps are:
1. Create a class that extends AbstractTableModel class.
2. In this class atleast override/define four methods:
a). public int getRowCount() //The no of rows the Table will display.
b). public int getColumnCount() //The no of columns the Table will display.
c). public Object getValueAt(int rowIndex, int columnIndex) //The value at the particular cell of the table
d). public String getColumnName(int col) //The name of the column
3. If you want to change the values in the Table dynamically, Then change the values and assure that the above methods must return the values as you want
then on the reference of the object of your TableModel class call
fireTableChanged(null);
4. Use the Constructor JTable(TableModel) instead of JTable(Object[][] value,String[] label)...
This will surely help in solving your problem...
- 08-06-2011, 03:55 PM #7
Member
- Join Date
- Aug 2011
- Posts
- 13
- Rep Power
- 0
javax.swing.table.DefaultTableModel model = new DefaultTableModel();
String [] filed_names;
Object [][] data;
model= new DefaultTableModel(data, field_names);
jTable1.setModel(model);
if you get data from db then use resultset.getstring and assing data to data array. you can use getrowcount and getcolumncount as index for assinging values.
have a good luck.Last edited by delican; 08-06-2011 at 04:00 PM.
- 08-07-2011, 04:16 AM #8
Member
- Join Date
- Aug 2011
- Posts
- 8
- Rep Power
- 0
- 08-15-2011, 03:31 AM #9
Member
- Join Date
- Aug 2011
- Posts
- 8
- Rep Power
- 0
Here is my issue. I need to be able to store the calculations in an array so that it can be retrieved and displayed again at a later date. I am unsure how properly over ride the table model but is seems you have some ideal of how to do it with the default model. the data will be calculated off the entries of the user. I have a loop doing the calculations and need this loop to store each row of data in the array. I can display it in a standard text area but when the amounts change the columns don't line up so I need this JTable to work. SO when using getrowcount and getcolumncount how do I set them up in the loop to receive the data?
-
If you store your data in a DefaultTableModel, then it will be retrievable later.
- 08-18-2011, 05:00 AM #11
Member
- Join Date
- Aug 2011
- Posts
- 8
- Rep Power
- 0
I am having difficulty finding information on how to set up a DefaultTableModel to accept my information. I need to pass 4 columns into the table int month, Double Principal, Double Interest, Double Balance. I can't find information on exactly how to do this can you point me in the right direction?
-
Suggestions:
- First and foremost, check out the DefaultTableModel API and link to it so you can go back to it for reference.
- You will want to create a class that extends DefaultTableModel.
- This class will override the getColumnClass method so that it returns the appropriate class for each column based on the column's index: Integer.class for a column index of 0 and for everything else, have it return Double.class.
- Check out the DefaultTableModel constructors. You'll want your class's constructor call the super constructor that allows you to load in a String array with the column heading names, and the int, 0, for 0 rows.
- For each row of data, you'll want to create an array of Object, Object[], that holds 4 items, an Integer and 3 Doubles. Note that you cannot use primitives here but must use the object wrappers instead (i.e., Integer, not int, and Double, not double).
- To add one of these Object arrays to make a row, simply call addRow(...) on your DefaultTableModel object passing in the array.
- If you get stuck, strongly consider creating and posting an SSCCE that demonstrates your problem.
Best of luck.
- 08-18-2011, 10:28 PM #13
Member
- Join Date
- Aug 2011
- Posts
- 8
- Rep Power
- 0
Ok I have some questions you say I need an Object array for each row and I have 360 rows in my longest equation so how do I create on the fly 360 Object[] arrays. Or is there a way for me to use a two dimensional array Object[][] where the first array is the row index and the second is the 4 pieces of data? Second for the use if they calculate a mortgage and want to save it and then calculate another and save it etc how to I separate each one for them to refer back to later?
-
How do you create 360 of anything? use a loop, a for loop to be exact, loop 360 times, and inside the loop create one Object[] array and add that row into your table model.
You'll probably store it to disk perhaps using serialization or a database.Second for the use if they calculate a mortgage and want to save it and then calculate another and save it etc how to I separate each one for them to refer back to later?
- 08-19-2011, 01:35 AM #15
Member
- Join Date
- Aug 2011
- Posts
- 8
- Rep Power
- 0
Ok so I have a loop in my program for the calculation so all I need to do is create and object array say
for (i=0; i<360; i++)
{ Object[i] month {= {Integer month};
Object[i] principal ={ Double principal};
Object[i] interest = {Double interest};
Object[i] balance = {Double balance};
}
This will create 360 instances of each column then how would I pass that into the table? That is where I seem to get lost
-
Again inside the loop you add the Object array to the table model. Pseudocode would look like this:
Also please don't forget to use code tags even when posting only a small snippet of code. We greatly appreciate it if you can make it easy for us to help you.Java Code:for int i goes from 0 to < 360 create a one dimensional Object[] array to hold 4 Objects. add the i-th row's data into this array // I think you're missing this step below: call addRow on my DefaultTableModel and add the array I just created and filled end for loop
Similar Threads
-
Adding all elements of an Array together, not adding up correctly
By Teclis in forum New To JavaReplies: 1Last Post: 04-05-2011, 08:58 PM -
Adding elements to an array
By slitka in forum New To JavaReplies: 9Last Post: 04-01-2011, 04:01 AM -
Adding elements before and after array
By liQuorice in forum New To JavaReplies: 4Last Post: 03-04-2011, 12:52 AM -
Adding the Elements of a 2D Array
By RMcLuckie45 in forum New To JavaReplies: 0Last Post: 11-07-2010, 11:04 PM -
Adding elements to an Object Array
By aneesahamedaa in forum New To JavaReplies: 4Last Post: 09-07-2008, 03:55 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks