Results 1 to 16 of 16
Like Tree1Likes
  • 1 Post By KevinWorkman

Thread: Creating a table

  1. #1
    Mate de Vita is offline Member
    Join Date
    Mar 2012
    Posts
    63
    Rep Power
    0

    Default 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?

  2. #2
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,969
    Rep Power
    8

    Default 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!

  3. #3
    Bushman is offline Member
    Join Date
    Apr 2012
    Location
    Spainish TOwn
    Posts
    25
    Rep Power
    0

    Default Re: Creating a table

    Quote Originally Posted by Mate de Vita View Post
    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?

    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
    PHP 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
    VARIABLES
    PHP 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.
    TABLE SETUP
    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 );

  4. #4
    Mate de Vita is offline Member
    Join Date
    Mar 2012
    Posts
    63
    Rep Power
    0

    Default 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:
    Java Code:
    model = new DefaultTableModel ( tableData, columnHeaders )
    {
         public class getColumnClass ( int column_index )
         {
    Is this really allowed? Defining a method that returns a class, not an object or primitive?

  5. #5
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,969
    Rep Power
    8

    Default 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.
    Fubarable likes this.
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  6. #6
    Mate de Vita is offline Member
    Join Date
    Mar 2012
    Posts
    63
    Rep Power
    0

    Default 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:
    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;
            }
        }
    }
    What am I doing wrong?

  7. #7
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,298
    Rep Power
    20

    Default 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.

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

  8. #8
    Mate de Vita is offline Member
    Join Date
    Mar 2012
    Posts
    63
    Rep Power
    0

    Default Re: Creating a table

    Quote Originally Posted by DarrylBurke View Post
    Describe 'not working'
    It displays the ImageIcon description strings (Wood, Clay and Iron), instead of the images.

    Quote Originally Posted by DarrylBurke View Post
    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.
    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.

    Quote Originally Posted by DarrylBurke View Post
    I fail to understand why you want to use a GridLayout to display a JTable and its header.
    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.

  9. #9
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,298
    Rep Power
    20

    Default 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:
    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);
                }
            });
        }
    If you want the header to contain ImageIcons as values, you will need to set them separately. e.g.
    Java Code:
    table.getTableHeader().getColumnModel().getColumn(0).setHeaderValue(new ImageIcon("C:/Path/Image1.png", "Wood"));
    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.

    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.

    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.
    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)

    db
    Last edited by DarrylBurke; 04-20-2012 at 09:36 PM.
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  10. #10
    Bushman is offline Member
    Join Date
    Apr 2012
    Location
    Spainish TOwn
    Posts
    25
    Rep Power
    0

    Default Re: Creating a table

    Quote Originally Posted by KevinWorkman View Post
    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.
    What I'm doing there is extending the table model there. I have written a complex table class whose table system is setup just as the code I typed you above...and it works flawlessly.
    It is a very robust way to establish and define your table.

  11. #11
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,298
    Rep Power
    20

    Default Re: Creating a table

    If you're going to make sweeping claims like that, you need to be more careful about the code you post. This is from your response at #3.
    Quote Originally Posted by Bushman View Post
    PHP Code:
    model.insertRow ( int index, new Object [ ] { "a string", "a string", "a string", new ImageIcon ( "your picture.png" ) } );
    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  12. #12
    Mate de Vita is offline Member
    Join Date
    Mar 2012
    Posts
    63
    Rep Power
    0

    Default Re: Creating a table

    Quote Originally Posted by DarrylBurke View Post
    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.

    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.
    I've done so now, and the images show up properly now. This is my program:

    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;
            }
        }
    }
    Is this OK now or is there still anything that I should fix/change/be careful about?
    Last edited by Mate de Vita; 04-21-2012 at 05:58 PM.

  13. #13
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,298
    Rep Power
    20

    Default 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.
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  14. #14
    Mate de Vita is offline Member
    Join Date
    Mar 2012
    Posts
    63
    Rep Power
    0

    Default 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.

  15. #15
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,298
    Rep Power
    20

    Default Re: Creating a table

    That's nowhere near *all* the basics :)

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

  16. #16
    Mate de Vita is offline Member
    Join Date
    Mar 2012
    Posts
    63
    Rep Power
    0

    Default 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

  1. Creating a Table with user input
    By JonniBravo in forum Eclipse
    Replies: 1
    Last Post: 09-08-2010, 12:50 PM
  2. Why the web browser needs to refresh first so that creating table may work? Pls help.
    By MarkSquall in forum JavaServer Pages (JSP) and JSTL
    Replies: 2
    Last Post: 03-29-2010, 11:14 AM
  3. Need help creating a table
    By Knizz in forum SWT / JFace
    Replies: 3
    Last Post: 07-18-2009, 03:46 AM
  4. Creating a SWT table with 1,000,000 items
    By Java Tip in forum SWT Tips
    Replies: 0
    Last Post: 07-11-2008, 04:31 PM
  5. regarding to creating table.....
    By daredavil82 in forum New To Java
    Replies: 0
    Last Post: 11-18-2007, 04:55 AM

Posting Permissions

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