Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 7 of 7

Thread: Hello everyone! I need help with JTable

  1. #1
    Junior Member
    Join Date
    Oct 2010
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Hello everyone! I need help with JTable

    Hi everyone i'm a newby with java

    I have a JTable where birdwatchers can put in the column "[Bird Seen] ,how much birds they have seen.
    And if you push the >SEND> button this account of [Birds Seen] must be accumelated on the [Birds Total] column.
    For example if you put 3 in column [Birds Seen] then also 3 must appear in the column [Birds Total] after you push the >SEND> button.
    But if you put for the second time lets say 4 in column [Bird Seen] then 7 must appear on the column [Birds Total]. Because you saw the first time 3 birds and the second time 4 birds so 3+4=7.

    I hope you understand what i mean, if not don't bother to ask.
    Here is a picture of how my table looks like, And the java code.

    every help is welcom!



    package Tabel01;
     
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.ScrollPaneConstants;
    import javax.swing.table.AbstractTableModel;
     
     
    public class TableDemo extends JPanel implements ActionListener   {
     
        /**
         * 
         */
        private static final long serialVersionUID = 1L;
     
        public  JButton   actieknop;
        public  JFrame    venster;
        public  JTable    table;
        public  JPanel    panel1, panel2;
     
     
        public TableDemo() {
     
            //Create and set up the window.
             venster = new JFrame("BirdCount");
     
     
            //make panels
             panel1 = new JPanel();
             panel2 = new JPanel();
             //Create and set up the content pane.
              venster.add(panel1, BorderLayout.CENTER);
             venster.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             venster.setSize(450,300);
     
             //make table
                table = new JTable(new MyTableModel());
                panel1.add(table);
                JScrollPane scroller1 = new JScrollPane(table);
                scroller1.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
                scroller1.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
                panel1.add(scroller1);
     
     
            table.setPreferredScrollableViewportSize(new Dimension(250, 150));
     
     
            //Make button
             actieknop = new JButton(">SEND>");
             actieknop.addActionListener(this);
             panel2.add(actieknop);
             //panel2.add(actieknop2);
             venster.add(panel2, BorderLayout.EAST);
     
     
             //Display the window.
             venster.setVisible(true);
    }
     
        class MyTableModel extends AbstractTableModel {
     
            /**
             * 
             */
            private static final long serialVersionUID = 1L;
     
            String[] columnNames = { "Bird",
                                               "Birds seen",
                                                   "Birds Total",
                                                           };
     
             Object[][] data = {
                   {"falck", "",
                       "", new Integer(0) , new Integer(0)},
                       {"pigeon", "",
                           "", new Integer(0), new Integer(0)},
                           };
     
             public int getColumnCount() {
                 return columnNames.length;
             }
     
             public int getRowCount() {
                 return data.length;
             }
     
             public String getColumnName(int col) {
                 return columnNames[col];
             }
     
             public Object getValueAt(int row, int col) {
                 return data[row][col];
             }
     
             public boolean isCellEditable(int row, int col) {
                 //Note that the data/cell address is constant,
                 //no matter where the cell appears onscreen.
                 if (col == 0 || col == 4){
                     return false;
                 }
               else {
                     return true;
                 }
             }
        }
     
     
         public static void main(String[] args) {
         new TableDemo();
     
         }
     
    @Override
        public void actionPerformed(ActionEvent arg0) {
            // TODO Auto-generated method stub
     
        }
             }
    Attached Images Attached Images
    Last edited by JavaPF; October 11th, 2010 at 11:12 AM. Reason: Please use highlight tags instead of code tags


  2. #2
    Member Darryl.Burke's Avatar
    Join Date
    Mar 2010
    Location
    Madgaon, Goa, India
    Posts
    494
    Thanks
    8
    Thanked 48 Times in 46 Posts

    Default Re: Hello everyone! I need help with JTable

    I hope you understand what i mean, if not don't bother to ask.
    OK I won't. I wish you luck with getting help without a clear description of what's happening that shouldn't, or not happening that should.

    db

  3. #3
    Junior Member
    Join Date
    Oct 2010
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Hello everyone! I need help with JTable

    Hi thank you for your quick reply.
    i'm not so good at writing english maybe thats why you don't understand me.:confused
    a clear description of what's happening that shouldn't, or not happening that should.
    The problem is not that something is happening i don't want to happen.
    But i have explained what i would like to happen if i push the >SEND> Button.
    I hoped someone could tell me how i could make work the >SEND> buton, like i explained in the introduction.
    Because i don't know how i must pass a number from one column to another in a JTable.

    i think i should do it with public void actionPerformed(ActionEvent arg0) { }, But i'm really a beginner with java so i hoped someone can give me a hint to get started.
    Or should i put an if/ else statement in actionPerformed.

  4. #4
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Hello everyone! I need help with JTable

    Quote Originally Posted by hektor View Post
    Hi thank you for your quick reply.
    i'm not so good at writing english maybe thats why you don't understand me.:confused


    The problem is not that something is happening i don't want to happen.
    But i have explained what i would like to happen if i push the >SEND> Button.
    I hoped someone could tell me how i could make work the >SEND> buton, like i explained in the introduction.
    Because i don't know how i must pass a number from one column to another in a JTable.

    i think i should do it with public void actionPerformed(ActionEvent arg0) { }, But i'm really a beginner with java so i hoped someone can give me a hint to get started.
    Or should i put an if/ else statement in actionPerformed.
    Ok, I understand what you are saying.

    This is actually quite simple. You know the row directly above the row you are adding to has the total. And you know how much you want to add to that total to get the value you are inserting into the current row.

    There are two ways of doing this:
    Method 1:
    So, the first thing you need to do is check which row has been added to. Provided the user has not changed the row they have added to, there is no problem. Otherwise, method 2 will be better. This method ALSO assumes the user hasn't changed any previous values. So, to do this, you first need to check the if you are on the first row. This can be done with the statement:
    if(table.getSelectedRow()==0)
    {...}
    else
    {...}
    If the selected row is the first row, then you want its column value to be equal to the value inputted on the left. Otherwise, you want the value to be equal to the value directly above + the value directly to the left. You can get these value using the method:
    int value = Integer.parseInt(table.getValueAt(row,column))
    Where: row is the row of the value you are getting and column is the column of the value you are getting. Keep in mind that you want to parse what you get here into an int. This is because the getValueAt(int,int) method returns an Object, but we need to add with ints. As a result, we have to parse the Object into an int. You know that if you are trying to get the value of the row previous to the current selected one, you can say:
    int row = table.getSelectedRow()-1;
    and if you are trying to get the column of value to the left of you, then column would be equal to 1. Although it is Column 2, it is Column Index 1.
    Lastly, you need to set the value of the cell using the method:
    table.setValueAt(value,row,column);
    Where: value is the value you have after you have added together the cell directly above you and the cell to the left of you. row is the the current row you are adding to. And column is the equal to 2.

    Method 2:
    This method is probably the better option, as it is more dynamic. Here we use a LOOP instead of an IF statement. For this, we will go through each row and add the values each time the button is pressed. Although this may mean we are reevaluating values that will not change, it is a better option if those values could change.
    What we can do is Loop through every row and add up the values in the column directly to the left of it. To do this, we need to create a FOR LOOP like this:
    for(int i=0;i<table.getRowCount();i++)
    {...}
    This FOR LOOP does not require us to check if there is only 1 row, as that is handled in the by the condition. Now, we want another FOR LOOP inside that loops through all the rows as well. To declare that, our total looping would look like this:
    for(int i=0;i<table.getRowCount();i++)
    {
    	for(int n=0;n<=i;n++)
    	{...}
    }
    The reason we do this is because we want to add up all the values on the cell on the left. But we also want to increment down the JTable rows. Keep in mind that our condition in our nested FOR LOOP goes until it is EQUAL TO OR LESS THAN our i variable. This is because we want to add up to, and including the row we are accessing. Now that we have our nested FOR LOOPs, we need to get each value and add them all together. This requires we make our total variable outside of our inner FOR LOOP and that we use the getValueAt(int,int) method that we discussed earlier. So, that would look like this:
    for(int i=0;i<table.getRowCount();i++)
    {
    	int total = 0;
    	for(int n=0;n<=i;n++)
    	{
    		total += Integer.parseInt(table.getValueAt(n,1));
    	}
    }
    What this is saying is that we are getting the value of Column 2 on Row n and adding it to our total. The int parsing is explained on Method 1. The last thing we need to do is set the value at the Column 3 on Row i to be equal to our total variable. In order to do that, we need to use the setValueAt(Object,int,int) method which was explained in Method 1. That would look like this:
    for(int i=0;i<table.getRowCount();i++)
    {
    	int total = 0;
    	for(int n=0;n<=i;n++)
    	{
    		total += Integer.parseInt(table.getValueAt(n,1));
    	}
    	table.setValueAt(total,i,2);
    }

    I believe that is it. Tell me if you have any questions. I want to make sure you understand the code.
    Last edited by aussiemcgr; October 9th, 2010 at 11:30 AM.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  5. The Following User Says Thank You to aussiemcgr For This Useful Post:

    JavaPF (October 11th, 2010)

  6. #5
    Junior Member
    Join Date
    Oct 2010
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Hello everyone! I need help with JTable

    Hello, thank you for explaining everything
    I read everything and have learnt a lot, but there are still things i don't understand.
    Sometimes java is like reading chinees

    i have put the code from METHOD 2 you gave me in actionPerformed:
        public void actionPerformed(ActionEvent arg0) {
        for(int i=0;i<table.getRowCount();i++)
        {
            int total = 0;
            for(int n=0;n<=i;n++)
            {
                total += Integer[COLOR="Red"].parseInt[/COLOR](table.getValueAt(n,1));
            }
            table.setValueAt(total,i,2);
        }
     
        }
    but i get an error message at parseInt:
     [The method parseInt(String) in the type Integer is not applicable for the argument (Object)]



    And if i push the button >SEND> then i get an error :
     Exception in thread "AWT-EventQueue-0" java.lang.Error: Unresolved compilation problem: 
        The method parseInt(String) in the type Integer is not applicable for the arguments (Object)
     
        at Tabel01.TableDemo.actionPerformed(TableDemo.java:127)
        at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
        at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
        at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
        at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
        at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
        at java.awt.Component.processMouseEvent(Unknown Source)
        at javax.swing.JComponent.processMouseEvent(Unknown Source)
        at java.awt.Component.processEvent(Unknown Source)
        at java.awt.Container.processEvent(Unknown Source)
        at java.awt.Component.dispatchEventImpl(Unknown Source)
        at java.awt.Container.dispatchEventImpl(Unknown Source)
        at java.awt.Component.dispatchEvent(Unknown Source)
        at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
        at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
        at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
        at java.awt.Container.dispatchEventImpl(Unknown Source)
        at java.awt.Window.dispatchEventImpl(Unknown Source)
        at java.awt.Component.dispatchEvent(Unknown Source)
        at java.awt.EventQueue.dispatchEvent(Unknown Source)
        at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
        at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
        at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
        at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
        at java.awt.EventDispatchThread.run(Unknown Source)

    I'm not sure what i should do, i tried to change'some things like the table from Object to Integer but it still wont work.
    I tried to use the METHOD 1 you gave me with the if statement, but i get the same errors.
    I think i'm out of ideas!

  7. #6
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Hello everyone! I need help with JTable

    eh, do this instead:
    total += Integer.parseInt(table.getValueAt(n,1).toString());

    I think you can alternatively do:
    total += ((Integer)table.getValueAt(n,1)).intValue());

    I can't remember exactly how to turn an Object into a primitive type. Both of those should do it however.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  8. #7
    mmm.. coffee JavaPF's Avatar
    Join Date
    May 2008
    Location
    United Kingdom
    Posts
    3,336
    My Mood
    Mellow
    Thanks
    258
    Thanked 294 Times in 227 Posts
    Blog Entries
    4

    Default Re: Hello everyone! I need help with JTable

    Thread moved to AWT / Java Swing - Java Programming Forums
    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.

Similar Threads

  1. JTable Row Color
    By aussiemcgr in forum Java Theory & Questions
    Replies: 2
    Last Post: October 8th, 2010, 03:59 PM
  2. JTable Quick Help
    By aussiemcgr in forum AWT / Java Swing
    Replies: 1
    Last Post: September 2nd, 2010, 05:58 PM
  3. JTable CheckBoxes
    By aussiemcgr in forum AWT / Java Swing
    Replies: 1
    Last Post: August 9th, 2010, 01:04 PM
  4. JTable Questions
    By aussiemcgr in forum AWT / Java Swing
    Replies: 21
    Last Post: August 9th, 2010, 02:34 AM
  5. JTable in JScrollPane
    By alwayslearner in forum AWT / Java Swing
    Replies: 1
    Last Post: January 31st, 2010, 10:24 PM