Results 1 to 12 of 12
  1. #1
    Berzerk is offline Member
    Join Date
    Jun 2010
    Posts
    7
    Rep Power
    0

    Default Displaying Multiple Tables based on Input

    I've read over the tutorial, quite a few times but I'm still having problems with displaying different tables based on input.

    For my assignment, we are given the task to create a program that keeps a track of a Hockey League and all of it statistics, team statistics, player statistics and that business. My group has decided to use tables as the way in which the user will input team and player information, and to use tables to output whatever the user desires.

    So, for one of the tables, there is a "Output League" option that will output all of the teams in the league in terms of points. There is a "Output Division", "Output Team" [which outputs players based on points] I want to try and keep everything as methods [probably my downfall :(]. But anyway, I have used the code from the above tutorial as a guide and my table array for the "Output League" option and it looks like [I have already combined all the teams in the division as a single array, and have sorted them according to points already].

    Java Code:
       String[] columnNames = {"Team Name",
    	      "Standing",
    	      "Points",
    	      "Wins",
    	      "Ties",
    	      "Losses",
    	      "Games Played",
    	      "Goals For",
    	      "Goals Against" 
    	      "Difference",};
    
      Object[][] data = new Object[league.length][10];
    	        
         for (int b = 0; b<league.length; b++) {
              for (int c = 0; c<10; c++) {
    	      if (c == 0) 
    	        	data[b][c] = league[b].getTeamName();
    	      if (c == 1) 
    	        	data[b][c] = league[b].getStanding();
    	      if (c == 2) 
    	        	data[b][c] = league[b].getPoints();
    	      if (c == 3) 
    	        	data[b][c] = league[b].getWins();
    	      if (c == 4) 
    	        	data[b][c] = league[b].getTies();
    	      if (c == 5) 
    	        	data[b][c] = league[b].getLosses();
    	      if (c == 6) 
    	        	data[b][c] = league[b].getGamesPlayed();
    	      if (c == 7) 
    	           	data[b][c] = league[b].getGoalsFor();
    	      if (c == 8) 
    	        	data[b][c] = league[b].getGoalsAgainst();
    	      if (c == 9) 
    	        	data[b][c] = league[b].getDifference();  
               }
         }
    Now, the array league refers to a parameter that I wish to send in as the array that the table will output, however I have tried everything my mind can think of and it never comes out right. So, ultimately, my question is how would I implement sending in a parameter [and to which methods and in this example, the array "league"]. Again, I used the code from the tutorial, more specifically the "TableDemo.java" one. I also want for fields to be edited through charts, so if there is anything that I need to modify, then please say.

    If anyone wants a copy of my program thus far, I can email it to you [because it's a couple of classes]. Anyway, if anyone is willing to help, all I ask for is a sort of skeleton on how my table methods would look like, and what I would need to do to not only run the table I want, but also to send in the parameter.

    Any help and direction would be greatly appreciated.

  2. #2
    tim's Avatar
    tim
    tim is offline Senior Member
    Join Date
    Dec 2007
    Posts
    435
    Rep Power
    7

    Default JTable example

    Welcome to Java Forums Berzerk. :D

    I've created an example for you based on your Hockey League assignment. Tables in Java were designed with the model-view-controller architecture. The control and view parts are implemented by default, and you can implement your own if you wanted to. The DefaultTableModel class is available, but since you want to edit your data, it's better to extend from the AbstractTableModel class. An example of an implementation of this model:
    Java Code:
    package example;
    
    import javax.swing.table.*;
    
    public class LeagueModel extends AbstractTableModel {
        protected League[] leagues = null;
        protected final String[] columnNames = new String[] {
            "Team Name",
            "Standing",
            "Points",
            "Wins",
            "Ties",
            "Losses",
            "Games Played",
            "Goals For",
            "Goals Against",
            "Difference"};
        public static final int TEAM_NAME = 0;
        public static final int STANDING = 1;
        public static final int POINTS = 2;
        public static final int WINS = 3;
        public static final int TIES = 4;
        public static final int LOSSES = 5;
        public static final int GAMES_PLAYED = 6;
        public static final int GOALS_FOR = 7;
        public static final int GOALS_AGAINST = 8;
        public static final int DIFFERENCE = 9;
        
        public int getRowCount() {
            return leagues.length;
        }
        
        public int getColumnCount() {
            return 10;
        }
        
        public String getColumnName(int columnIndex) {
            return columnNames[columnIndex];
        }
        
        public Class<?> getColumnClass(int columnIndex) {
            // The default cell renderer only supports Object.class and Number.class
            return Object.class;
        }
        
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return true;
        }
        
        
        public Object getValueAt(int rowIndex, int columnIndex) {
            League league = leagues[rowIndex];
            switch(columnIndex){
                case TEAM_NAME:
                    return league.getTeamName();
                case STANDING:
                    return league.getStanding();
                case POINTS:
                    return league.getPoints();
                case WINS:
                    return league.getWins();
                case TIES:
                    return league.getTies();
                case LOSSES:
                    return league.getLosses();
                case GAMES_PLAYED:
                    return league.getGamesPlayed();
                case GOALS_FOR:
                    return league.getGoalsFor();
                case GOALS_AGAINST:
                    return league.getGoalsAgainst();
                case DIFFERENCE:
                    return league.getDifference();
            }
            return "null";
        }
        
        public void setValueAt(Object value, int rowIndex, int columnIndex) {
            League league = leagues[rowIndex];
            switch(columnIndex){
                case TEAM_NAME:
                    league.setTeamName(value.toString());
                    break;
                case STANDING:
                    league.setStanding(value.toString());
                    break;
                case POINTS:
                    league.setPoints(Integer.parseInt(value.toString()));
                    break;
                case WINS:
                    league.setWins(Integer.parseInt(value.toString()));
                    break;
                case TIES:
                    league.setTies(Integer.parseInt(value.toString()));
                    break;
                case LOSSES:
                    league.setLosses(Integer.parseInt(value.toString()));
                    break;
                case GAMES_PLAYED:
                    league.setGamesPlayed(Integer.parseInt(value.toString()));
                    break;
                case GOALS_FOR:
                    league.setGoalsFor(Integer.parseInt(value.toString()));
                    break;
                case GOALS_AGAINST:
                    league.setGoalsAgainst(Integer.parseInt(value.toString()));
                    break;
                case DIFFERENCE:
                    league.setDifference(Integer.parseInt(value.toString()));
                    break;
            }
        }
        
        public LeagueModel(League[] leagues) {
            this.leagues = leagues;
        }
        
    }
    It's important to notice the getColumnClass() method. This is where typical null pointer exceptions crop in. To add your table to a JFrame:
    Java Code:
    package example;
    
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.*;
    
    public class Main extends JFrame {
        protected JTable table = null;
        protected League[] leagues = new League[] {new League("Legendary League"), new League("Furious Felines"), new League("Java Junkies")};
        
        public Main() {
            super("Table example");
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            setLocationByPlatform(true);
            table = new JTable();
            table.setModel(new LeagueModel(leagues));
            getContentPane().add(BorderLayout.CENTER, new JScrollPane(table)); // the scroll pane is required to get the column headers
            pack();
            setVisible(true);
        }
        
        
        
        public static void main(String[] args) {
            new Main();
        }
    }
    Note the JScrollPane component. The scroll pane is required to add column headers. I'm not sure how to add them otherwise. Maybe someone can clear this up? ;) Also, notice the use of constants to index to field names. It's easier to read for this problem, but I would recommend a more dynamic approach. This code is not very maintainable.

    Good luck with your assignment Berzerk :p
    Tim
    Eyes dwelling into the past are blind to what lies in the future. Step carefully.

  3. #3
    Berzerk is offline Member
    Join Date
    Jun 2010
    Posts
    7
    Rep Power
    0

    Default

    Awesome! Thank you so much Tim! For the welcome and thank you for the example! You have no idea how greatly you've helped me ;P. I can easily adapt the code now, and all of the fragmented understanding of tables just got soldered together by you, ;D. The constants to index to field names was also something I thought about, probably does make it better suited instead of using a for loop ;P. I now understand how I should structure my program.

    Again, thank you in every single possible language [be it real world or programming ;P].

    [My name is probably really unprofessional ;D]

  4. #4
    Berzerk is offline Member
    Join Date
    Jun 2010
    Posts
    7
    Rep Power
    0

    Default

    So, another problem. I've run into a problem with sending in parameters, because the way I have my program set up is that there's a menu (to add teams, players and for output) that I output through a console. When they select "output", and they select "league", nothing happens :(.

    I made my League Output model, and it looks exactly like it does on the Sun Tutorial on JTables, and I've mixed in Tim's code where it applied. I was wondering, say, if I wanted to run the chart, how would I go about doing it?

    This is my class definition for my LeagueOutput

    Java Code:
    import java.awt.Dimension;
    import java.awt.GridLayout;
    
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    
    public class LeagueOutput extends JPanel {
    	private boolean DEBUG = false;
    	
    	public LeagueOutput(Team[] teams) {
    		super(new GridLayout(1,0));
    
    	    	JTable table = new JTable(new LeagueOutputModel());
    	        table.setPreferredScrollableViewportSize(new Dimension(500, 70));
    	        table.setFillsViewportHeight(true);
    	        
    	        JScrollPane scrollPane = new JScrollPane(table);
    	        
    	        add(scrollPane);
    	    }
    	
    	class LeagueOutputModel extends AbstractTableModel {
    					
    	    protected Team[] leagues = null;
    	    protected final String[] columnNames = new String[] {
    	        "Team Name",
    	        "Standing",
    	        "Points",
    	        "Wins",
    	        "Ties",
    	        "Losses",
    	        "Games Played",
    	        "Goals For",
    	        "Goals Against",
    	        "Difference"};
    	    public static final int TEAM_NAME = 0;
    	    public static final int STANDING = 1;
    	    public static final int POINTS = 2;
    	    public static final int WINS = 3;
    	    public static final int TIES = 4;
    	    public static final int LOSSES = 5;
    	    public static final int GAMES_PLAYED = 6;
    	    public static final int GOALS_FOR = 7;
    	    public static final int GOALS_AGAINST = 8;
    	    public static final int DIFFERENCE = 9;
    	    
    	    public int getRowCount() {
    	        return leagues.length;
    	    }
    	    
    	    public int getColumnCount() {
    	        return 10;
    	    }
    	    
    	    public String getColumnName(int columnIndex) {
    	        return columnNames[columnIndex];
    	    }
    	    
    	    public Class<?> getColumnClass(int columnIndex) {
    	        // The default cell renderer only supports Object.class and Number.class
    	        return Object.class;
    	    }
    	    
    	    public boolean isCellEditable(int rowIndex, int columnIndex) {
    	        return true;
    	    }						
    		
    	    public Object getValueAt(int rowIndex, int columnIndex) {
    	        Team league = leagues[rowIndex];
    	        switch(columnIndex){
    	            case TEAM_NAME:
    	                return league.getTeamName();
    	            case STANDING:
    	                return league.getStanding();
    	            case POINTS:
    	                return league.getPoints();
    	            case WINS:
    	                return league.getWins();
    	            case TIES:
    	                return league.getTies();
    	            case LOSSES:
    	                return league.getLosses();
    	            case GAMES_PLAYED:
    	                return league.getGamesPlayed();
    	            case GOALS_FOR:
    	                return league.getGoalsFor();
    	            case GOALS_AGAINST:
    	                return league.getGoalsAgainst();
    	            case DIFFERENCE:
    	                return league.getDifference();
    	        }
    	        return "null";
    	    }  
    	}
    
    	static void createAndShowGUILeague(Team[] teams) {
    		//Create and set up the window.
    		JFrame frame = new JFrame("Teams In League");
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    		//Create and set up the content pane.
    		LeagueOutput newContentPane = new LeagueOutput(teams);
    		newContentPane.setOpaque(true); //content panes must be opaque
        	frame.setContentPane(newContentPane);
    
        	//Display the window.
        	frame.pack();
        	frame.setVisible(true);
    	}
    	
        public static void StartLeagueOutput(final Team[] teams) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUILeague(teams);
                }
            });
        }
    	
    }
    And this is how I called the class in another method

    Java Code:
    teams = TeamCombiner(a);
    new LeagueOutput(teams);
    When I select the option "Output League", nothing happens. If anyone wants me to post all of the files associated with the package, I'll gladly put them up. Maybe I'm more confused than I thought I was ;P. What "TeamCombiner" does is that it sends "a" which is a League, and combines all of the teams in both divisions (east and west) into a single array. And then bubble sorts through them with regard to points, then returning it.

    Is it a mistake on my part or is it impossible to do?

    Any help would be appreciated.

  5. #5
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    You can always create a Jar file that includes source, change the extension from Jar to zip and upload it here if desired. Much luck!

  6. #6
    Berzerk is offline Member
    Join Date
    Jun 2010
    Posts
    7
    Rep Power
    0

    Default

    I think I exported it correctly HBHL.zip
    Last edited by Berzerk; 06-16-2010 at 04:05 AM.

  7. #7
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    um,... you didn't have the jar/zip file include the source java files, only the class files, so there's little we can do with this zip file. Sorry.

  8. #8
    Berzerk is offline Member
    Join Date
    Jun 2010
    Posts
    7
    Rep Power
    0

    Default

    Hmm, sorry, they are now in .java format.

  9. #9
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    You seem to be trying to combine a console program and a Swing GUI program. If so, I advise against this and either sticking with one or the other.

  10. #10
    Berzerk is offline Member
    Join Date
    Jun 2010
    Posts
    7
    Rep Power
    0

    Default

    Hmm, so it's as I thought. Is there any way for them to be combined? And by that I mean, a console that outputs charts within the console, or a table that with console-like ability?

  11. #11
    curmudgeon is offline Senior Member
    Join Date
    May 2010
    Posts
    436
    Rep Power
    5

    Default

    If you needed to display a JTable from within a console app, then one way to do it is to create the JTable and display it in a JOptionPane. This way you'll halt the console thread until the JOptionPane has been dealt with. But to just show data in a tabular format, in a console program, I'd much prefer using printf and formatting my output nicely with that. Otherwise, another option is to consider creating a Swing GUI app from the get-go.

  12. #12
    Berzerk is offline Member
    Join Date
    Jun 2010
    Posts
    7
    Rep Power
    0

    Default

    Well, thank you all for helping me.

    Tim, I have no idea how to thank you enough for helping me out. The program is done yay! And it does mix in both console and tables, it gets user inputted data on what they want to see, and the table runs. Everything is all fine and dandy, the editing values, all of it :D.

    Thank you guys again!

Similar Threads

  1. Replies: 0
    Last Post: 11-28-2009, 03:37 AM
  2. Replies: 3
    Last Post: 10-28-2009, 01:45 AM
  3. Replies: 3
    Last Post: 10-12-2009, 02:03 PM
  4. displaying tables in joptionpane
    By kaemonsaionji in forum New To Java
    Replies: 2
    Last Post: 02-26-2009, 06:53 AM
  5. Reading data from csv file based on specific input
    By jaiminparikh in forum Advanced Java
    Replies: 14
    Last Post: 02-13-2009, 09:07 PM

Posting Permissions

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