• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Tim Cooke
  • Devaka Cooray
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
Bartenders:
  • Carey Brown
  • Roland Mueller

Row Selection problems with JTable

 
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello!

I am working on a project for school, and have run into a couple of problems with a JTable. The project compiles, but does not do two things. The first is in an attempt to select the first row upon program start, which returns the error "Row Index out of Range". I cannot get past this error. To run what I have, I have commented out this line. The other problem is in cycling through the rows with a next button. (There will be a previous button too but with a next button working properly, I can handle this.) I know that the default behavior if I hit the enter key will do the same thing, but I need a next button for the assignment. As it stands, nothing happens when I hit the button..... Any help is appreciated! Thanks!

 
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
you need to tidy up some things before proceeding,

you extend JTable
class InventoryTest extends JTable

and call many methods: (some)
setSelectionMode( ListSelectionModel.SINGLE_SELECTION );
getRowCount();
setRowSelectionInterval( 0, getRowCount()-1 );//attempt to

but the real JTable, the one on the screen, is the created (not extended) one
final JTable table = new JTable( dm )

fix it all up (remove the "extends JTable", then fix compile errors one at a time),
and post back if the problem persists
 
Bartender
Posts: 11497
19
Android Google Web Toolkit Mac Eclipse IDE Ubuntu Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You are subclassing JTable but creating and using a new JTable inside it !
Your subclassed JTable has zero rows.
Try

I personally would use getSelectionModel().setRowSelectionInterval(). The JTable itself is not aware of any selections (neither is it aware of the data). Using this style always helps me remember this fact. If you check out the code in JTable, you will notice it is just a pass through method, which calls the selection model method anyway. Needless to say, it is a matter of personal preference.

Edit: Damn! Michael beat me to it. Doesn't he ever sleep?
 
Debra Simeroth
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Edit: Damn! Michael beat me to it. Doesn't he ever sleep?



Ha Ha! You guys make me laugh... OK, my first thought was indeed that I had too much going on in this module... (is that correct terminology?) I will edit and see if the problem persists... BTW, I did try the getSelectionModel().setRowSelectionInterval() option and didn't get anywhere.... Guess I will go back to the OO drawing board and make some objects... Has anyone seen "The Lost Room"? I started to do it, but had a myriad of errors. That could explain my problem. Hopefully I wont be back. One last question... my code is OK?... it is just all confused because of my poor structure? Thanks again...
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
> One last question... my code is OK?...

at a quick glance, what do you expect the nxtBtn actionListener to do? (just be reading the code)
 
Maneesh Godbole
Bartender
Posts: 11497
19
Android Google Web Toolkit Mac Eclipse IDE Ubuntu Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The getSelectionModel approach will work once you call it on the correct table.

You have one class which does everything.
I would split it into parts
1) One class to initialize the JFrame and add its children
2) One class to define the table functionality
3) One class to generate/populate the data in the table model. Right now you are hard coding the data. In future, when you want to fetch it from some DB or something, it is very easy to do so, without touching any other classes.

In general, try to emulate the way the java classes themselves are coded. There is a clear distinction in functionality.
 
Debra Simeroth
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Michael Dunn wrote:at a quick glance, what do you expect the nxtBtn actionListener to do? (just be reading the code)



Hi Michael,

The next button should simply highlight the next row, and upon reaching the last row, move up to the first. At this juncture in my learning, that is what it looks like it will do.
 
Rancher
Posts: 3324
32
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

The first is in an attempt to select the first row upon program start,



I just use:



You can use the same method in your Next button logic.

I know that the default behavior if I hit the enter key will do the same thing



If you want a fancy solution you would just reuse the existing Action that is invoked by the Enter key. Check out the
Action Map Action. Its probably not something you want to hand in for a school assignment, but others reading this posting might find it interesting.
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
> The next button should simply highlight the next row, and upon reaching the last row, move up to the first.

your actionPerformed is not going to do that.


add the indicated line, then click the button multiple times, see what happens
 
Debra Simeroth
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Somehow, I feel like I have just learned multiplication and forgot how to add! Learn the more complex, and forget the simple! I think, and the operative word here is think (which could be all wrong) that I have this right... however am having trouble with my main method now. The examples in my text have the data in the main method, and the method I was using before to runt the program isn't working now. The only error I have at the moment is with the "run" method in InventoryMain. Of course, I haven't been able to run the whole programs so who knows what errors I will have! I will leave out my class "Item", because there is no issue with it.

Thanks again... in advance :D





and edited in as Michael suggests is Item....
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
with the latest code, you seem to be going backwards

some points:
your table with the renderer is in class Table, but local to 'public void table( Data row )'
Table() is not created anywhere
your data is in class Data, again local to 'public void table( Data row )'
Data() is not created anywhere
this 'public void table( Data row )' does not create a Data object.
your nxtBtn actionPerformed still does not do what you want.
'new InventoryFrame().buildGUI();' won't compile as you've now given buildGUI an argument to be supplied 'public void buildGUI( JTable table)'
you still have 'extends JTable', but a lot of your code deals with a created JTable (not extended)

try going back to the original post of mine in your other thread, then adding one modification at a time, compiling/running/testing at each modification.


> I will leave out my class "Item", because there is no issue with it.

most here need to run your code to see what's happening, make adjustments, test etc,
so unless they know they can get Item() from your other post, they'll probably skip over this thread
 
Debra Simeroth
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Michael Dunn wrote:with the latest code, you seem to be going backwards

:cry:

[hangs head and sighs] This is so hard! I recommend that no one take a accelerated online Java programming course... especially with no other programming experience! The real bummer is that I want to learn this, but there is so much to learn! OK, so I will go back to object creation and review.... constructors and review.... as well as review what you have written.... Thanks Michael. I wish I could understand what key concepts I am not getting so I can go back and study them further. Thanks again for your help.
P.S. I added class Item.
 
Rob Camick
Rancher
Posts: 3324
32
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Well, like most newbies you haven't developed debugging skills yet.

As I understand the question you want to know how to create a "Next" button selects the next row. Well 99% of the code you posted has absolutely nothing to do with that requirement. So when you try to learn a new concept you start by creating a simple test program. This can be done in 5 minutes.

All you need is:

a) a JTable in a scrollpane
b) a JButton with an ActionListener added to it
c) A JFrame to add the scroll pane and button to.

It takes one line of code to create a JTable:

JTable table = new JTable(20, 5);

It will take another maybe 5-6 lines to create a button with an ActionListener. And a few more lines to create the frame. This a called a SSCCE (Short, Self Contained, Compilable and Executable, Example Program).

Now you can start testing different ideas. I've already given you a simple way to change the row selection.

So create your SSCCE. Try the suggestions. If it doesn't work then you have complete code to post not bits and pieces.

Then once you understand the basic concept you can add it back into your real program.
 
Debra Simeroth
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Rob Camick wrote:Well, like most newbies you haven't developed debugging skills yet.



Hi Rob,

Yes, you are right... the debugging window is a window I have no idea what to do with... My idea of debugging is to rewrite the code that doesn't compile... [blushes a little] I have started using NetBeans which is nice because I can compile and run in the same window... The API docs are all here for me too. Beyond this, I have a rapid response group (Java Ranch) to help me. Thanks for the tip, I will start using it right away.... BTW, I took 3 steps back to my original code in this post and am starting over... Your previous post with the " table.changeSelection(0, 0, false, false);" code got me off to a good start and I will follow your advice... along with the suggestions of the "most worthy" Michael Dunn.

Thanks!
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
what follows is for a single .java file (break it up later into individual classes)

I just followed these steps, and it displyed fine, actionListeners performed OK

1) add class Item, compile

2) add class Data, but have it return a DefaultTableModel, compile
also suggest changing method name to be more self-explanatory
//public void data()
to
public DefaultTableModel getModel()
at the end of the method, create an instance of a DefaultTableModel using rowdata,colNames,
returning that object;
3) add class InventoryFrame, setting table's model to 'new Data().getModel()'
note: get rid of 'extends JTable', and use the table creation code you have in Table()
also get rid of the Table class
compile - you will get some errors where you need to add 'table.' in front of getRowCount() etc.
keep re-compiling, fixing one error at a time
compile until error free
add the DecimalFormatRenderer, recompile

4) add class InventoryMain, compile
it should be ready to run (error free) now.

at this point you have a visual 'view' of the data.

now you can add your other buttons/labels/other components
when they compile/run ok, add the listeners, compile

now you need to test the listeners (testing many times),
to do exactly what you want them to do.

your nxtBtn actionPerformed code, as written, just gets the currently selected row number,
then adds 1 to the rowNumber obtained - this will not change the selected row - you
have been shown the code to changeSelection, you need to use it in the listener code.
you need to use the % operator to 'wrap' the row, when required
int row = table.getSelectedRow();
row = (row+1) % table.getRowCount();
now changeSelection using row.
 
Debra Simeroth
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello Michael and Rob!

WOO HOO! I have been messing around in my SSCCE and got my button to work! Many thanks to you both for your patient guidance with this newbie :jumpingjoy: ! Here is the code that finally did it!



Now to begin work on my other buttons.... shouldn't be a big deal, just this code in reverse.

My final project for this class is next week.... I will start working on that as soon as I have this part completed.... Then I can study at a relatively normal pace, allowing time for this stuff to sink in. I will have another Java class in my Bachelors program, so I will keep studying until then... I don't want to do another accelerated course without having a good deal of knowledge under my belt. Thanks again guys! :beerchug:
 
Debra Simeroth
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
//found stupid error and will repost if i need to ... sorry for any inconvenience if anyone is responding!
 
Rob Camick
Rancher
Posts: 3324
32
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
First of all I know this is only a SSCCE but meaningfull names help and it doesn't take any more time. ButtonHandler and ButtonHandler1 mean nothing to me. Don't you think the words "next", "previous" should be included somewhere.

Also, you may not know this, but Frame is the class name of an AWT class. It is always a good idea to use a unique name.

Finally, the code you posted is overly complicated. It should not be much different than you "next" code. Even you next code is a bit messy with redundant and unused code.

I commented out all the unused code from both:


 
Debra Simeroth
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Rob Camick wrote:



Hi Rob,

I was getting ready to ask for help... again, when i saw your post; which by the way, worked quite well. Why is it, though, that getRowCount -1 works? Doesn't the row count return the integer value of the the row? Why would I need to subtract one? I understand the zero based count used in Java, but doesn't the program itself account for that, or are tables not zero based?? Your insight, as well as your help, are both greatly appreciated!

Thanks again....

Your most humble student,
Deb

By the way... I set up my SSCCE to be reused for other projects, which is why I didn't use any real naming convention.... Sorry. I have also been using NetBeans, and discovered, after my post, that I had failed to name my SSCCE as my main project. Hence, nothing that I compiled made any difference in the actual running of my program, so I felt obligated to go back and "re-try" everything I had learned in my recent studies. Ultimately, I still needed the help. I was beginning to think I needed to add an index or another listener!
 
Rob Camick
Rancher
Posts: 3324
32
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Debra Simeroth wrote:
I understand the zero based count used in Java



Not really, you still have some confusion. It is something you will need to get used to.

The getRowCount() returns the total number of rows in the table. If you have one row it returns "1".

If you want to select that row you use "0" as an index.

I would also suggest you don't understand why the following line of code works:



That line of code is equivalent to:



 
Lasagna is spaghetti flvored cake. Just like this tiny ad:
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic