How do i update a JTable with new data?

Hey
I have a JTable where the data of some football players are shown. Name, club, matches and goals. What i want is to change the data in
the JTable when i click a button. For example each team in a league has its own button, so when i click the teams button, JTable has
data of that teams players.
Here is the code i have atm, there isnt anything on how to change the data, because i dont know where to start, plz point me in somekind of direction:
* To change this template, choose Tools | Templates
* and open the template in the editor.
package test;
import java.awt.*;
import java.awt.event.*;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JMenuBar;
import javax.swing.ImageIcon;
import javax.swing.JTable;
import javax.swing.JButton;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JPanel;
import javax.swing.JFrame;
* @author Jesper
public class Main extends JFrame implements ActionListener {
    private Players players;
    private JTextArea output;
    private JScrollPane scrollPane2;
    private JButton button1, button2;
    private String newline = "\n";
    private int club = 1;
    public Main(){
        players = new Players();
    public JMenuBar createMenuBar(){
        JMenuBar menuBar = new JMenuBar();
        JMenu menu = new JMenu("File");
        menu.setMnemonic(KeyEvent.VK_A);
        menu.getAccessibleContext().setAccessibleDescription("The only menu in this program that has menu items");
        menuBar.add(menu);
        // add menuitems/buttons
        JMenuItem menuItemNew   = new JMenuItem("new");
        menuItemNew.setActionCommand("1");
        menuItemNew.addActionListener(this);       
        JMenuItem menuItemOpen   = new JMenuItem("Open");
        JMenuItem menuItemQuit   = new JMenuItem("Quit");
        menuItemQuit.setActionCommand("2");
        menuItemQuit.addActionListener(this);
        // add to menu
        menu.add(menuItemNew);
        menu.add(menuItemOpen);
        menu.add(menuItemQuit);
        return menuBar;
    public void actionPerformed(ActionEvent e){
        String s;
        if ("Silkeborg IF".equals(e.getActionCommand())){
            club = 1;
            s = e.getActionCommand();
            output.append(s + newline);
            button1.setEnabled(false);
            button2.setEnabled(true);
        } else{
            club = 2;
            s = e.getActionCommand();
            output.append(s + newline);
            button1.setEnabled(true);
            button2.setEnabled(false);
    //Quit the application.
    protected void quit() {
        System.exit(0);
    public Container createContent(){
        JPanel contentPane = new JPanel(new GridLayout(3,1));
        ImageIcon icon = createImageIcon("middle.gif", "a pretty but meaningless splat");
        JTable table = new JTable(players.showPlayers(club));
        //Create the first label.
        button1 = new JButton("Silkeborg IF");
        button1.setToolTipText("Klik her for at se Silkeborg IF");
        button1.addActionListener(this);
        button1.setActionCommand("Silkeborg IF");
        //Create the second label.
        button2 = new JButton("FC Midtjylland");
        button2.setToolTipText("Klik her for at se FC Midtjylland");
        button2.addActionListener(this);
        button2.setActionCommand("FC Midtjylland");
        //Create a scrolled text area.
        output = new JTextArea(5, 30);
        output.setEditable(false);
        scrollPane2 = new JScrollPane(output);
        //Add stuff to contentPane.
        contentPane.add(button1);
        contentPane.add(button2);
        contentPane.add(table);
        contentPane.add(scrollPane2, BorderLayout.CENTER);
        return contentPane;
    protected static ImageIcon createImageIcon(String path,
                                               String description) {
        java.net.URL imgURL = Main.class.getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL, description);
        } else {
            System.err.println("Couldn't find file: " + path);
            return null;
    public static void createGUI(){
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Main main = new Main();
        frame.setJMenuBar(main.createMenuBar());
        frame.setContentPane(main.createContent());
        frame.setSize(500, 500);
        frame.setVisible(true);
     * @param args the command line arguments
    public static void main(String[] args) {
        createGUI();
}

ooohh sorry... i posted the wrong code :S
Here is the correct code:
* To change this template, choose Tools | Templates
* and open the template in the editor.
package test;
import java.util.HashMap;
import java.util.Set;
import javax.swing.table.*;
* @author Jesper
public class Players {
    HashMap<Player, Stats> players;
    public Players(){
        players = new HashMap<Player, Stats>();
        addPlayer();
    public void addPlayer(){
        //Silkeborg IF
        players.put(new Player("Martin ?rnskov", 1), new Stats(19, 3, 1));
        players.put(new Player("Thomas Raun", 1), new Stats(23, 6, 0));
        players.put(new Player("Jimmy Mayasi", 1), new Stats(26, 26, 3));
        players.put(new Player("Lasse J?rgensen", 1), new Stats(33, 0, 0));
        //FC Midtjylland
        players.put(new Player("Frank Kristensen", 2), new Stats(19, 3, 1));
        players.put(new Player("Thomas R?ll", 2), new Stats(23, 6, 0));
        players.put(new Player("Simon Poulsen", 2), new Stats(26, 26, 3));
        players.put(new Player("Magnus Troels", 2), new Stats(33, 0, 0));
    public DefaultTableModel showPlayers(int club){
        String[] columNames = {"Spiller", "Klub", "Kampe", "M?l", "R?de kort"};
        //Object[][] data = {{"Martin ?rnskov", 19, 3, 1}, {"Thomas Raun", 23, 6, 0}};
        Set<Player> keys = players.keySet();
        Object[][] data = new Object[keys.size()][columNames.length];
        int i = 0;
        for(Player player : keys){
           if(player.getClub() == club){
               data[0] = player.getName();
data[i][1] = player.getClub();
data[i][2] = players.get(player).getMatches();
data[i][3] = players.get(player).getGoals();
data[i][4] = players.get(player).getRedCards();
i++;
DefaultTableModel table = new DefaultTableModel(data, columNames);
return table;

Similar Messages

  • New ipad just purchased.  Running on mac os 9, is this possible.  how do i update my computer with new mac os

    I just purchased a new iPad with 3G.  Connected to my mac which was purchased in 2006, all software updated but for some reason the ipad is not connecting to my computer.  Is there an issue?

    From the box the ipad came in and Apples website.
    System Requirements
    Apple ID (required for some features)
    Internet access5
    Syncing with iTunes on a Mac or PC requires:
    Mac: OS X v10.5.8 or later
    PC: Windows 7; Windows Vista; or Windows XP Home or Professional with Service Pack 3 or later"iTunes 10.5 or later (free download from www.itunes.com/download)
    You will have to purchase the install disks from Apple or another retailer.

  • Updating a JPanel with new data, using CardLayout

    Hi,
    I'm using a CardLayout to change between JPanels.
    I have 2 JPanels: panel1, panel2; 2 JButtons: backButton, nextButton;
    I also have 1 JTable - table1 - which get it's info from a database.
    I add nextButton and table1 to panel1, and add backButton to panel2.
    I add panel1 and panel2 to the CardLayout, and of course I add the Cardlayout to the JFrame and so on.
    When I start the application I get the panel1 with a table filled up from the DB. I then press the nextButton and get the panel2 visible.
    Problem:
    My problem now is how to do when I press the backButton so that the application checks the DB and updates the table1.
    I make a ActionListener to the backButton, which makes the panel1 visible again, but it does not update the table1 from the DB.
    How do I do that??
    Thx. for all answers!!
    /bogger

    of course it will be the same - you must call the database again.
    if you just copy and paste the code, that fills your database with data where you make the panel visible again, it'll work
    (of course it will be better to create a method to update the table, not just paste the code)

  • How can I update JTable with new Object[][]

    Hallo, I have got a problem. I want to update my Jtable with new Values,
    with
    setValueAt(Object aValue, int row, int column)
    i can only update one Object.
    Is it possible to update All Objects "Object[][]"??? in a whole Table
    after I clicked a Button???

    Hi,
    AbstractTableModel's method setValueAt(Object aValue, int row, int column)
    is not the way to fill values into a table. It is the way the table returns the changed values to you after the user has entered something. This is a very common misconception, probably because the method names are so confusing.
    The table model uses getValueAt (int row , int column)
    to fill in its rows and columns.
    If you extend AbstractTableModel to make this method fill in the correct values from you data array. then, when you wish to update the whole table, you can
    1) Put new values in the data array
    2) fireTableValuesChanged
    this will cause the table model to call getValueAt for every row and column.
    good luck.

  • Updating graph with new data

    I have a problem updating my graphs with new data in Illustrator. When I update them with new data each month the y and x-axis tend to change font and size.
    What can be the problem? Please help me!

    Hi Rajasekar
    You can purchase the enterprise toolkit fron NI, it includes a "database connectivity toolkit".
    As regards the design pattern to do you you describe, it will depends on the refresh rate you need and the rate at which you want to write your data to the database.
    I would have 2 loops :
     - one acquiring the data and putting it in a queue,
     - and a second that get the data from the queue, logging data to database and refreshing the graph.
    If the write time to database is too long and slows down the graph refresh you place it in another loop.
    Hope this helps
    When my feet touch the ground each morning the devil thinks "bloody hell... He's up again!"

  • I want to update iCloud account with new apple id but don't know password for old apple id.  Plus can no longer receive email at old apple id.  How can I delete the current iCloud account on my iPhone if the previously stated conditions exist?

    I want to update iCloud account with new apple id but don't know password for old apple id.  Plus can no longer receive email at old apple id.  How can I delete the current iCloud account on my iPhone if the previously stated conditions exist?

    If the old ID is yours, and if it is an earlier version of your current ID, go to https://appleid.apple.com, click Manage my Apple ID and sign in with your current iCloud ID.  Click edit next to the primary email account, change it back to your old email address and save the change.  Then edit the name of the account to change it back to your old email address.  You can now use your current password to turn off Find My iDevice, even though it prompts you for the password for your old account ID. Then save any photo stream photos that you wish to keep to your camera roll.  When finished go to Settings>iCloud, tap Delete Account and choose Delete from My iDevice when prompted (your iCloud data will still be in iCloud).  Next, go back to https://appleid.apple.com and change your primary email address and iCloud ID name back to the way it was.  Now you can go to Settings>iCloud and sign in with your current iCloud ID and password.

  • A serious problem with JTable to update with new data.

    I am customizing a JTable. In the table 3 rows and row wise same data presents. After every 30 sec table will be update with new data. But a exception is coming like: ArrayIndexOutofBound 4>=0. Exception is not coming so frequently some time it comes within 1 min or after 1 hour of program running and each time *4>=0* is varies with different number.
    Here is the model i am using and to update table i am calling setTableData( ) with updated vector as a argument.
    public class MyModel extends AbstractTableModel {
              protected Vector m_vector;          
              public MyModel(Vector m_vector) {     this.m_vector = m_vector;     }
              public int getColumnCount() {          
                   return m_vector==null ? 0 : m_vector.size();           
              public int getRowCount() {     return 3;          }
              public String getColumnName(int col) {     return null;     }
              public Object getValueAt(int row, int col) {
                       if (col < 0 || col>=getColumnCount())
                      return null;
                  try{
                  MyData column = (MyData)m_vector.elementAt(col);               
                  switch (row) {
                      case 0: return column.gate;
                      case 1: return column.time;
                      case 2: return column.status;            
                  }}catch(Exception e){
                        System.out.println("Error is here");
                        e.printStackTrace();
                  return null;               
              public Class getColumnClass(int c) {return getValueAt(0, c).getClass();     }
              public boolean isCellEditable(int row, int col) {
                   if (row == 1) { return false; } else { return true; }
              public void setTableData( Vector mData)
                         this.m_vector = new Vector(mData);                    
                         fireTableStructureChanged();
         }Please help me out.

    This is the exception:
    java.lang.ArrayIndexOutOfBoundsException: 4 >= 3
         at java.util.Vector.elementAt(Vector.java:431)
         at javax.swing.table.DefaultTableColumnModel.getColumn(DefaultTableColumnModel.java:277)
         at javax.swing.plaf.basic.BasicTableUI.paintCells(BasicTableUI.java:1047)
         at javax.swing.plaf.basic.BasicTableUI.paint(BasicTableUI.java:974)
         at javax.swing.plaf.ComponentUI.update(ComponentUI.java:142)
         at javax.swing.JComponent.paintComponent(JComponent.java:541)
         at javax.swing.JComponent.paint(JComponent.java:808)
         at javax.swing.JComponent.paintChildren(JComponent.java:647)
         at javax.swing.JComponent.paint(JComponent.java:817)
         at javax.swing.JViewport.paint(JViewport.java:722)
         at javax.swing.JComponent.paintChildren(JComponent.java:647)
         at javax.swing.JComponent.paint(JComponent.java:817)
         at javax.swing.JComponent.paintWithOffscreenBuffer(JComponent.java:4787)
         at javax.swing.JComponent.paintDoubleBuffered(JComponent.java:4740)
         at javax.swing.JComponent._paintImmediately(JComponent.java:4685)
         at javax.swing.JComponent.paintImmediately(JComponent.java:4488)
         at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:410)
         at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:117)
         at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:178)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:454)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:201)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:145)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:137)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:100)and Column may increase/decrease depending upon data retrieved.

  • HT1311 How can I get updates for apps with new Apple ID

    How can I get updates for apps with new Apple ID. I have apps that I got for free, and some that I have purchased. I had to create a new Apple ID because I don't have a credit card now.

    Apps will always be tied to the ID in which they were purchased or downloaded under. You can not change this unless you buy or download the free  app using the new ID.

  • HT4623 When I plug my new iphone 5 into my computer and click on itunes, I get a message that Itunes 10.7 is required on my phone. How do I update my iphone5 with itunes 10.7?

    When I plug my new iphone 5 into my computer and click on itunes, I get a message that Itunes 10.7 is required on my phone. How do I update my iphone5 with itunes 10.7?

    Thanks.  My computer is updated.  When I plug my iphone in, it does not pick up my iphone to sync and gives me the message indicated above.
    I cannot sync my new iphone with my computer.

  • HT4865 i changed my apple id and password but how can i update my iphone with the new apple id and password?

    i changed my apple id and password but how can i update my iphone with the new apple id and password?i changed my apple id and password but how can i update my iphone with the new apple id and password?

    You have to delete the old account, provide the password for the ID when prompted to turn off Find My iPhone, then sign back in with the ID you wish to use.  This deletes the account and your iCloud data from your device, but not from iCloud.  Provided you are signing back into the same account, your iCloud data will reappear on your device when you sign back in.
    To avoid losing photo stream photos that are not in your camera roll, save them to your camera roll before deleting the account (open your my photo stream album, tap Select, tap the photos, tap the share icon -- box with upward facing arrow, then tap Save to Camera Roll).

  • HT1848 MY wife has an Iphone 4  and I have a 5. To date we haev used one apple is/account to manage music purchases. Recently we bought a Mac and created a new apple account for her. How do I synched her phone with new apple account?

    MY wife has an Iphone 4  and I have a 5. To date we have used one apple account to manage music purchases/library. I updated ny phone to the new OS version and all her texting is showing up on my phone.  I understand if i create an apple account for her I will not see her texts. Recently we bought a Mac and created a new apple account for her. How do I synched her phone with new apple account and get access to the music library under my account on the new MAC laptop  before I update her phone to the new OS?
    Going forward if I purchase music under my apple id and want her to have it on her device, how can I acheive that?

    You can continue to share an Apple ID for purchases.
    Sign her in to her new account here:
    Settings > iCloud > Delete Account (Keep on Phone if you want to transfer contacts, calendars, etc...) then sign in with her new ID
    Settings > Messages > Send & Receive > Apple ID > Sign out then in with new
    Settings > FaceTime > Apple ID > Sign out then in with new
    Use the same Apple ID here:
    Settings > iTunes & App Stores > Apple ID

  • How do I create a jtable with horizontalScroll bar,plz help me!

    I created a jtable component,Because my table's columns has 50 items,I must need a horizontalScroll Bar.
    but I find the horizontalScroll don't display,when I add record to the jtable,the verticalScroll Bar is showed.How do I create a jtable with horizontalScroll bar,can u help me!
    thank you in advance!

    Hi,
    This piece of code will help :
         //Get the Component Adapter for taking action against resizing of
    //of Panel
    ComponentListenerAdapter componentAdapter =
    new ComponentListenerAdapter()
    //Get the scrollbar or remove the scrollbar upon resizing
    protected void resizingAction()
    Container tableParent = table.getParent();
    if (tableParent instanceof JViewport)
    //Check if the width of the Table Parent Container
    //is less than the Preferred Size of the Table
    if (tableParent.getSize().getWidth() <
    table.getPreferredSize().getWidth())
    //Yes it is
    //Remove the Auton Resize Function and get the
    //Scrollbar
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF );
    else
    //No it is not
    //Get the Auto Resize functionality back in place
    table.setAutoResizeMode(
    JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);
    //Add the component Adapter to the Table Header
    table.getTableHeader().addComponentListener(componentAdapter);
    private abstract class ComponentListenerAdapter
    implements ComponentListener
              * The <code>componentHidden<code> method has no implementation
              * @param event The Event occured whenever the Component is Hidden
              public void componentHidden(ComponentEvent event)
                   //No Implementaion - Intentially Left Blank
              * The <code>componentShown</code> method has no implementation
              * @param event The Event occured whenever the Component is Shown
              public void componentShown(ComponentEvent event)
                   //No Implementaion - Intentially Left Blank
              * The <code>componentMoved</code> method has no implementation
              * @param event The Event occured whenever the Component is Moved
              public void componentMoved(ComponentEvent event)
                   //No Implementaion - Intentially Left Blank
              * The <code>componentResized</code> method is invoked whenever the
              * component is resized. The resizing action will set the columns and
              * scrollbar to act properly
              * @param event The Event occured whenever the Component is Resized
              public void componentResized(ComponentEvent event)
                   resizingAction();
    * Subclasses of this override this method to determine what is to be
    * done once the Component has been Resized
    protected abstract void resizingAction();
    Hope this will solve all your JTable horizontal resizing problems
    --j                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Ockeim getting problem in imovie & iphoto update.my 1st id is bld,i changed my id but during update it is showing my previous id.please help me how should i update my app by new id.

    im getting problem in imovie & iphoto update.my 1st id is blocked,i changed my id but during update it is showing my previous id.please help me how should i update my app with my new id.

    Contact App Store support. There's a link on the right hand side of the App Store Window. They're the only ones who can sort out account issues.

  • How can I print a JTable with varying sized rows?

    How can I print a JTable with varying sized rows?
    I am using java 1.5, and have made a cell renderer to display multiple lines in rows and it works well, however when I use the new print method it doesn't separate the cells onto the next page, it cuts them and will print the rest of the row on the next page. Does anyone know how I might go about making this happen?
    cheers

    I finally found out the reason, The column heights were being set through my renderer. If I hadn't viewed them in the scrollpane the row heights were set to the default height of 16 therefore when the print method was called it clipped all the rows wrong, what is weird though is that the row height printed out correctly but the clipping area was set wrong because it was getting the default value of 16 from rowHeight(row).

  • How do I create a JTable with some empty cells in it?

    I have a three column JTable. The first column is a String showing description. The second column contains numbers (double) and the third column also contains numbers. In some cases not all cells in a row should contain data. So for instance, I could have row one showing only description (a String in the first column), and then row two showing description (a String in the first column) and a number (a double in the second column) in columns one and two respectively. My problem is that, the data gets copied from the cells with data to the cells which are supposed to be empty. So, how do I create a JTable with some empty cells in it.

    I have tried empty strings for those values, but it did not work. My table puts objects in an arraylist called reconciliation. The arraylist takes different objects with the same super class. The code below explains. Are you suggesting I pass null to my constructor?
    JTable table = new JTable(new ReconTableModel());The method below is from the table model
    protected  List<Reconciliation> reconciliation = new ArrayList<Reconciliation>();
    protected void fillModel(){
          reconciliation.add(new CashBook("Cash Book Report"," "," "));
          reconciliation.add(new CheckingBankAccount("Checking Bank Account"," "," "));
          reconciliation.add(new BankBalance("Bank Balance As Per Bank Statement",500," "));
          reconciliation.add(new PaymentVouchers("Payment Voucher Receipt",300," "));
          reconciliation.add(new DepositVoucher("Deposit Voucher Receipt",1000," "));
          reconciliation.add(new ReconciledBalance("Reconcilied Bank Balance",1200," "));
          reconciliation.add(new BalanceAt("Bank Balance At",800," "));
          reconciliation.add(new Difference("Difference",400," "));
          Collections.sort( reconciliation, new Comparator<Reconciliation>(){
          public int compare( Reconciliation a, Reconciliation b) {
            return a.getTransactionName().compareTo( b.getTransactionName());
      }

Maybe you are looking for

  • Problems printing to HP Color LaserJet 2605dn

    First, the technical details. The 2605dn is running firmware datecode 20061114. My Macs are running 10.4.10, and the computers and the printer are all connected to a Linksys BEFSR41 router. I also have a Windows XP laptop that is connected to the rou

  • ADFapplication stops working after few days of uptime : invalidobjname

    We are currently doing uptime testing of our prodcut. We are using JDEVADF_11.1.1.7.0_GENERIC_130226.1400.6493. After 3 days uptime our application stops working and we are seeing following errors in the log :- oracle.jbo.InvalidObjNameException: JBO

  • Siebel 8.1.1.11 on Windows 2008 32-bit

    Dear All, We are planning to upgrade from 8.1.1.5 to 8.1.1.11 and currently on Windows 2008 32-bit. Will Siebel 8.1.1.11 work on Windows 2008 32-bit for the SES, SWSE, etc? The "Certifications" tab does not indicate Microsoft Windows 2008 32-bit as a

  • Quartz Composer Visualizer crashes.

    Hi, I'm a great fan of Quartz Composer, and would like to start playing with multiple screen composition. I can successfully run a composition fullscreen on my own mac with QC visualizer. However, whenever I try to start one of my compositions in Qua

  • 2007 2.8 GHz iMac slowing down...

    For the past week or so, my late 2007 2.8 GHz Core 2 Duo iMac has been getting slower and slower. It gets to the point where opening a simple menu bar item takes a full second, and opening a simple app like System Preferences can take five or ten sec