Results 1 to 16 of 16
Thread: Creating a table
- 04-17-2012, 07:48 PM #1
Member
- Join Date
- Mar 2012
- Posts
- 50
- Rep Power
- 0
Creating a table
I would like to create a table of data in my program with a Swing GUI, that would look something like this:

Though there don't need to be spaces between the cells.
I thought of using a JTable and a JTableHeader, but 1) I don't know how to put an image into a cell of a JTable, and 2) according to the example in this tutorial, a JTable creates a table that allows some user interaction (kind of like a non-editable excel table - it allows row selecting and similar). I don't need any of that, I just want a simple data representation in the form of a table.
Is it possible to do that with a JTable or is there another class that I can use?
- 04-17-2012, 08:28 PM #2
Re: Creating a table
Sure does sound like a job for a JTable. You can use a custom renderer to display images (it's not as hard as it sounds), and you can disable the user interaction. Most of this is covered in the basic JTable tutorial: How to Use Tables (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Swing Components)
But if you really don't want to use a JTable, you have to use a layout: Lesson: Laying Out Components Within a Container (The Java™ Tutorials > Creating a GUI With JFC/Swing)How to Ask Questions the Smart Way
Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!
- 04-17-2012, 08:48 PM #3
Member
- Join Date
- Apr 2012
- Location
- Spainish TOwn
- Posts
- 25
- Rep Power
- 0
Re: Creating a table
In order to ensure that the table becomes able to accept data types like ImageIcon, you are required to do some extensions.
It becomes easy to manipulate a JTable if you had created a DefaultTableModel, then passed that to the table in initialization.
The DefaultTableModel is what you extend to ensure ImageIcon typed data add-ability.
You lament that you want a table with simple data representation, but it is somewhat unavoidable that you will have to dive into non-straightforward
code to generate tables that allow the addition of images to them. But this is easy, so just observe.
You would then pass the table to a JScrollPane, so you may scroll through items that exceed the default table height. I WILL INVEST MY KNOWLEDGE AND TIME in guiding you through this with code below:
Guideline:
IMPORTS
VARIABLESPHP Code:import javax.swing.ImageIcon; //if you want images in your table, you must import this shit. import javax.swing.JTable; //your table import javax.swing.table.DefaultTableModel; //your table model. This makes it very easy to add objects to table import javax.swing.JScrollPane; //your table container that will allow you to scroll though table items if many items are added
TABLE SETUPPHP Code:String columnHeaders [ ] = { "header 1", "header 2", "header 3", "header 4" }; //this is your actual column header data, each string representing a different column heading. String tableData [ ] [ ]; //this two dimensional array is what will hold your table data. int itemCount = 0; //you need to keep track of the items you add to table. JTable table; //your table DefaultTableModel model; //your table model JScrollPane scrollPane; //your table container. you would add this to the panel, so as to display the table.
PHP Code://establish the table model..passing the tableData, and columnHeaders //this is the normal way of declaring a table model, with no ImageIcon capability. model = new DefaultTableModel ( tableData, columnHeaders ); //you should comment this out. //But you have to extend it like this to be able to add images. model = new DefaultTableModel ( tableData, columnHeaders ) { //you need to accesss the column class of the table model, to establish that you want to add data types of various classes. //getColumnClass is a standard function here. public class getColumnClass ( int column_index ) { //this is where your item count comes in. Object object = getValueAt ( itemCount, column_index ); if ( object == null ) //if the added object is null, return Object.class; //then return its class else return object.getClass ( ); //or get its class by calling getClass ( ) on the object instance, that got the value at the itemCount, and column_index. } }; //NOW YOU NEED TO SETUP YOUR TABLE. Simple one line. table = new JTable ( model ); //you just pass the above model to it. //NOW SETUP SCROLL PANE. Simple once more, just pass the table to it. scrollPane = new JScrollPane ( table ); //DONE!!!
ADDING ELEMENTS TO THE TABLE.
PHP Code://YOU WILL USE THE EASE OF DEFAULT TABLE MODEL CAPABILITIES TO MANIPULATE YOUR TABLE. //adding an element to the end of the table model.addRow ( new Object [ ] { "a string", "a string", "a string", new ImageIcon ( "your picture.png" ) } ); //use table model itemCount ++; //you also need to increment item count!!!!!!!!!!!!!!!!! OR //adding an element to a specific index model.insertRow ( int index, new Object [ ] { "a string", "a string", "a string", new ImageIcon ( "your picture.png" ) } ); itemCount ++; //you also need to increment item count!!!!!!!!!!!!!!!!! //DONE!!!!
SHOWING THE TABLE IN YOUR PANEL.
PHP Code://Say you have a panel, to show the table just add the scrollPane to it.p your panel.add ( scrollPane );
- 04-18-2012, 08:09 PM #4
Member
- Join Date
- Mar 2012
- Posts
- 50
- Rep Power
- 0
Re: Creating a table
First off, thank you both for your replies. I've gone through the tutorial and your reply, Bushman, and there is now one thing I don't understand:
Is this really allowed? Defining a method that returns a class, not an object or primitive?Java Code:model = new DefaultTableModel ( tableData, columnHeaders ) { public class getColumnClass ( int column_index ) {
- 04-18-2012, 08:19 PM #5
Re: Creating a table
I would be pretty cautious of his code, to be perfectly honest. But yes, you can return a Class from a method. I still think using a renderer is the way to go.
How to Ask Questions the Smart Way
Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!
- 04-20-2012, 06:41 PM #6
Member
- Join Date
- Mar 2012
- Posts
- 50
- Rep Power
- 0
Re: Creating a table
OK I tried making a custom renderer but it's not working, so there is something I'm not doing right here. This is what I have now:
What am I doing wrong?Java Code:public class Test { public static void main (String[] args) { JFrame frame = new JFrame(); JPanel panel = new JPanel (new GridLayout (2,1)); JTable table; Object[][] data = {{"Blah", "Blah", "Blah"}}; Object[] header = { new ImageIcon ("C:/Path/Image1.png", "Wood"), new ImageIcon ("C:/Path/Image2.png", "Clay"), new ImageIcon ("C:/Path/Image3.png", "Iron") }; final TableCellRenderer headerRenderer = new HeaderRenderer(); table = new JTable (data, header); table.getTableHeader().setDefaultRenderer (headerRenderer); panel.add (table.getTableHeader()); panel.add (table); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); frame.add (panel); frame.setVisible (true); } private static class HeaderRenderer extends JLabel implements TableCellRenderer { public Component getTableCellRendererComponent (JTable table, Object object, boolean isSelected, boolean hasFocus, int row, int column) { if (object instanceof ImageIcon) { setIcon ((ImageIcon)object); setToolTipText (((ImageIcon)object).getDescription()); } else setText ((String)object); return this; } } }
- 04-20-2012, 07:19 PM #7
Re: Creating a table
Describe 'not working'
It's pointless to set a tooltip text to a renderer. Go back to the tutorial on How to Use Tables and go through the section about editor and renderer concepts to understand why.
I fail to understand why you want to use a GridLayout to display a JTable and its header.
dbWhy do they call it rush hour when nothing moves? - Robin Williams
- 04-20-2012, 08:12 PM #8
Member
- Join Date
- Mar 2012
- Posts
- 50
- Rep Power
- 0
Re: Creating a table
It displays the ImageIcon description strings (Wood, Clay and Iron), instead of the images.
The setToolTipText is just something I copied from the tutorial, I haven't gone through the tooltip section yet. I deleted it now, and everything's the same.
Because if I don't, it uses a FlowLayout, which displays the table next to the header, rather than below the header. And I don't want to use a scrollable pane for the table.Last edited by Mate de Vita; 04-20-2012 at 08:14 PM.
- 04-20-2012, 09:32 PM #9
Re: Creating a table
The JTable constructor you use applies the toString() of the elements of the header array to the table header. From the source:
If you want the header to contain ImageIcons as values, you will need to set them separately. e.g.Java Code:public JTable(final Object[][] rowData, final Object[] columnNames) { this(new AbstractTableModel() { public String getColumnName(int column) { return columnNames[column].toString(); } // <---- public int getRowCount() { return rowData.length; } public int getColumnCount() { return columnNames.length; } public Object getValueAt(int row, int col) { return rowData[row][col]; } public boolean isCellEditable(int row, int column) { return true; } public void setValueAt(Object value, int row, int col) { rowData[row][col] = value; fireTableCellUpdated(row, col); } }); }Also note that your renderer implementation is lacking in that it doesn't set the text to null for a header cell that contains an Icon, and doesn't set the Icon to null for a column that should show only text. It doesn't respect the foreground color of the table header, and a plain JLabel doesn't look much like a typical table header cell.Java Code:table.getTableHeader().getColumnModel().getColumn(0).setHeaderValue(new ImageIcon("C:/Path/Image1.png", "Wood"));
You may find it more convenient to extend my Default Table Header Cell Renderer « Java Tips Weblog class and add functionality to display your Icons.
FlowLayout and GridLayout aren't the only two layout managers in the book. You could use a BorderLayout (NORTH and CENTER) or a BoxLayout (Y_AXIS)Because if I don't, it uses a FlowLayout, which displays the table next to the header, rather than below the header. And I don't want to use a scrollable pane for the table.
dbLast edited by DarrylBurke; 04-20-2012 at 09:36 PM.
Why do they call it rush hour when nothing moves? - Robin Williams
- 04-21-2012, 06:57 AM #10
Member
- Join Date
- Apr 2012
- Location
- Spainish TOwn
- Posts
- 25
- Rep Power
- 0
- 04-21-2012, 10:13 AM #11
- 04-21-2012, 05:53 PM #12
Member
- Join Date
- Mar 2012
- Posts
- 50
- Rep Power
- 0
Re: Creating a table
I've done so now, and the images show up properly now. This is my program:
Is this OK now or is there still anything that I should fix/change/be careful about?Java Code:import java.awt.*; import javax.swing.*; import javax.swing.table.*; public class Test { public static void main (String[] args) { JFrame frame = new JFrame(); JPanel panel = new JPanel (new GridLayout (2,1)); JTable table; Object[][] data = {{"Blah", "Blah", "Blah"}}; Object[] header = {"","",""}; final TableCellRenderer headerRenderer = new HeaderRenderer(); table = new JTable (data, header); table.getTableHeader().getColumnModel().getColumn(0).setHeaderValue (new ImageIcon ("C:/Path/Wood.png", "Wood")); table.getTableHeader().getColumnModel().getColumn(1).setHeaderValue (new ImageIcon ("C:/Path/Clay.png", "Clay")); table.getTableHeader().getColumnModel().getColumn(2).setHeaderValue (new ImageIcon ("C:/Path/Iron.png", "Iron")); table.getTableHeader().setDefaultRenderer (headerRenderer); panel.add (table.getTableHeader()); panel.add (table); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); frame.add (panel); frame.setVisible (true); } private static class HeaderRenderer extends DefaultTableHeaderCellRenderer { private HeaderRenderer() { setHorizontalAlignment (CENTER); setVerticalAlignment (CENTER); setOpaque (false); } public Component getTableCellRendererComponent (JTable table, Object object, boolean isSelected, boolean hasFocus, int row, int column) { super.getTableCellRendererComponent (table, object, isSelected, hasFocus, row, column); if (object instanceof ImageIcon) { setIcon ((ImageIcon)object); setText (null); } else { setText ((String)object); setIcon (null); } return this; } } }Last edited by Mate de Vita; 04-21-2012 at 05:58 PM.
- 04-21-2012, 06:20 PM #13
Re: Creating a table
1. I would assign a TableColumnModel variable* the value returned from table.getTableHeader().getColumnModel() and use that variable for the next 3 lines. Less clutter, more readable.
2. The renderer text is already set by the call to the super implementation. You only need to set the icon to null in the 'else' condition. Also, for rendering the String representation of an Object type parameter, it's always more flexible to use toString() rather than casting to String.
3. All Swing components should be constructed and their methods called on the EDT and not on any other Thread -- not even the main Thread. Go through this Lesson: Concurrency in Swing (The Java™ Tutorials > Creating a GUI With JFC/Swing)
db
* edit In fact, it would be better still to assign a variable for the table header, as you have multiple calls to getTableHeader.Last edited by DarrylBurke; 04-21-2012 at 06:23 PM.
Why do they call it rush hour when nothing moves? - Robin Williams
- 04-22-2012, 11:14 PM #14
Member
- Join Date
- Mar 2012
- Posts
- 50
- Rep Power
- 0
Re: Creating a table
OK, thank you both. I'll be back later with more questions.
Right now, I'm going to go through all those tutorials, which I should and would have done in the first place, if I'd known this program would require virtually all the basics of Java.
- 04-23-2012, 07:14 AM #15
Re: Creating a table
That's nowhere near *all* the basics :)
dbWhy do they call it rush hour when nothing moves? - Robin Williams
- 04-23-2012, 11:35 PM #16
Member
- Join Date
- Mar 2012
- Posts
- 50
- Rep Power
- 0
Re: Creating a table
In the program that I've posted here, definitely not. But this was only a test program for the JTable, since I wasn't able to test it in the real program, as I'm having a few problems with getting it to even show up at all in the real thing. But like I said, that's a subject for another time :)
Similar Threads
-
Creating a Table with user input
By JonniBravo in forum EclipseReplies: 1Last Post: 09-08-2010, 12:50 PM -
Why the web browser needs to refresh first so that creating table may work? Pls help.
By MarkSquall in forum JavaServer Pages (JSP) and JSTLReplies: 2Last Post: 03-29-2010, 11:14 AM -
Need help creating a table
By Knizz in forum SWT / JFaceReplies: 3Last Post: 07-18-2009, 03:46 AM -
Creating a SWT table with 1,000,000 items
By Java Tip in forum SWTReplies: 0Last Post: 07-11-2008, 04:31 PM -
regarding to creating table.....
By daredavil82 in forum New To JavaReplies: 0Last Post: 11-18-2007, 04:55 AM


1Likes
LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks