Jtable + listbox + Date

1)We're using a Jtable to make a reservation and when a user clicks on a square in the Jtable(grid), he should get a form to fill in and afterwards his name will be filled in to the selected square in the Jtable(grid). Does anybody know the code to do this?
This Jtable(grid) opens in a separate window and we'd like it to open in the regular window, how can we do this?
2)Does anybody know how you can change the date. f.e. I want to change the current date into the date of the last week when I push on a button. I don't know how??
3)What is the code to make a listbox which uses the data in an access database?
Could we get this in regular java code, not javascript, thanks!

You won't get much JavaScript round here anyway!
That's quite a lot of questions you've got there.
1) This would depend partly on how you're storing the data for the cells. However, to get a window to pop up when you click on a cell you need to write a custom TableCellEditor. There's an example of how to do this in the Swing section of the Java Tutorial. Your custom editor should simply create a new modal dialog and retrieve the values from it once it is closed.
2) To manipulate dates you need to use the Calendar class. For example, to change a date back a week you'd do something like this:
Calendar calendar = calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY, -7); // go back seven days
Date newDate = calendar.getTime();3) If you're able to connect to your access database then it will be as simple as writing an SQL query for it and reading the values back in to a JList.
Connection conn = null;
Statement stmt = null;
try
  conn = DriverManager.getConnection("jdbc:odbc:MyDataSource");
  stmt = conn.createStatement();
  ResultSet rs = stmt.executeQuery("SELECT name FROM my_table ORDER BY name");
  list.removeAllItems();
  while(rs.next())
    list.addItem(rs.getString(1));
finally
  // close statement and connection
}The example I've given here assumes you've set your Access database up as an ODBC datasource called "MyDataSource".
Have a look in the JDBC forums for more examples of how to connect to Access and read data back.
Hope this helps.

Similar Messages

  • Save JTable's data

    hello,
    Can i save the JTable's data in binary and reload them?
    give me some suggestions please
    Now i save the JTable's data as txt format,but i want to save a password's MD5 result before them(its format is binary).i want to save them in one format,how can i do?
    thank u for your help

    I don't understand what's the problem.
    Java can do binary file I/O.
    Any DB supports binary data type.
    So .....

  • Regarding Array to Multicolumn Listbox data's manipulation

    Hi  - I want to display the above mentioned array in muticolumn listbox with 2 columns , first column needs to be belongs to array [0] (Date and time ) and second column needs to be belongs to array [1] and array [2] ( Cone and Vane strings).
    I have tried to implement the same, please go through the attached VI and I cannot make the above mentioned array data's into two column multi column listbox data's (that is , can't able to display the array [1] and array [2] data's in single column.
    Please let me know the solution to resolve this as soon as possible.
    Thanks and Regards,
    Dinesh
    Attachments:
    Cone and Vane Operations_Final.vi ‏60 KB

    Well, your VI is a complete mess and has several CPU burner loops that run as fast as the computer allows. There is also a lot of duplicate and overly complex code. Programmed correctly, code with all this functionality could probably fit on a postcard.
    Anyway, for just building the multicolumn listbox, here's somewhat simpler code. Hopefully you can adapt it to your problem.
    Note that you probably want to add only one row at a time, and you only want to add to the listbox and save to the file when new data arrives and not millions of times per second. Try a queue, for example.
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    Cone&Vane.vi ‏8 KB

  • Hi, i'm having trouble in filling a jtable with data

    hi, i'm having trouble in filling a jtable with data, but the real problem is that i have stablished a JDBC connection throught the windowsxp ODBC to my database written on microsoft access platform, so i created my table
    public CenterPanel(){
    panel = new JPanel();
    dataTable = new JTable(10,10);
    dataTable.setBorder(BorderFactory.createLineBorder(Color.black,2));
    panel.add(dataTable);
    setLayout(new BorderLayout());
    add(panel,BorderLayout.CENTER);
    i can see the table on my driver, but i want to fill it by connecting to the database and fil the fields from the database, i have the code to connect and retrieve the fields but on the dos, i want to fill them in the table,
    the code for accessing is
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
         Connection conn1 = DriverManager.getConnection      ("jdbc:odbc:EHLAN",
                             "marius","svasdiga");
                   Statement stmt1 = conn1.createStatement();
                   Statement stmt2 = conn1.createStatement();
                   ResultSet rs1 = stmt1.executeQuery ("select * from Appartment");
                   System.out.println("App. Num, Stair Num, Elec. Num");
              while (rs1.next()) {
                   System.out.print (rs1.getInt ("appnum") + ","+" ");
                   System.out.print (rs1.getString ("staircase") + ","+" ");
                   System.out.println (rs1.getInt("electrnum") );
    ResultSet rs2 = stmt2.executeQuery ("select * from Person");
    System.out.println("First Name, Last Name, Blood Type");
              while (rs2.next()) {
                   System.out.print (rs2.getString ("namef") + ","+" ");
                   System.out.print (rs2.getString ("namel") + ","+" ");
                   System.out.println (rs2.getString("bloodType") );
    so help me to fill this data to the table. thank you
    yours sincerely,
    marius ajemian

    hi, i'm having trouble in filling a jtable with data, but the real problem is that i have stablished a JDBC connection throught the windowsxp ODBC to my database written on microsoft access platform, so i created my table
    public CenterPanel(){
    panel = new JPanel();
    dataTable = new JTable(10,10);
    dataTable.setBorder(BorderFactory.createLineBorder(Color.black,2));
    panel.add(dataTable);
    setLayout(new BorderLayout());
    add(panel,BorderLayout.CENTER);
    i can see the table on my driver, but i want to fill it by connecting to the database and fil the fields from the database, i have the code to connect and retrieve the fields but on the dos, i want to fill them in the table,
    the code for accessing is
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
         Connection conn1 = DriverManager.getConnection      ("jdbc:odbc:EHLAN",
                             "marius","svasdiga");
                   Statement stmt1 = conn1.createStatement();
                   Statement stmt2 = conn1.createStatement();
                   ResultSet rs1 = stmt1.executeQuery ("select * from Appartment");
                   System.out.println("App. Num, Stair Num, Elec. Num");
              while (rs1.next()) {
                   System.out.print (rs1.getInt ("appnum") + ","+" ");
                   System.out.print (rs1.getString ("staircase") + ","+" ");
                   System.out.println (rs1.getInt("electrnum") );
    ResultSet rs2 = stmt2.executeQuery ("select * from Person");
    System.out.println("First Name, Last Name, Blood Type");
              while (rs2.next()) {
                   System.out.print (rs2.getString ("namef") + ","+" ");
                   System.out.print (rs2.getString ("namel") + ","+" ");
                   System.out.println (rs2.getString("bloodType") );
    so help me to fill this data to the table. thank you
    yours sincerely,
    marius ajemian

  • JTable edited data doesn't appear in the same time

    Hi
    i have aserious problem JTable edited data doesn't appear in the same time imust tom minimize the frame and maximize it to see the table modified what is the reason?

    Quit multi-posting the same question every time. You asked this same question 3 hours ago:
    http://forum.java.sun.com/thread.jspa?threadID=729894
    The last time you posted the same question within two minutes of one another:
    http://forum.java.sun.com/thread.jspa?threadID=729202
    http://forum.java.sun.com/thread.jspa?threadID=729200
    Not only that, you never bother to reply to your postings to indicate whether the advice given was helpfully or not. This is commonly known as thanking people for the time spent helping your.
    Learn to use the forum correctly or you will be on your own in the future.

  • Refresh data in a jtable when data changes

    I have a jtable grdTable and a tableModel mytableModel which extend abstract table model
    I have a jcheckbox in the column 1 which i want to uncheck all
    I am doing the following.The data is changed ,I could see by doing susyem.out.println() but the data in the table does not refreshes.
    public void showTablechanges()
    TableModel tm = grdTable.getModel;
    for(int i=0 ;i<grdTable.getRowCount();i++)
    grdTable.setValueAt(Boolean.FALSE, i, 1);
    ( (MyTableModel)tm).fireTableDataChanged();
    grdTable.repaint();
    What am i missing or what wrong I am doing.How can i make the data refresh.
    I tried do a sys out after seting the value and it is showing as false but the checkbox is still checked.I have tried a lot of things but I am not able to refresh the jtable.
    Please please help.
    Thanks

    Thanks so much for the reply I read the links.I modified my code as
    public void showTablechanges() {
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    TableModel tm = grdTable.getModel;
    for (int i = 0; i < grdTable.getRowCount(); i++) {
    grdTable.setValueAt(Boolean.FALSE, i, 1);
    ((MyTableModel) tm).fireTableDataChanged();
    grdTable.repaint();
    This makes no difference.What strange thing is happening out of 12 checkboxes ,11 are unchecked but the first one always remains checked.EVen without the
    invoke later 11 are unchecked and 1 remains checked
    This method is in a panel and this panel is invoked from another MAin panel which has a changelistener for this panel.
    i.e if the method above is in myPanel.java then in my main panel,I have
    myPanel.addChangeListener(this)
    Also if i remove the line
    ((MyTableModel) tm).fireTableDataChanged();
    All checkboxes remains checked.
    I am really confused and this looks very tough to me ,Can you find out what is wrong
    Thanks,

  • JTable cell data alignment ..Emergency

    Hello,
    I have created a table using a JTable. I want to align some columns data right, and some left and some columns center. How do I go about to do this. If i add textfields on this table ..then all the stuff goes smooth but in case of simple TableColumns alighnment dont work
    for(int index=0;index<columnNames.length;index++)
    TableColumn column = table.getColumnModel().getColumn(index);
    Component component =table.getDefaultRenderer(table.getColumnClass(index)). getTableCellRendererComponent( table, data[index],false, false, 0, index);
    if i cast component to textField then i found Method name textField.setHorizontalAlignment(SwingConstants.RIGHT);
    but if i hav simple JTable then i dont found any method setHorizontalAlignment(SwingConstants.RIGHT);
    Can you please help me.
    Thanks in advance

    Overrider getColumnClass() in your table model such that you return the class of the data in that column. For java.lang.Number derivatives, JTable will right justify those for you.

  • Two dimension in JTable and date.

    Hi,
    Can anyone show me or teach me how to create two dimension in JTable.
    The column is time ie 12pm-1pm, 1pm-2pm.......3am-4am, and the row is monday, tuesday .....sunday.And row should consists of day and date ie monday 1/4,tuesday 2/4.....sunday 8/4.
    Thanks for any help.

    Hi,
    You cannot automatically filter members using a mapping based on the smart list. To do that work, i recommend using an UDA (User Defined Attribute) or create an attribute dimension associated to your employee dimension.
    Regards,
    David Mendele
    BI / EPM Project manager at Business & Decision
    Lima, Peru

  • JTable, verifying data before changing cell value

    I am trying to trap erroneous dataentry into a JTable. I have some fields which are populated by objects which are a subclass of Number. My original though was to trap the data entry at the setValueAt method and verify it there; however, if I enter alpha characters into the cell, it never gets to setValueAt. Any ideas?

    The easy fix was to short circuit getColumnClass to return the class of string. The constructor doesn't bomb and I can trap it at the setValueAt() method in my table model.
    This is a database application which displays information from a three table join. I have written methods to set all of the master values to the editted values.
    Basic idea is to create Hashmaps keyed off of the unique keys for each row of each master table. A vector is placed in a hashmap for each unique key. Each row with that key is then placed in the vector. If a cell from a master is updated, it is easy to grab the key, then grab the vector of all of the rows with that key in it, and update all of the associated rows.
    Not sure if anyone else will find it useful, but here it is.
    package com.cessna.ewt.bay;
    import com.cessna.ewt.util.WeightNumber;
    import com.cessna.ewt.util.WeightEmployee;
    import java.awt.Toolkit ;
    import java.util.Vector;
    import javax.swing.JLabel ;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.JOptionPane;
    import java.awt.Color;
    import java.util.HashMap;
    * Table Model for the Bay application
    public class BayTableModel extends AbstractTableModel{
    public BayTableModel(WeightEmployee nUser) {
    this(); user = nUser;
    public BayTableModel()
    {    super();
    changed = false;
    data = new Vector();
    for (int iloop = 0; iloop < 20; iloop++) {
         data.add(new BayRecord());     }
    public BayTableModel(Vector nData) {
    super();
    changed = false;
    data = nData;
    public int getColumnCount() {    
    return BayRecord.VISABLE_COLUMN_COUNT ;
    public int getRowCount() {    
    return data.size();
    public int getPreferredColumnWidth(int col) {
    return COLUMN_WIDTH[col];
    public Object getValueAt(int row, int col) {
    BayRecord dataRecord = (BayRecord) data.get(row);
    return dataRecord.get(col);
    }public String getColumnName(int column) {
    return BayRecord.COLUMN_NAMES[column];
    public Class getColumnClass(int c) {
    if(c == BayRecord.FS) {
    System.out.println("DEBUG: GET COLUMN CLASS FOR FS");
    return BayRecord.getColumnClass(c);
    public boolean isCellEditable(int row, int col) {
    if (user != null) {
    if (user.canApprove()) {
    //System.out.println(user + " can approve.");
    return true;
    //System.out.println(user + " can not approve.");
    return false;
    public Color getNonEditableBackground(int col) {
    return Color.lightGray;
    public Color getEditableBackground(int col) {
    return Color.white;
    public void setUser(WeightEmployee nUser) {
    user = nUser;
    public void setValueAt(Object aValue, int row, int column) {
    System.out.println("into setValueAt");
    BayApplet applet = BayApplet.bayApplet;
    BayRecord dataRecord = (BayRecord) data.get(row);
    String oldValue = dataRecord.get(column).toString();
    String newValue = aValue.toString();
    //Don't do anything if it hasn't changed     
    if ( newValue.compareTo(oldValue) == 0 ) return;
    // Do data validation here
    switch ( column) {
    case (BayRecord.BAY ):
    case (BayRecord.BAY_DESCRIPTION ) :
         //update for the entire bay
         updateTable(column,dataRecord.get(BayRecord.EWTBMX_ID).toString(),newValue);
         dataRecord.setBayChanged(true);
         break;
    case (BayRecord.SUBBAY_DESCRIPTION ) :
    //update for all records associated with this subbay
              dataRecord.setSubBayChanged(true);
         updateTable(column,dataRecord.get(BayRecord.EWTSB_ID).toString(),newValue);
         break;
    case (BayRecord.FS ) :
    case (BayRecord.BL ) :
    case (BayRecord.WL ) :
    System.out.println("new value = " + newValue);
    try {
    Float.parseFloat(aValue.toString());
    catch (Exception e) {
              JOptionPane.showMessageDialog(applet
         , e
    , "BayTableModel.setValueAt(...) Format Error"
    , JOptionPane.ERROR_MESSAGE) ;
    return; // input value cannot convert to number
    WeightNumber tempNumber =new WeightNumber(newValue,WeightNumber.CG_FORMAT );
    dataRecord.set(column,tempNumber);
    dataRecord.setBayPointChanged(true);
    break;
    default: if ( newValue.compareTo(oldValue) != 0 ) {
    dataRecord.set(column,aValue);
    applet.setModified(true);
    * Updates all of the bay discriptions for table
    public void updateTable (int column, String key ,String newValue ){
    HashMap tempMap;
    switch(column) {
    case BayRecord.BAY :
    case BayRecord.BAY_DESCRIPTION :
         tempMap = bayMap;
         break;
    case BayRecord.SUBBAY_DESCRIPTION :
         tempMap = subBayMap;
         break;
    default: return; }
    // Does the master relationship exist?     
    if (! tempMap.containsKey(key)){
         return;
    if ( tempMap.get(key) == null) return;
    // get the vector that is associated with this key
    // associated with key
    Vector tempVector = (Vector)tempMap.get(key);
    for (int iloop = 0;iloop < tempVector.size();iloop++) {
         BayRecord tempRecord = (BayRecord) tempVector.get(iloop);
         tempRecord.set(column,newValue);
    * Returns the alignment of the specified <I>col</I> in the table.
    public int getAlignment(int col){
    return (COLUMN_ALIGNMENT[col]) ;
    public boolean isChanged () {
    return changed;
    public void setChanged (boolean nChanged) {
    changed = nChanged;
    public void updateData(Vector nData){
    data.removeAllElements();
    bayMap = new HashMap();
    subBayMap = new HashMap();
    WeightNumber ewtbmxID ;
    WeightNumber ewtsbID ;
    for (int iloop = 0; iloop < nData.size(); iloop++){
    BayRecord tempRecord = (BayRecord)nData.get(iloop);
    data.add(tempRecord);
    addToMaps(tempRecord);;
    * Places record hashmaps for easy access
    private void addToMaps(BayRecord nRecord) {
    // has ewtbmx_id been set?
    if (nRecord.get(BayRecord.EWTBMX_ID) == null){
         return;
    // is there a bayMap?
    if (bayMap == null) {
         bayMap = new HashMap(); }
    WeightNumber ewtbmxID = (WeightNumber) nRecord.get(BayRecord.EWTBMX_ID);
    Vector bayVector;
    //Does the vector for this key exist?
    if (bayMap.containsKey(ewtbmxID.toString() )) {
    bayVector = (Vector) bayMap.get(ewtbmxID.toString());
    else {
         bayVector = new Vector();
    bayMap.put(ewtbmxID.toString(),bayVector );
    bayVector.add(nRecord );
    if (nRecord.get(BayRecord.EWTSB_ID) == null) return;
    // is there a subBayMap?
    if (subBayMap == null) {
         subBayMap = new HashMap(); }
    WeightNumber ewtsbID = (WeightNumber) nRecord.get(BayRecord.EWTSB_ID);
    Vector subBayVector;
    if (subBayMap.containsKey(ewtsbID.toString() )) {
    subBayVector = (Vector) subBayMap.get(ewtsbID.toString());
    else {
    subBayVector = new Vector();
    subBayMap.put(ewtsbID.toString(),subBayVector );
    subBayVector.add(nRecord );
    * Array of column widths for all displayed columns in the JTable.
    public static final int COLUMN_WIDTH[] = {30,200,200,40,40,40};
    * Array of column alignments for all displayed columns in the JTable.
    private static final int COLUMN_ALIGNMENT[] = {    JLabel.LEFT, JLabel.LEFT, JLabel.LEFT    ,  JLabel.RIGHT, JLabel.RIGHT, JLabel.RIGHT} ;
    private Vector data;
    private WeightEmployee user;
    //This map will contain references to
    //Rows in the JTable associated with unique bays
    //If someone changes a bay on one line, it will change it
    //for all lines associated with that bay.
    private HashMap bayMap;
    private boolean changed;
    //This map will contain references to
    //Rows in the JTable associated with unique subbays
    //If someone changes a subbay on one line, it will change it
    //for all lines associated with that bay.
    private HashMap subBayMap;
    public static final String SOURCE = "$Source: /apps/csna/javaSource/com/cessna/ewt/weight/RCS/WeightTableModel.java,v $";
    public static final String REV = "$Revision: 1.1 $";}

  • Updating JTable from data from resultset

    I have an athletics database, where the user updates an event and round e.g. 100M run Round 1. I then have a query which returns the 3 fastest times from each round for whatever event.
    Now on my JTable gui, the user chooses what event and round to update through 2 JCombo boxes, one for events, one for rounds. Now if the user chooses the round name final, i need the JTable to update the table with the three fastest times from rounds 1, 2 and 3.
    Whats the best way to do this? I was thinking putting all the different result sets into an array, and then through an if loop have somthing like
    if(roundType.equals (final))then in the body of this loop, create an instance of my JTable setting the rows for each column the the resultset data.
    Is this the right approach or any other advise?
    cheers

    You probably defined the "table" variable twice. Once as a class variable and once as a local variable and your "insertValue" method is referring to the wrong variable and therefore updating the wrong table.

  • Help requested - JTable input data

    Hi,
    I need to build an empty JTable and then have the user interactively fill the rows of the table. Now, I know how to build a static table with row values in the code. However, I have no clue how to get a empty table filled by user input. Any example, help or suggestion is highly appreciated. Thanks.

    That would work, but it might be more complicated than necessary. If you look in the DefaultTableModel class you'll find methods to insert and remove rows. Once you have the data, you can insert it usingDefaultTableModel model = yourTable.getModel();
    model.addRow(data);http://java.sun.com/j2se/1.4/docs/api/javax/swing/table/DefaultTableModel.html

  • Providing a TooltipText for the ListBox  data selection  in Javascript

    Hi ,
    I have a ListBox(select) which contains multiple values when i select a value it should popup a tooltip text mentioning that selected value. How to do it Javascript? Please do provide a solution for this. Since this is urgent.
    Thanks,
    M.Ananthu

    You can download this:
    http://www.walterzorn.com/tooltip/tooltip_e.htm
    Then modify the onMouseOver of the select to call a Javascript function which will display the popup based on the currently selected index...

  • Problems to get Jtable's data

    Hi
    I have has probles when I tried to get dato of my table, my table has 3 JComboBox, this is my code
    jTable1.setModel(new DefaultTableModel(
    new Object [][]
    {null, null, null, null},
    new String []
    "Columna", "Operador", "Valor", "L\u00f3gico"
    TableColumn operateColumn = jTable1.getColumnModel().getColumn(1);
    //Se crea y llena ComboBox
    JComboBox comboBox2 = new JComboBox();
    comboBox2.addItem("Es igual que");
    comboBox2.addItem("Es mayor que");
    comboBox2.addItem("Es menor que");
    operateColumn.setCellEditor(new DefaultCellEditor(comboBox2));
    // The rest of the JComboBox
    And this is my Method to get the data, but it dosen't work, Could you help me?
    private void jButtonAceMouseClicked(MouseEvent evt)
    String strQuery = "SELECT ";
    Object ob = new Object();
    int indexCombo;
    for (int i=1;i<=jTable1.getRowCount();i++)
    for (int j=1;j<=jTable1.getColumnCount();j++)
    if (j==2)
    indexCombo = 0;
    indexCombo = comboBox2.getSelectedIndex();
    ob = jTable1.getValueAt(i,j);
    }

            for (int i=0;i<jTable1.getRowCount();i++) {
                for (int j=0;j<jTable1.getColumnCount();j++) {
                    Object value = jTable1.getValueAt(i,j);
                    System.out.println(
                            " row="    + i +
                            " column=" + j +
                            " value="  + ( value != null ? value : "null" )
                System.out.println("");
            }

  • 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;

  • JTable as a data entry screen

    I am trying to use JTable for data entry. I assign few columns to contain
    Integer class type and others with Float. Now, the problem that arise is
    that Objects of Integer and Float are sub-classes class Number and JTable
    has by default a Cell Editor defined to handle this Class type. The problem
    arises only when a float type is handled. Floats which i use carry either a 3
    decimals or 2 (basically quantity is represented in 3 decimals and amounts in
    2 decimals). But for eg if i have a float 3456.78 i want that to displayed as
    3456.780 and if 987.6 then 987.60. I can manipulate them in the required form
    as a String but not as Number. (then its not right aligned). I have no clues how to do this and its very much important that i finish this asap.
    Gurus out here please pour all the help you can .
    Thanks in advance
    Shomal

    You talked about editors, but it seems like you are able to edit just fine. It seems that displaying a previously edited Float is your real problem. If that is the case, you just need to add a specialized cell renderer for displaying your Float objects.
    First create an implementation of TableCellRenderer (it's easy, there is only one method) that returns your Float object rendered correctly.
    Then just add the following code:
    TableCellRenderer renderer = new MyFloatRenderer().
    table.setDefaultRenderer(Float.class, renderer);
    From now on Integers will use the regular Number Cell Renderer and Floats will use your custom renderer.
    If you have a problem with the editor also, the steps are similar.
    Implement TableCellEditor (only one method again) then add the following code:
    TableCellEditor editor = new MyFloatEditor();
    table.setDefaultEditor(Float.class, editor);
    Offer duke dollars next time, you'll probably get a more timely response.

Maybe you are looking for