Rebuilding JTable

I'm trying to build a table by first selecting a table name. then i press a button and the table appears. When i change the table name and press the button again the table doesn't change. What is going wrong????
Here's the code:
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import java.sql.*;
import java.util.*;
import javax.swing.*;
import javax.swing.JInternalFrame;
public class IPMAC extends JInternalFrame {
     private Connection connection;
private Statement statement;
     private ResultSet resultSet;
     String selectedGroep;
     private JTable table;
     private int AAP = 1;
static final int xOffset = 480, yOffset = 10;
     int y, // De y waarde declareren
x; // De x waarde declareren
private JComboBox groepKeuze;
Vector result;
JDesktopPane desktop;
     public IPMAC()
     throws
                    ClassNotFoundException,
                    SQLException,
                    IllegalAccessException,
                    InstantiationException{
super("IP MAC",
          false, //resizable
     true, //closable
     false, //maximizable
     true);//iconifiable
          //Set up the GUI.
desktop = new JDesktopPane(); //a specialized layered pane
setContentPane(desktop);
//Set the window's location.
setLocation(xOffset, yOffset);
final String url = "jdbc:mysql://localhost/IPMAN";
          final String username = "";
          final String password = "";
          Class.forName("org.gjt.mm.mysql.Driver").newInstance();
     connection = DriverManager.getConnection( url, username, password );
     Label label1 = new Label();
     Label label2 = new Label();
     Label label3 = new Label();
     final TextField macadresveld = new TextField();
     final TextField ipadresveld = new TextField();
     Button button1 = new Button();
     Button button2 = new Button();
     Button button3 = new Button();
          label1.setText("MAC Adres");
          getContentPane().add(label1);
          label1.setBounds(370,60,70,25);
          label2.setText("IP Adres");
          getContentPane().add(label2);
          label2.setBounds(370,110,70,25);
          label3.setText("Groepnaam");
          getContentPane().add(label3);
          label3.setBounds(370,160,70,25);
          getContentPane().add(macadresveld);
          macadresveld.setBounds(440,60,156,20);
          getContentPane().add(ipadresveld);
          ipadresveld.setBounds(440,110,156,20);
          button1.setLabel("Koppel MAC");
          getContentPane().add(button1);
          button1.setBackground(java.awt.Color.lightGray);
          button1.setBounds(506,10,90,25);
          button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
               JOptionPane.showMessageDialog
               ( null, "MAC Adres is being added...", "Updating...",     JOptionPane.INFORMATION_MESSAGE);
try {
          Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
          connection = DriverManager.getConnection( url, username, password );
          Statement stmt = connection.createStatement();
          int numUpdated01 = stmt.executeUpdate("UPDATE ip SET MacAdres = '" + macadresveld.getText() + "' WHERE IpAdres = '" + ipadresveld.getText() + "' ");
          connection.close();
          catch ( ClassNotFoundException cnfex )
          System.err.println(
     "Failed to load JDBC/ODBC driver." );
          cnfex.printStackTrace();
          System.exit( 1 ); // terminate program
          catch ( SQLException sqlex )
          System.err.println( "Unable to connect" );
          sqlex.printStackTrace();
               JOptionPane.showMessageDialog
               ( null, "Data has been updated...", "Updated...",     JOptionPane.INFORMATION_MESSAGE);
          button2.setLabel("Save / Exit");
          getContentPane().add(button2);
          button2.setBackground(java.awt.Color.lightGray);
          button2.setBounds(506,300,90,25);
          button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
dispose();
          button3.setLabel("View Data");
          getContentPane().add(button3);
          button3.setBackground(java.awt.Color.lightGray);
          button3.setBounds(506,265,90,25);
          button3.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
                         System.out.println("de gekozen Groep is:" + selectedGroep);
                         try     {
                    getTable();
                         catch(Exception ex)     { }
groepKeuze = new JComboBox(getContents());
groepKeuze.setMaximumRowCount(4);
     groepKeuze.setBounds(440,160,156,20);
groepKeuze.setBackground(java.awt.Color.white);
     getContentPane().add( groepKeuze );
groepKeuze.addItemListener(new ItemListener() {
     public void itemStateChanged( ItemEvent e ) {
          selectedGroep = groepKeuze.getSelectedItem().toString();
          System.out.println( "de gekozen Groep is:" + selectedGroep );
     setSize(616,370);
          show();
          private Vector getContents()
          throws
          ClassNotFoundException,
          SQLException,
          IllegalAccessException,
          InstantiationException
               Connection connection;
          Statement statement;
               ResultSet resultSet;
     final String url = "jdbc:mysql://localhost/IPMAN";
               final String username = "";
               final String password = "";
               Class.forName("org.gjt.mm.mysql.Driver").newInstance();
          connection = DriverManager.getConnection( url, username, password );
               result = new Vector();
               String query = "SELECT DISTINCT Groep FROM ip";
          statement = connection.createStatement();
          resultSet = statement.executeQuery( query );
               while (resultSet.next()) {
               result.addElement(resultSet.getString("Groep"));
          statement.close();
          return result;
     private void getTable()     throws
          ClassNotFoundException,
          SQLException,
          IllegalAccessException,
          InstantiationException
Statement statement;
ResultSet resultSet;
String query = "SELECT NetwerkAdres,IpAdres,KlasseNetwerk,Groep FROM ip WHERE Groep = '" + selectedGroep + "'";
statement = connection.createStatement();
resultSet = statement.executeQuery( query );
displayResultSet( resultSet );
statement.close();
selectedGroep = "";
private void displayResultSet( ResultSet rs )
     throws
          ClassNotFoundException,
          SQLException,
          IllegalAccessException,
          InstantiationException {
boolean moreRecords = rs.next();
if ( ! moreRecords ) {
JOptionPane.showMessageDialog( this,
"ResultSet contained no records" );
setTitle( "No records to display" );
return;
Vector columnHeads = new Vector();
Vector rows = new Vector();
ResultSetMetaData rsmd = rs.getMetaData();
for ( int i = 1; i <= rsmd.getColumnCount(); ++i )
columnHeads.addElement( rsmd.getColumnName( i ) );
do {
rows.addElement( getNextRow( rs, rsmd ) );
} while ( rs.next() );
table = new JTable( rows, columnHeads );
JScrollPane scroller = new JScrollPane( table );
getContentPane().add(scroller);
          scroller.setBounds(0,0,370,325);
validate();
private Vector getNextRow( ResultSet rs,
ResultSetMetaData rsmd )
     throws     ClassNotFoundException,
               SQLException,
               IllegalAccessException,
                    InstantiationException{
Vector currentRow = new Vector();
for ( int i = 1; i <= rsmd.getColumnCount(); ++i )
switch( rsmd.getColumnType( 1 ) ) {
case Types.VARCHAR:
currentRow.addElement( rs.getString( i ) );
break;
case Types.INTEGER:
currentRow.addElement(
new Long( rs.getLong( 1 ) ) );
break;
default:
System.out.println( "Type was: " +
rsmd.getColumnTypeName( i ) );
return currentRow;
Could somebody try to answer this question???
thanks!!

try
table.getModel().fireTableStructureChanged();
where you have the validate() line just to see.. I've never actually created a new JTable for every new display, I just manipulate the models and then run the fireTableDataChanged() or fireTableStructureChanged() methods.. That takes care of all this stuff automatically, and I think that'd be a more efficient way of doing things..
If THAT doens't work, then I'd be suspicious of your scrollpane not redrawing itself.. Do a System.out.println( (String)table.getValueAt(1,1) ); and see if the table actually has the new values or not.. If it DOES but it's not on screen, then you know this is the case.. Then I'd try scroller.revalidate() and scroller.repaint().
doug

Similar Messages

  • JTree addSelectionPath and ClassCastExceptions

    Hi.
    I'm trying to build a tree view from a list of strings that represent relative path names (ie: Icons\a\image.dds)
    I have tokenized the path name based on the file separator and placed it into a String array which is used to create a new TreePath object, but when I try to add the tree path to the tree using tree.addSelectionPath(TreePath) it throws a ClassCastException: java.lang.String.
    Is this something I am doing wrong, or is this a problem with java? I have extensively searched the forum and have not found anything that relates to this.
    Thanks in advance.

    Same question on "model" and "view":
    JTable build on top of TableModel, I think the implenmentation of JTable constructor like this: invoke the methods of TableModel and get the rowCount and columnCount number, then according rowCount and columnCount number and "getValueAt()" method build a doulble "for" loop to create vector of vector, then according the vector of vector to build a table and draw the table, are these ideas correct?
    The question is every time when we modify the TableModel, we explicitly call "fireTableDataChanged()" method, this method will notify all of the listeners, where are these listeners? did these listeners recall JTable constructor to rebuild the table and draw? if yes, how does this happen? if not, where do we recall double "for" loop? it seems the simple and easys way to recall JTable constructor, but if we rebuild JTable object, how can we notify the JPanel to redraw? it seems lots of mystry on "model" and "view" for me.
    The big question is no body answer my questions, it is because my questions so simple, so easy or so stupid, I am new in Java, that's why I have these questions, I need Java professionals to help me!
    Thanks for all your help!

  • Multiple JComboxes in Jtable.  Select 1, rebuild the other

    I have two JComboboxes in a Jtable row. When I make a selection in 1 of them, I want to rebuild the other and automatically select an item in it. I don't have any problem putting JComboboxes in the table but I can't seem to edit the second one when I select an item in the first one.
    Thanks, Larry

    table.setCellSelectionEnabled(true);
    table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
    DefaultListSelectionModel model =
         (DefaultListSelectionModel)table.getColumnModel().getSelectionModel();
    model.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

  • Mouselistner is not working with jtable in the browser

    Hi
    I am having a problem with jTable.
    I added a mouselistener to table header to sort table but when i run that applet from my netbean ide it works fine but when i run that applet in my browser it doesn't work, i have tested, its not even generate mouseclick event .Please help me guys.
    I call this function after calling initComponents() method of JApplet.
    public void setTableAction()
    //set mouselistener to sort table on click of table header
    final JTableHeader head= jTable1.getTableHeader();
    head.addMouseListener(new java.awt.event.MouseAdapter()
    public void mouseClicked(java.awt.event.MouseEvent evt)
    Vector data= ((DefaultTableModel)jTable1.getModel ()).getDataVector();
    sortTable(data, head.columnAtPoint(evt.getPoint()));
    //set action map to change the default action performed for enter key pressed
    InputMap imap = jTable1.getInputMap(JTable.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    KeyStroke enterKey = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
    KeyStroke tabKey = KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0);
    final Action oldAction= jTable1.getActionMap().get(imap.get(tabKey)); // get map to set enter key.
    imap.put(enterKey, "enter"); // set enter key
    Action newAction = new AbstractAction(){
    public void actionPerformed(ActionEvent e) {
    oldAction.actionPerformed(e);
    JTable table= (JTable)e.getSource();
    table.changeSelection(0,0,false,false);
    if(table.isCellEditable(0,0))
    String sTemp= (String)table.getValueAt(0,0);
    if(sTemp.length()>0) {
    if(bRenewItem)
    retrieveRcodeDetails("",sTemp);
    else
    processRCodeDetails(sTemp, e);
    }else
    table.editCellAt(0,0);
    jTable1.getActionMap().put("enter", newAction);
    jTable1.setPreferredScrollableViewportSize(jTable1.getPreferredSize());
    }

    Hi,
    I also am using the Bépo layout with an encrypted drive and encountered the same problem: the Return key does not work.
    It seems to work fine if you use the fr-bepo-latin9 keymap.
    # /etc/vconsole.conf
    KEYMAP=fr-bepo-latin9
    But I also looked at the files /usr/share/kbd/keymaps/i386/bepo/fr-bepo.map.gz and /usr/share/kbd/keymaps/i386/bepo/fr-bepo-latin9.map.gz (you can open gzipped files in vim directly). fr-bepo-latin9.map.gz defines keycode 28 (Return) but fr-bepo.map.gz does not.
    I modified fr-bepo.map.gz:
    # vim /usr/share/kbd/keymaps/i386/bepo/fr-bepo.map.gz # Append that line : "keycode 28 = Return".
    # mkinitcpio -p linux # Rebuild the initramfs.
    The Return key now works, but the Backspace (14, "Delete") and Shift (54) keys don’t work. I found that both the cf.map.gz (french canadian layout) and fr-bepo-latin9.map.gz files define those keycodes as well as other non-printing keys so I copied the following lines from fr-bepo-latin9.map.gz to fr-bepo.map.gz:
    keycode 1 = Escape Escape
    keycode 14 = Delete Delete
    keycode 15 = Tab Tab
    keycode 28 = Return
    keycode 29 = Control
    keycode 42 = Shift
    keycode 54 = Shift
    keycode 56 = Alt
    keycode 58 = Caps_Lock
    keycode 97 = Control
    It works! Don’t forget to rebuild the initramfs after you change the keymap file.
    # mkinitcpio -p linux
    I will send a message to the kbd and bépo projects mailing lists and report back.

  • Adding a Column to a JTable

    I have a simple gui where I query a database and return a result set in a JTable using a table model. I would like to be able to add a new column with checkboxes as the first column in the table. I've seen examples using checkboxes with boolen data from the database, but this column is not being returned from the database it is a new added column.
    The first task is to add the column and I am struggling with this. My code is below.
    import java.awt.BorderLayout;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    public class DatabaseTest extends JFrame {
      private QueryTableModel qtm;
      public DatabaseTest()
        super("JTable Test");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(350, 200);
        qtm = new QueryTableModel();
        JTable table = new JTable(qtm);
        JScrollPane scrollpane = new JScrollPane(table);
        JPanel p1 = new JPanel();
        p1.setLayout(new GridLayout(3, 2));
        p1.add(new JLabel("Click here to Query the DB: "));
        JButton jb = new JButton("Search");
        jb.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e)
            qtm.Query();
        p1.add(jb);
        getContentPane().add(p1, BorderLayout.NORTH);
        getContentPane().add(scrollpane, BorderLayout.CENTER);
      public static void main(String args[]) {
        DatabaseTest tt = new DatabaseTest();
        tt.setVisible(true);
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.ResultSetMetaData;
    import java.sql.Statement;
    import java.util.Vector;
    import javax.swing.table.AbstractTableModel;
    class QueryTableModel extends AbstractTableModel {
      Vector cache;
      private int colCount;
      private String[] headers;
      Statement statement;
      private static Connection conn = null;
      public QueryTableModel() {
        cache = new Vector();
      public String getColumnName(int i) {
        return headers;
    public int getColumnCount() {
    return colCount;
    public int getRowCount() {
    return cache.size();
    public Object getValueAt(int row, int col) {
    return ((String[]) cache.elementAt(row))[col];
    public void Query() {
    cache = new Vector();
    try {
    Class.forName("oracle.jdbc.driver.OracleDriver");
    conn=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:*****","******","*******");
    statement = conn.createStatement();
    ResultSet rs = statement.executeQuery("Select username from dba_users where rownum < 6");
    ResultSetMetaData meta = rs.getMetaData();
    colCount = meta.getColumnCount();
    // Now we must rebuild the headers array with the new column names
    headers = new String[colCount];
    for (int h = 1; h <= colCount; h++) {
    headers[h - 1] = meta.getColumnName(h);
    while (rs.next()) {
    String[] record = new String[colCount];
    for (int i = 0; i < colCount; i++) {
    record[i] = rs.getString(i + 1);
    cache.addElement(record);
    fireTableChanged(null);
    // Add column code here?
    } catch (Exception e) {
    cache = new Vector(); // blank it out and keep going.
    e.printStackTrace();
    }Not sure how to add the column. I've tried a few variations of the following code with no luck:TableColumn tc = new TableColumn(0, 120);
    tc.setHeaerValue("Name");
    table.getColumnModel().addColumn(tc);Any help would be appreciated.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    The first task is to add the column Well, I like the suggestions from the link given in the above posting :-) It shows you how to dynamically alter the TableModel after its initial creation, and is probably the best generic solution.
    But, just so you understand better how a TableModel works I"ll just put another thought in your mind. Maybe in this case you just create the TableModel correctly the first time so you don't need to do a dynamic change. The TableModel doesn't know where the data came from. It doesn't care that it came from a ResultSet. All it knows it that you have data in an array. So whats to prevent you from hard coding the first column to contain Boolean data?
    {code}headers = new String[colCount+1];
    headers[0] = "Boolean Column";
    for (int h = 1; h <= colCount; h++)
    headers[h] = meta.getColumnName(h);
    while (rs.next())
    String[] record = new String[colCount+1];
    record[0] = new Boolean.FALSE;
    for (int i = 1; i <= colCount; i++)
    record[i] = rs.getString(i);
    }{code}

  • Please help me..JTable trouble

    Hi all java guru,
    i've have a JTable in which i want to insert some styled text (e.g. bold,underline,italic).... i use a JEditorPane as CellEditor and JEditorPane as renderer. In each JEditorPane i have registered a StyledEditorKit that is used for styles.
    I've noted that when i insert styled text, initially cell maintains text style, but when i click on other cell,style of text disappears....i want to specify that i don't want to add style to entire cell, but i wish to add style at a portion of text.....
    notbold bold | not styled text
    Cell0 ----------------------- Cell1
    Is this behavior normally ???
    Then i've implemented a CustomTableModel that maintains information about text style, in such way that when renderer cell, i can rebuild exact text with its style....same method is adopted for CellEditor.
    It is possible to have more than one JTable in my application....then to correctly handle all JTables ' put the in a vector and during editing and rendering i find current focusable JTable and edit/render it.
    It seems a right solution ???
    I insert style on text using a toolbar and menubar in a dynamically way.
    Please, give to me an advice...Is right this solution??Or exist another way to resolve this proble in a more elegant way??
    Tnx in advance
    regards,
    anti-shock

    That's correct.
    Try to set HTMLEditorKit for your editor/renderer JTextPane. In the TableModel you can save text from textPane.getText() and set the text in the renderer component in the appropriate renderer's method.
    regards,
    Stas

  • Please Help.JTable insert styled text

    Hi all java guru,
    on post http://forum.java.sun.com/thread.jsp?forum=57&thread=485469 i've depicted my scenario in which i have a JTable where i want to add styled text.
    i've implemented a CustomTableModel that maintains information about text style, in such way that when renderer cell, i can rebuild exact text with its style....same method is adopted for CellEditor.
    It is possible to have more than one JTable in my application....then to correctly handle all JTables ' put them in a vector and during editing and rendering i find current focusable/selected JTable and edit/render it.
    Clearly i maintain information about style of text when i insert it, that is when i insert text, i update my CustomTableModel...same thing must be done when i delete text from JTable...that is, i must update CustomTableModel too in this case.
    Because my CellEditor is a JEditorPane component (extend it) i've registered document associated to it to a DocumentListener that notify every time that a remove operation is happens.
    What is the problem now???problem is that when i finish to edit a cell and click on another cell i've got a removeUpdate(DocumenEvent e) event, and i can't distinguish it.....it seems a real remove event....
    In this case(when i change cell) the code that is executes returns wrong result and invalidate all the rest.
    I think error is where i register celleditor , now i do it in CustomCellRenderer class that extend JEditorPane and implements TableCellRenderer.
    Please help me...this is a great trouble that invalidate all my work :(
    Any new idea is welcome.
    regards,
    anti-shock

    Hi stanislav, of course i can...you're a myth :)
    public class CustomCellEditor extends AbstractCellEditor implements TableCellEditor {
           CellEditor cellArea;
         JTable table;
         public CustomCellEditor(JTable ta) {
              super();
              table = ta;
              // this component relies on having this renderer for the String class
              MultiLineCellRenderer renderer = new MultiLineCellRenderer();
              table.setDefaultRenderer(String.class,renderer);
         public Object getCellEditorValue() {
              return cellArea.getText();
         public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected,     int row, int column) {
              int start = 0;
              int end = 0;
                                               // Get current selected table
              TableEditor tb = (TableEditor) TableEditor.getSelectedTable();
              TableModel model = (TableModel) tb.getModel();
              Vector fontInfo = model.getFontFor(row,column);
              CellEditor cellArea = (CellEditor) ((CustomCellEditor)tb.getCellEditor (row,column)).getCellEditor();
              Document doc = cellArea.getDocument();
              String content = tb.getValueAt(row,column).toString();     
              if (doc!=null && fontInfo.size()>0 && !content.equals("")) {
                                                     // This method reads from model and get right style info
                                                     // for current text, and restore them
                                                     restoreFontWithAttributes(doc,fontInfo,content);
              else
                   cellArea.setText(tb.getValueAt(row,column).toString());
              cellArea.rowEditing = row;
              cellArea.columnEditing = column;
              cellArea.lastPreferredHeight = cellArea.getPreferredSize().height;
              return cellArea;
          * @return
         public CellEditor getCellEditor() {
              return cellArea;
         public class CellEditor extends JEditorPane {
              private CellStyledEditorKit k;
              public CellEditor() {
                    super("text/plain","");
                    k = new CellStyledEditorKit();
                    setEditorKit(k);
                    // I tried to add document here, but i have had wrong behavior
                   doc = new DocumentListener() {
                   public void removeUpdate(DocumentEvent e) {
                      // Get current selected table
                      TableEditor tb = (TableEditor) TableEditor.getSelectedTable();
                      TableModel model = (TableModel) tb.getModel();
                      model.updateFontInfo();
                   getDocument().addDocumentListener(doc);
    }Ok, stan...this is my CustomCellRenderer class....as i have already said, i have some style text info mainteined by CustomTableModel associated with JTable.
    I update CustomTableModel every time that an insert and remove operation happens.
    If i add a DocumentListener to CellEditor (that rapresents editor cell of my table) happens that, if i remove some character from an editing cell, i got a removeUpdate event.....and this is right!!! But if i change cell (e.g. supposing editing cell(1,1), click on cell(2,1) then stop edit cell(1,1) and start edit cell(2,1)) i got a removeUpdate event, that I don't wait for to me..
    Look at this:
    empty cell | some text
    cell 0 ------- cell1
    supposing you're in cell1 and you have finished to insert "some text".Then click on cell0, that is empty....then document associated with CellArea(extend JEditorPane) before of the click on cell0 had some text, but after click have no text, then for it a removeUpdate is happens.....and is that one i got..
    it's as if an unique document is associated to all cells, while should be one document for each cell (i hope this is right).
    Clearly, i've same code for renderer, in such way that i can restore style of text on rendering.
    Hope is clear....if U have any idea or suggestion please give to me.
    Tnx a lot Stanislav..
    regards,
    anti-shock

  • JTable custom renderer never calls getTableCellRendererComponent()

    I have a custom renderer for Dates in my JTable. I've set it as the renderer on Date columns and I've also tried setting it as the table default for the Date type. In both cases the getTableCellRendererComponent() method never gets called.
    I've also tried right-justifying String columns with
              DefaultTableCellRenderer renderer = (DefaultTableCellRenderer)table.getDefaultRenderer(String.class);
              renderer.setHorizontalAlignment(JLabel.RIGHT);
    but the Strings are always left-justified. Same with integers.
    I verify that the new renderer / alignments are actually set immediately after setting them. A few method calls later I notice that the alignments have changed back. My custom date renderer is still set, however.
    My code calls fireTableStructureChanged(). I set/reset all renderers after the call to fireTableStructureChanged(). I wonder if fireTableStructureChanged() rebuilds the table some teim later wiping out the renderer / alignments that I've set and replacing them with the defaults.
    Is there a callback or some method that I need to override after calling fireTableStructureChanged() in order to get my renderer / alignments to remain in effect?

    I can't post the code because it is proprietary and the application itself is large.
    The trouble seems to start when I call fireTableStructureChanged(). None of the toy examples in books that I've seen address fireTableStructureChanged(). The JavaDocs for Swing don't tell you about all of the side effects of fireTableSTructureChanged().
    You're comment about overriding getColumnClass() got my custom data renderer working. The Javadocs for DefaultTableModel and JTable don't mention when you need to override getColumnClass(). Overriding getColumnClass() in the TableModel seems to apply to JTable as well. I don't understand why, but it seems to work.
    I am able to justify my columns be creating a default renderer and calling setHorizontalAlignment() on it and setting it as the default for the JTable. The code below doesn't work, however:
    DefaultTableCellRenderer renderer = (DefaultTableCellRenderer)table.getDefaultRenderer(int.class);
    renderer.setHorizontalAlignment(JLabel.RIGHT);
    It seems that the default renderers reset themselves back to their default state. I have no idea why, but that is what I am seeing.
    There is also a big difference in the way that primitives and wrappers are handled (i.e. int compared to Integer).
    One of the other posters here said that if I call setModel() that I would have to reset the renderers. The Javadocs don't say anything about that. (I only call setModel during initialization. I do update the actual data in the TableModel which can change the structure of the table. That is when I call fireTableStructureChanged() and all the difficulties start.)
    This whole episode has shown that the Swing Javadocs are next-to-worthless for writing real-world Swing applications. I've written several Swing applications over the years, and once they get beyond the simple level they become difficult to write and maintain due to the lack of documentation. For my next Java GUI I'm going to check out JavaFX (as soon as it is available on Linux). I don't see how it could be worse than Swing.
    Thanks for all of your help. You got me on the path to getting this solved.

  • Vertical ScrollBar for JTable disappears when trying to scroll!

    Hi!
    I have 2 JTables and these are in a JScrollPane. I need to add a Vertical ScrollBar in such a way that when the number of rows increases, the scrollbar will scroll both the table's data.
    I am not using the Vertical ScrollBar of the ScrollPane instead i have added a JScrollBar to the two Panes( i.e. scrollPane.setVerticalScrollBar() ). This works fine.
    But when I remove the columns from the right JTable , i.e. I have only one JTable left, the Vertical scrollbar disappears inspite of the number of rows being the same.
    I have tried setting ViewPortView etc. but nothing works.
    Please help!

    Remember that was a test. It tells us the iPhoto is essentially sound and the issue is within that main Library.
    Next move is to try repair that library.
    Option 1
    Back Up and try rebuild the library: hold down the command and option (or alt) keys while launching iPhoto. Use the resulting dialogue to rebuild. Choose to Repair Database. If that doesn't help, then try again, this time using Rebuild Database.
    If that fails:
    Option 2
    Download iPhoto Library Manager and use its rebuild function. (In early versions of Library Manager it's the File -> Rebuild command. In later versions it's under the Library menu.)
    This will create an entirely new library. It will then copy (or try to) your photos and all the associated metadata and versions to this new Library, and arrange it as close as it can to what you had in the damaged Library. It does this based on information it finds in the iPhoto sharing mechanism - but that means that things not shared won't be there, so no slideshows, books or calendars, for instance - but it should get all your events, albums and keywords, faces and places back.
    Because this process creates an entirely new library and leaves your old one untouched, it is non-destructive, and if you're not happy with the results you can simply return to your old one.  
    Regards
    TD

  • JTable with AUTO_RESIZE_OFF not resizing at all!

    I tried to find solution in other posts, but no success.
    I created a JTable with
    table.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);That�s fine, but now I can�t resize it at all while interacting with it.
    That�s the main code of the table.
    I�d appreciate any any help.
    Thanks in advice.
            int preferredWidth = 0;
            int preferredSizeSum = 0;
            //Rebuild TableColumnModel with correct number of columns
            ((AbstractTableModel)getTable().getModel()).fireTableStructureChanged();
            //Set the columns widths based on the field data
            TableColumnModel columnModel = getTable().getColumnModel();
            for (int i = 0; i <= multiProperties.size(); i++) {                       
                TableColumn column = columnModel.getColumn(i);
                //Start with the reported column width
                preferredWidth = column.getWidth();
                //Enforce minimum width needed to display column header text
                preferredWidth = Math.max(preferredWidth, ((AbstractTableModel)getTable().getModel()).getColumnName(i).length() * 10);
                //Enforce maximum width so long fields get truncated
                preferredWidth = Math.min(preferredWidth, 200);
                //Set the column width
                column.setPreferredWidth( preferredWidth );
                column.setMinWidth( 5 );
                column.setMaxWidth( 500 );
                preferredSizeSum += preferredWidth;
            getTable().setMaximumSize( new Dimension( 500*multiProperties.size(), tableHeight ) );
            getTable().setMinimumSize( new Dimension( 5*multiProperties.size(), tableHeight ) );
            getTable().setPreferredSize( new Dimension( preferredSizeSum, tableHeight ) );       
            getTable().setSize( new Dimension( preferredSizeSum, tableHeight ) );

    Works fine for me:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=623692
    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program (SSCCE) that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.

  • Rebuild table when actionperformed

    I'm trying to rebuild my table to reflect the changed data when my calculate button is clicked. I'm getting a null pointer exception on compile
    public class DennisBillingsWK3 extends JPanel implements ActionListener
         private double principal = 200000; 
         private int term[] = {30, 15, 7};               
         private double interestRate[] = {5.75, 5.5, 5.35};
         private double payment = calcPayment(0); 
         private String data[] = {"30 years at 5.75%", "15 years at 5.5%", "7 years at 5.35%"};
         private Object tableData[][];
         String[] colNames = {"Period", "Payment", "Interest", "Loan Balance"};
         private JLabel jlPrincipal;
         private JLabel jlLoanOptions;
         private JLabel jlPayment;
         private JScrollPane scrollPane;
         private JButton calculate;
         private JButton exit;
         private JFormattedTextField ftfPrincipal;
         private JFormattedTextField ftfPayment;
         private JTable table;
         private JComboBox loanOptions;
         public static void main(String[] args)
              DennisBillingsWK3 loan = new DennisBillingsWK3();
              loan.createGUI();
         public DennisBillingsWK3()
              super(new BorderLayout());
              jlPrincipal = new JLabel("Principal: ");
              jlPayment = new JLabel("Payment: ");
              jlLoanOptions = new JLabel("Loan options");
              ftfPrincipal = new JFormattedTextField();
              ftfPrincipal.setValue(new Double(principal));
              ftfPrincipal.setColumns(10);
              ftfPrincipal.addActionListener(this);
              ftfPayment = new JFormattedTextField();
              ftfPayment.setValue(new Double(payment));
              ftfPayment.setColumns(10);
              ftfPayment.setEditable(false);
              ftfPayment.setForeground(Color.black);
              table = new JTable();
              JScrollPane scrollPane = new JScrollPane(table);
              table.setFillsViewportHeight(true);
              loanOptions = new JComboBox(data);
              jlPrincipal.setLabelFor(ftfPrincipal);
              jlPayment.setLabelFor(ftfPayment);
              jlLoanOptions.setLabelFor(loanOptions);
              JPanel labelPane = new JPanel(new GridLayout(0,1));
              labelPane.add(jlPrincipal);
              labelPane.add(jlLoanOptions);
              labelPane.add(jlPayment);
              JPanel fieldPane = new JPanel(new GridLayout(0,1));
              fieldPane.add(ftfPrincipal);
              fieldPane.add(loanOptions);
              fieldPane.add(ftfPayment);
              JButton calculate = new JButton("Calculate");
              calculate.setActionCommand("calculate");
              calculate.addActionListener(this);
              JButton exit = new JButton("Exit");
              exit.setActionCommand("exit");
              exit.addActionListener(this);
              JButton clear = new JButton("Clear");
              clear.setActionCommand("clear");
              clear.addActionListener(this);
              JPanel buttonPane = new JPanel(new GridLayout(0,1));
              buttonPane.add(calculate);
              buttonPane.add(exit);
              buttonPane.add(clear);
              setBorder (BorderFactory.createEmptyBorder(30, 30, 30, 30));
              add(labelPane, BorderLayout.CENTER);
              add(fieldPane, BorderLayout.EAST);
              add(buttonPane, BorderLayout.SOUTH);
              add(scrollPane, BorderLayout.NORTH);
         public void createGUI()
              JFrame frame = new JFrame("Mortgage Calculator");
              frame.setBounds(350,300,600,150);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.add(new DennisBillingsWK3());
              frame.pack();
              frame.setVisible(true);
         public double calcPayment(int i)
              double adjRate = interestRate/(12*100);
              int adjTerm = term[i]*12;
              payment=principal*((adjRate*Math.pow((1+adjRate),adjTerm))/(Math.pow((1+adjRate),adjTerm)-1));
              BigDecimal hundredths = new BigDecimal(payment);
              hundredths = hundredths.setScale(2, BigDecimal.ROUND_UP);
              return hundredths.doubleValue();
         public void calcAmortTable(int i)
              double adjRate = interestRate[i]/(12*100);
              int adjTerm = term[i]*12;
              payment = calcPayment(i);
              double interest;
              double runningPrincipal = principal;
              DecimalFormat money = new DecimalFormat("$0.00");
              tableData = new Object[adjTerm][4];
              for(int x=0; x<adjTerm; x++) {
                   interest = adjRate*runningPrincipal;
                   runningPrincipal -= payment - interest;
                   tableData[x][0]= x+1;
                   tableData[x][1]= money.format(payment);
                   tableData[x][2]= money.format(interest);
                   tableData[x][3]= money.format(runningPrincipal);
              table = new JTable(tableData, colNames);
              scrollPane.add(table);
              scrollPane.validate();
         public void actionPerformed(ActionEvent e)
              if("calculate".equals(e.getActionCommand())) {
                   try {
                             if(principal <= 0 || ftfPrincipal.getValue() == null) {
                                  throw new NumberFormatException();
                             principal = ((Number)ftfPrincipal.getValue()).doubleValue();
                             int loanIndex = loanOptions.getSelectedIndex();
                             ftfPrincipal.setValue(principal);
                             ftfPayment.setValue(calcPayment(loanIndex));
                             calcAmortTable(loanIndex);
                   catch(NumberFormatException err)
                             JOptionPane.showMessageDialog(null,"No fields can be 0 or empty","Error",JOptionPane.INFORMATION_MESSAGE);
              if("exit".equals(e.getActionCommand())) {
                   System.exit(0);//System.exit closes application     
              if("clear".equals(e.getActionCommand())) {
                   ftfPrincipal.setValue(null);
                   ftfPayment.setValue(null);

    I snipped the code out of my constructor and removed the field and I made the following changes but my table doesn't show. I don't get any error or exceptions but not table
    Here's my constructor and calcAmortTable respectively
    public DennisBillingsWK3()
              // The super keyword calls the constructor from the parent class JPanel
              super(new BorderLayout());
              //set values for textfield labels
              jlPrincipal = new JLabel("Principal: ");
              jlPayment = new JLabel("Payment: ");
              jlLoanOptions = new JLabel("Loan options");
              //Setup text fields, initial value, number of positions and action listener
              ftfPrincipal = new JFormattedTextField();
              ftfPrincipal.setValue(new Double(principal));
              ftfPrincipal.setColumns(10);
              ftfPrincipal.addActionListener(this);
              ftfPayment = new JFormattedTextField();
              ftfPayment.setValue(new Double(payment));
              ftfPayment.setColumns(10);
              ftfPayment.setEditable(false);
              ftfPayment.setForeground(Color.black);
              //Setup amortization table
              table = new JTable();
              table.setFillsViewportHeight(true);
              //Setup combo box
              loanOptions = new JComboBox(data);
              //Attach labels to text fields
              jlPrincipal.setLabelFor(ftfPrincipal);
              jlPayment.setLabelFor(ftfPayment);
              jlLoanOptions.setLabelFor(loanOptions);
              //set labels and fields in a grid
              JPanel labelPane = new JPanel(new GridLayout(0,1));
              labelPane.add(jlPrincipal);
              labelPane.add(jlLoanOptions);
              labelPane.add(jlPayment);
              //create panel for textfields and add fields
              JPanel fieldPane = new JPanel(new GridLayout(0,1));
              fieldPane.add(ftfPrincipal);
              fieldPane.add(loanOptions);
              fieldPane.add(ftfPayment);
              //create buttons, set action commands and listener to be used in ActionPerformed method
              JButton calculate = new JButton("Calculate");
              calculate.setActionCommand("calculate");
              calculate.addActionListener(this);
              JButton exit = new JButton("Exit");
              exit.setActionCommand("exit");
              exit.addActionListener(this);
              JButton clear = new JButton("Clear");
              clear.setActionCommand("clear");
              clear.addActionListener(this);
              //Create panel for buttons
              JPanel buttonPane = new JPanel(new GridLayout(0,1));
              buttonPane.add(calculate);
              buttonPane.add(exit);
              buttonPane.add(clear);
              //set border for GUI and add panels to container
              setBorder (BorderFactory.createEmptyBorder(30, 30, 30, 30));
              add(labelPane, BorderLayout.CENTER);
              add(fieldPane, BorderLayout.EAST);
              add(buttonPane, BorderLayout.SOUTH);
    public void calcAmortTable(int i)
              double adjRate = interestRate/(12*100);
              int adjTerm = term[i]*12;
              payment = calcPayment(i);
              double interest;
              double runningPrincipal = principal;
              DecimalFormat money = new DecimalFormat("$0.00");
              tableData = new Object[adjTerm][4];
              for(int x=0; x<adjTerm; x++) {
                   interest = adjRate*runningPrincipal;
                   runningPrincipal -= payment - interest;
                   tableData[x][0]= x+1;
                   tableData[x][1]= money.format(payment);
                   tableData[x][2]= money.format(interest);
                   tableData[x][3]= money.format(runningPrincipal);
              table = new JTable(tableData, colNames);
              JScrollPane scrollPane = new JScrollPane();
              table.setFillsViewportHeight(true);
              add(scrollPane, BorderLayout.NORTH);

  • Update database from Jtable

    Hi all,
    I am trying to update database from Jtable. I added Jtable to scrollpane .
    My question is..
    after updating the Jtable..I want to save the details to database..when I click save button on my screen...how to do that? Please help me out! Thanks in advance..
    Here is the code that I wrote...
    public class VasuTest extends JFrame {
    private boolean DEBUG = true;
    Vector column_list = new Vector();
    Vector rows = new Vector();
    public VasuTest() {
    super("VasuTest");
         JToolBar toolBar = new JToolBar();
    JButton button = null;
    button = new JButton("Send Email");
    button.setToolTipText("This is the Exit button");
    button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
         System.out.println("Send Email");
    toolBar.add(button);
    button = new JButton("Save");
    button.setToolTipText("This is the Save button");
    button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
         System.out.println("Save");
    toolBar.add(button);
    button = new JButton("Exit");
    button.setToolTipText("This is the Exit button");
    button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
         System.exit(0);
    toolBar.add(button);
         JPanel ContentPane = new JPanel();
    ImageIcon i1 = new ImageIcon("Dongle.gif");
    JLabel j1 = new JLabel( i1, JLabel.CENTER);
         ContentPane.add(j1,BorderLayout.CENTER);
         setContentPane(ContentPane);
         JDBCT myModel = new JDBCT();
    String q = "select a.email_no,a.email_ln_no,b.cust_no,null customer_name,null cdate,a.batch_no,b.purch_ord_no,a.user_part_no,null part_desc,a.user_upgraded_part_no,null prod_id,a.qty,a.price,a.encrypted_sum_id,a.decrypted_sum_id,a.approval_key,a.status_cd,decode(a.status_cd,'APPROVED','true','ERROR','false','PROCESSED','true') approved,null end_cust,null sales_ord,null so_line,null sales_ord_cust,null shipment ,null sales_end_cust_name ,null shipment_line,a.note,null fromcust from upgrade_req_key_s3 a,upgrade_req_s3 b where a.email_no = b.email_no order by a.email_no,a.email_ln_no";
    myModel.setQuery();
    final Font f = new Font("SansSerif", Font.BOLD, 10);
    JTable table = new JTable(myModel);
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    // Container ContentPane = getContentPane();
         int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;
         int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS;
         JScrollPane scrollPane = new JScrollPane(table,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
         scrollPane.setPreferredSize ( new Dimension ( 770, 400 ) );
    ContentPane.add(toolBar,BorderLayout.CENTER);
    //Add the scroll pane to this window.
    ContentPane.add(scrollPane,BorderLayout.CENTER);
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    public class JDBCT extends AbstractTableModel {
    Vector cache; // will hold String[] objects...
    int colCount;
    int rowHeight;
    String [] headers;
    Connection db;
    Connection conn;
    Statement statement;
    String currentURL;
    // public QueryTableModel() {
    // cache = new Vector();
    // new oracle.jdbc.driver.OracleDriver();
    try {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    catch (ClassNotFoundException e) {
    System.out.println(e.getMessage());
    System.exit(-1);
    String url = "jdbc:odbc:c3-erp,s3,s3";
    public String getColumnName(int i) {
         if (i == 0)      {  return      "Email No"                     ;     } else
    if (i == 1)      {  return      "Email Line No.";} else
         if (i == 2)      {  return      "Customer";} else
         if (i == 3)      {  return      "Customer Name";} else
         if (i == 4)      {  return      "Date";} else
         if (i == 5)      {  return      "Batch No";} else
         if (i == 6)      {  return      "Customer PO";} else
         if (i == 7)      {  return      "Upgrade From Part";} else
         if (i == 8)      {  return      "Part Description";} else
         if (i == 9)      {  return      "Upgrade To Part";} else
         if (i == 10)      {  return      "Product Id";} else
         if (i == 11)      {  return      "Quantity";} else
         if (i == 12)      {  return      "Price";} else
         if (i == 13)      {  return      "Encypted Sum ID";} else
         if (i == 14)      {  return      "Decrypted Serial No";} else
         if (i == 15)      {  return      "Key";} else
         if (i == 16)      {  return      "Status";} else
         if (i == 17)      {  return      "Approved";} else
         if (i == 18)      {  return      "End Customer";} else
         if (i == 19)      {  return      "Sales Order";} else
         if (i == 20)      {  return      "SO Line";} else
         if (i == 21)      {  return      "Sales Order End Customer";} else
         if (i == 22)      {  return      "Sales Order End Customer Name";} else
         if (i == 23)      {  return      "Shipment";} else
         if (i == 24)      {  return      "Shipment Line";} else
         if (i == 25)      {  return      "Errors";} else
         if (i == 26)      { return       "From"; }
         else {return headers[i-1] ;}
    public int getColumnCount() { return colCount; }
    public int getRowCount() { return cache.size(); }
    //public Class getColumnClass(int c) {
    // return getValueAt(0, c).getClass();
    // overloaded isCellEditable method so that it returns true
    // in reference to a cell being editable.
    public boolean isCellEditable(int row, int col) { return true; }
    // overloaded setValyeAt which updates the data Vector and
    // calls the fireTableRowsUpdated() to notify any listeners
    // that data has changed and they need to redraw.
    public void setValueAt(Object value, int row, int col) {
    ((String[])cache.elementAt(row))[col] = (String)value;     
         fireTableRowsUpdated(row,row);     
    public void getInfo () {
    System.out.println("Row Count is : " + cache.size());
         System.out.println("Value at 0,0 is : " + getValueAt(0,0));
    //     boolean res = isCellEditable(0,0);
    //     System.out.println("The value of the Boolean result is : " + res);
    public Object getValueAt(int row, int col) {
    return ((String[])cache.elementAt(row))[col];
    // All the real work happens here!
    // In a real application, we'd probably perform the query in a separate thread.
    public void setQuery() {
    cache = new Vector();
    try {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    conn = DriverManager.getConnection ("jdbc:odbc:c3-erp","s3","s3");
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery("select a.email_no,a.email_ln_no,b.cust_no,null customer_name,null cdate,a.batch_no,b.purch_ord_no,a.user_part_no,null part_desc,a.user_upgraded_part_no,null prod_id,a.qty,a.price,a.encrypted_sum_id,a.decrypted_sum_id,a.approval_key,a.status_cd,decode(a.status_cd,'APPROVED','true','ERROR','false','PROCESSED','true') approved,null end_cust,null sales_ord,null so_line,null sales_ord_cust,null shipment ,null sales_end_cust_name ,null shipment_line,a.note,null fromcust from upgrade_req_key_s3 a,upgrade_req_s3 b where a.email_no = b.email_no order by a.email_no,a.email_ln_no");
    ResultSetMetaData meta = rs.getMetaData();
    colCount = meta.getColumnCount();
    String[] record = new String[27];      
    // Now we must rebuild the headers array with the new column name
    headers = new String[27];
    for (int h=0; h < 27; h++) {
    // headers[h-1] = meta.getColumnName(h);
         headers[h] = getColumnName(h);
    // and file the cache with the record from our query. This would
    // be practical if we were expecting a few million records to our
    // response query, but we are not so we can do this.
    while(rs.next()) {
         for (int i=0; i < colCount; i++) {
         record[i] = rs.getString(i + 1);
         cache.addElement(record);
         // Get the FIRST column of the table tableView
    // TableColumn column0 = table.getColumn(cache.elementAt(0));
    // Set the cell editor as non editable.
    // column0.setCellEditor(new EditableCellEditor(new JComboBox(), true));
    fireTableChanged(null); // notify everyone the we had a new table.
    catch (Exception e) {
    cache = new Vector(); // blank it out and keep going.
         e.printStackTrace();
    public static void main(String[] args) {
    VasuTest frame = new VasuTest();
    frame.pack();
    frame.setVisible(true);
    }

    When you click on the save button, you need to go through the model and retrieve the values getValueAt().
    Convert to whatever type you want since getValueAt() returns type Object and update the DB.

  • Problen in appearing  Jtable in JTextPAne ???

    Hi. to all,
    In thiscode i try to appear table in JTextPane .. There is a button "table" when you press on it the JDilog will appear in it you can specify the number of row and column to design the table ..... then when you press applay in JDilog the table should appear
    There is my try but it has error can't adjust it please any one tell me the correct way :
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTextPane;
    public class Table extends JFrame {
        private JTextPane textPane=new JTextPane();
        private JButton tableButton=new JButton("Table");
        private JPanel mainPanel=new JPanel();
        public Table(){
            mainPanel.setLayout(new BorderLayout());
            mainPanel.add(tableButton,BorderLayout.NORTH);
            tableButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                       new TableTest().setVisible(true);
                       textPane.setText(new TableTest().myTable);    // This ie error but i can not the way to set table in textpane
            mainPanel.add(textPane,BorderLayout.CENTER);
            getContentPane().add(mainPanel);
        public static void main(String[]args){
            Table table=new Table();
            table.setDefaultCloseOperation(Table.EXIT_ON_CLOSE);
            table.setSize(new Dimension(500,250));
            table.setLocationRelativeTo(null);
            table.setVisible(true);
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Point;
    import java.awt.event.ActionListener;
    import java.util.Hashtable;
    import javax.swing.BorderFactory;
    import javax.swing.Box;
    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JLabel;
    import javax.swing.JScrollPane;
    import javax.swing.JSpinner;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.border.TitledBorder;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.TableModel;
    public class TableTest extends JDialog {
        private JSpinner rowSpinner, colSpinner;
        private Box mainBox, rowSpinnerBox, colSpinnerBox;
        private JLabel rowLabel, columnLabel;
        private JTextField rowField, colField;
        private TitledBorder titledBorder;
        private JButton okButton,cancelButton;
        public TableModel myTable;
        private int[] row;
        private int[] col;
        public TableTest() {
            intializeSpinner();
            intializeBox();
            intializeLabel();
            intializeTextField();
            intializeButton();
            designView();
            row = (int[]) rowSpinner.getValue();
            col = (int[]) colSpinner.getValue();
            myTable = new TableModelTest(row, col);
            JTable table = new JTable(myTable);
            JScrollPane scrollPane = new JScrollPane(table);
            getContentPane().add(mainBox);
            getContentPane().add(scrollPane);
        private void intializeSpinner() {
            rowSpinner = new JSpinner();
            rowSpinner.setPreferredSize(new Dimension(100, 15));
            rowSpinner.setMaximumSize(new Dimension(100, 15));
            colSpinner = new JSpinner();
            colSpinner.setPreferredSize(new Dimension(100, 15));
            colSpinner.setMaximumSize(new Dimension(100, 15));
        private void intializeBox() {
            titledBorder = BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.BLACK, 3), "Insert table");
            mainBox = Box.createVerticalBox();
            mainBox.setBorder(titledBorder);
            rowSpinnerBox = Box.createHorizontalBox();
            colSpinnerBox = Box.createHorizontalBox();
        private void intializeLabel() {
            rowLabel = new JLabel("Insert row       :");
            columnLabel = new JLabel("Insert column :");
        private void intializeTextField() {
            rowField = new JTextField();
            rowField.setPreferredSize(new Dimension(100, 15));
            rowField.setMaximumSize(new Dimension(100, 15));
            colField = new JTextField(10);
            colField.setPreferredSize(new Dimension(100, 15));
            colField.setMaximumSize(new Dimension(100, 15));
        public void intializeButton(){
            okButton=new JButton("ok");
            cancelButton=new JButton("cancel");
        public void okButtonAddActionListener(ActionListener listener){
            okButton.addActionListener(listener);
        private void designView() {
            rowSpinnerBox.add(rowLabel);
            rowSpinnerBox.add(Box.createHorizontalStrut(5));
            rowSpinnerBox.add(rowField);
            rowSpinnerBox.add(Box.createHorizontalStrut(5));
            rowSpinnerBox.add(rowSpinner);
            //   rowSpinnerPanel.add(Box.createHorizontalGlue());
            colSpinnerBox.add(columnLabel);
            colSpinnerBox.add(Box.createHorizontalStrut(5));
            colSpinnerBox.add(colField);
            colSpinnerBox.add(Box.createHorizontalStrut(5));
            colSpinnerBox.add(colSpinner);
            //  colSpinnerPanel.add(Box.createHorizontalGlue());
            mainBox.add(rowSpinnerBox);
            mainBox.add(Box.createVerticalStrut(5));
            mainBox.add(colSpinnerBox);
            mainBox.add(Box.createVerticalGlue());
        class TableModelTest extends AbstractTableModel {
            public Hashtable lookUp;
            public int rows;
            public int columns;
            public int[] columnNames;
            public TableModelTest(int[] rows, int[] colNames) {
                this.rows = rows.length;
                this.columns = colNames.length;
                lookUp = new Hashtable();
                // this.columnNames = new int[columns];
                //  System.arraycopy(colNames, 0, this.columnNames, 0, columns);
            public int getRowCount() {
                return rows;
            public int getColumnCount() {
                return columns;
            public Object getValueAt(int rowIndex, int columnIndex) {
                return lookUp.get(new Point(rowIndex, columnIndex));
    }thanks in advance

    In thiscode i try to appear table in JTextPane Basically you add the component throught the JTextPane model which is the document; the new style contain the table as an attribute and registered with StyleConstants
    try this ( not tested)
    StyleContext context = new StyleContext();
        StyledDocument document = new DefaultStyledDocument(context);
        Style tableStyle = context.getStyle(StyleContext.DEFAULT_STYLE);
        TableModel model = new DefaultTableModel( new Object[]{"col1", "col2"}, 2);
        JTable table = new JTable(model);
        StyleConstants.setComponent(tableStyle, table);
        try {
          document.insertString(document.getLength(), "this will not show", tableStyle );
        } catch (BadLocationException badLocationException) {
          System.err.println("Oops");
        JTextPane textPane = new JTextPane(document);
        textPane.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(textPane);Why you do not build an html page which contains the table and set the text on the JTextPane to this page( String); then add hyperlinkListener so that you can rebuild the html table upon an predefined different links inside the html table
    Hope this could help. Please give me a shout in case you need further help
    Regards,
    Alan Mehio
    London,UK

  • Rebuilding an iTunes Library: How to Do It & What to Expect

    When iTunes is performing poorly--sluggishness, weird Podcast updating behavior, etc.--and you have tried everything, the prospect arises of rebuilding the iTunes Library. Instructions are simple. The idea is that the XML Library file will inevitably be "cleaner" than the possibly corrupted ITL file which is the file that iTunes edits in managing your iTunes content, and that after rebuilding your library from the xml file, you will have a fresh, clean ITL file. So, back up your machine. Then, go to your iTunes folder and TRASH the file "iTunes ibrary.itl" in the ~/Music/Tunes Folder. Do not empty the Trash. Also, MOVE the file "iTunes Music Library.xml" to your Desktop. Then start iTunes, select Import in the File Menu and select the iTunes Music Library.xml" that is on your Desktop. It could take hours depending on the size and you can just wait until the automatic rebuild is complete. Incidentally, I strongly recommend that you also disconnect your Mac from the Internet during this entire procedure; more on that later.
    Here is the caveat in rebuilding your Library: Apple purposely does not document the ITL file and will only say that most but not all of the information is written to the XML file, a file that technically only exists so that third party applications might be able to work with the iTunes Library. So what information will be missing after you rebuild you library from the XML file? Here is what I found:
    i. Music library and playlists: Good news, this remains intact. However, if your ITL file was corrupted you will discover some funny business. For example, there may be items such as Podcasts you have converted to Music files that reappear as Podcast files. You may find that there are files that are missing or files that you know you have, but seem to be missing from the new iTunes Library. There are various utilities or iTunes plugins such as those from the Doug's Applescripts site that will automate the discovery of these and other problems. Also, alas, the Date Added for all files will be today's date and time, not the day and time from as long as 10 years ago.
    Your iDeivces (iPods, iPhones, and iPads) will see this rebult library as entirely new. Thus, you will need to decide which Playlists, Artists, etc. to manage/import into each of your iDevices as though they are brand new. Basically, this is a time consuming slog, but you will need to do it. All will be erased and reimported even though they are already on your device. Dumb but there you have it.
    Movies, TV Shows, Audiobooks, Books, and Photos: These will remain intact with the same general caveats and iDeivce reimport issues as with the Music files. Namely, you will need to decide what you want to sync anew.
    Apps: Here is something that is not included n the XML file. Fortunately, the fix is to simply drag the contents of the Mobile Applications folder into iTunes and drop it. The import will be automatic. However, there may be multiple versions of some of your apps. about which iTunes will warn you and ask for a decision. Unfortunately, the file names of the multiple version apps are not given. So, my technique is to keep the newest version and leave the older one where it is, keeping a list of all of the ones you did not import. After you are done with the import you can go to the Apps window in iTunes, find the imported versions of those files, right click the icon, and then select "Show in Finder." You will then know the file name of the kept file and by inference can identify and decide what you want to do with the other version. In may cases it turns out to be a downrev version that can be moved elsewhere. However, it could also be a version for, say, your iPhone, that does not work with your iPad. In this case, import it and keep it. I would suggest keeping all of the seemingly orphaned apps around for awhile just in case you later find you need them.
    Good news: When you connect your iDevice(s) to iTunes you will find that iTunes accepts the apps already installed on them. You need do nothing further in most cases. Wonderful.
    Podcasts: Hopefully you heeded my advice to disconnect from the Internet. Because Podcasts seem to be the most problematic of the Library. If connected to the Internet you may, for example, find that the Podcasts will begin to download episodes willy nilly and contrary to your preferred settings. You don't need this right now! So, that said, the Podcasts will be restored including Podcasts that may not currently have any current episodes in them. However, you may find that you will need to Subscribe to some podcasts even though you already had a subscription. In fact, some this having to Subscribe may persist over a few days. Just go ahead and do it of you want the subscriptions. Also, make sure that the Settings for each Podcast are as you like them. You can then connect your iDevice and set it up just as though it is new and iTunes will tediously build your new Podcast library on your iDevice just as with your Music files. Of course you will need to do this for each of your iDevices.
    One other thing to watch in connection with Podcasts is your Music section. I ended up with almost 3000 podcast episodes that were not current that were listed in my Music section but greyed out and identified as Streaming content. Rooting these out was a simple matter of selecting for "Genre" and deleting all of the genre "Streaming" from the Library. This list had nothing to do with the settings for Podcasts. It may be a bug or just one of the symptoms of corruption of my particular original ITL file. Notably, I was connected to the Internet when I rebuilt my Library and this is one of the reasons I highly recommend disconnecting before the rebuild. However, this gremlin could occur when you do reconnect. I don't know and I am not about to test for it, So watch for this or for other funny business.
    Cloud/iTunes Match stuff: If you had turned on iTunes Match I have no help for you. I have never used it. Intuitively, I suspect this could be an epic mess in the context of rebuilding your Library from the XML file. But maybe not--hopefully not!
    iPads, iPhones and the Library: In my case it appears that much of the problem with my iTunes Library file had to do with anomalies and differences betwen what my iTunes Library thought was on a device and what was actually there. Do not be surprised if you feel that you need to restore one of your iDevices. However, prior to doing so consider making an encrypted backup of your iDevice. Encrypted backups include settings and other information that could take hours to reenter and is not included on regular style backups. After a restore, you can be sure that this restoration will be the canonical status of both what is on your iDevice and what iTunes thinks is on your device. Thus you can work with this and then modify it confidently.
    Epilogue: For me, this procedure restored performance to iTunes that had been getting steadily worse for about two years. The new ITL file was about 1MB smaller than the old one. Incidentally, even though the ITL fle was modified by iTunes with most major iTunes versions, it traced its provenance back to 2004 when I got my first iPod. That is very long time and so the development of errors and weirdness is not terribly surprising.

    Because the Nano was previous synced to another comuter/iTunes library.
    See the following:
    Syncing to a "New" Computer or replacing a "crashed" Hard Drive: Apple Support Communities

  • How do I get at a JTable on a JInternalFrame?

    I've been working on this Multiple Document Interface application, and things have been great up to this point. The user chooses to run a "report" and then selects an entity to get the info for. I then hit the database. Each row returned from the database query goes into it's own data object, which is added to an ArrayList in my custom table model, and that ArrayList is used to generate the JTable, which is then added to a ScrollPane, which is then added to the JInternalFrame, which is then added to the JDesktop pane. Good stuff, right?
    I'm now trying to add Print functionality, and I'm at a loss. What I want to do is have the user do the standard File->Print, which will print out the JTable on the currently selected inner frame. I can get a JTable to print using JTable.print(). What I can't do is find a way to get the JTable from the selected frame.
    I can get the selected frame using desktop.getSelectedFrame(), but I'm at a loss as to what to do next. I've played around with .getComponent, but I'm not having any luck. the components returned don't seem to do me any good...for example, JViewPort?
    Am I going about this the wrong way? Have I poorly designed this? Am I missing the obvious?
    Thanks,
    -Adam

    Well, if you only have a single component on the internal frame then you can use getComponent(0). But then you need to go up the parent chain to get the actual table. You will initially get the JScrollPane, then use that to get the JViewport and then use that to get the viewport component.
    Another option is to extend the JInternalFrame class and insted using the add method to add a component you create get/setTable(...) methods. Then you can save the table as a class variable before adding it the scrollpane and adding the scrollpane to the internal frame.

Maybe you are looking for

  • Different totals based on dates (month vs date range)

    I know I've seen this before, but I can't find the thread. I have a column in a fact table for price. When I add price and the month (eg April 2012) from the time dimension, it totals one number, but when I remove the month, and add a date range (4/1

  • Installing Mac OS X on an external firewire hard drive.

    No matter what I try, I cannot get my Mac mini to boot from the SuperDrive, in order to install the Mac OS X operating system onto my external firewire hard drive... The Mac mini always recognises the external firewire HD, each time the system boots-

  • Deleted crystal report still showing in Authorization window

    Hi there, I have a report created in crystal report and imported into SAP B1. Then I deleted it from Report and Layout Manager. However, the report can still be seen from Authorizations window. It canu2019t be seen from Main Menu though. Is there any

  • Text printing in reports

    Hi Experts,     I am putting some text in the text tab of the Purchase order Transaction ME21N. When I am taking Script for that Purchase order that text is coming in the printing.But my problem is that same text I captured into Reports.Suppose if I

  • Extending Audio file throughout multiple menus.

    Here is what I am trying to do: I have a main menu and two submenus. I would like to use a single audio file to play throughout my menus. Is this possible to achieve some how???? I am using Encore 2.0. Thank you in advance for your help. Serge