Updating a JTable by hiding/displaying columns

I have a customizable JTable where I display/hide columns according to a users' selection criteria. My code works fine for hiding/displaying columns if the Jtable is opened for the fist time, but doesnot work if I want to hide columns in already displayed table.How do I do it?? Any clue?? I tried
myTabModel.fireTableDataChanged();
but this only works for updating the table data...it does not hide columns for me... when I hide column I just remove desired column like this:
myTable.removeColumn(myTable.getColumn("Column 3"));

Here is the sample code I tried. It worked without any invalidate or repaint or updateUI(). generated using NetBeans
check for <==== for the line of code doing this
* TableTest.java
* Created on October 9, 2002, 1:42 PM
* @author  Anki Reddy Nelaturu
public class TableTest extends javax.swing.JFrame {
    /** Creates new form TableTest */
    public TableTest() {
        initComponents();
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
    private void initComponents() {
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();
        menuBar = new javax.swing.JMenuBar();
        fileMenu = new javax.swing.JMenu();
        openMenuItem = new javax.swing.JMenuItem();
        saveMenuItem = new javax.swing.JMenuItem();
        saveAsMenuItem = new javax.swing.JMenuItem();
        exitMenuItem = new javax.swing.JMenuItem();
        editMenu = new javax.swing.JMenu();
        cutMenuItem = new javax.swing.JMenuItem();
        copyMenuItem = new javax.swing.JMenuItem();
        pasteMenuItem = new javax.swing.JMenuItem();
        deleteMenuItem = new javax.swing.JMenuItem();
        helpMenu = new javax.swing.JMenu();
        contentsMenuItem = new javax.swing.JMenuItem();
        aboutMenuItem = new javax.swing.JMenuItem();
        getContentPane().setLayout(null);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                exitForm(evt);
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
        jScrollPane1.setViewportView(jTable1);
        getContentPane().add(jScrollPane1);
        jScrollPane1.setBounds(80, 30, 230, 120);
        jButton1.setText("jButton1");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
        getContentPane().add(jButton1);
        jButton1.setBounds(170, 180, 81, 26);
        jTextField1.setText("jTextField1");
        getContentPane().add(jTextField1);
        jTextField1.setBounds(60, 190, 63, 20);
        fileMenu.setText("File");
        openMenuItem.setText("Open");
        fileMenu.add(openMenuItem);
        saveMenuItem.setText("Save");
        fileMenu.add(saveMenuItem);
        saveAsMenuItem.setText("Save As ...");
        fileMenu.add(saveAsMenuItem);
        exitMenuItem.setText("Exit");
        exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitMenuItemActionPerformed(evt);
        fileMenu.add(exitMenuItem);
        menuBar.add(fileMenu);
        editMenu.setText("Edit");
        cutMenuItem.setText("Cut");
        editMenu.add(cutMenuItem);
        copyMenuItem.setText("Copy");
        editMenu.add(copyMenuItem);
        pasteMenuItem.setText("Paste");
        editMenu.add(pasteMenuItem);
        deleteMenuItem.setText("Delete");
        editMenu.add(deleteMenuItem);
        menuBar.add(editMenu);
        helpMenu.setText("Help");
        contentsMenuItem.setText("Contents");
        helpMenu.add(contentsMenuItem);
        aboutMenuItem.setText("About");
        helpMenu.add(aboutMenuItem);
        menuBar.add(helpMenu);
        setJMenuBar(menuBar);
        pack();
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        jTable1.removeColumn(jTable1.getColumnModel().getColumn(Integer.parseInt(jTextField1.getText())));        // <========
    private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
        System.exit(0);
    /** Exit the Application */
    private void exitForm(java.awt.event.WindowEvent evt) {
        System.exit(0);
     * @param args the command line arguments
    public static void main(String args[]) {
        new TableTest().show();
    // Variables declaration - do not modify
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JMenu fileMenu;
    private javax.swing.JMenuItem exitMenuItem;
    private javax.swing.JButton jButton1;
    private javax.swing.JMenuItem saveAsMenuItem;
    private javax.swing.JMenuItem saveMenuItem;
    private javax.swing.JMenuItem copyMenuItem;
    private javax.swing.JMenuItem pasteMenuItem;
    private javax.swing.JMenuItem cutMenuItem;
    private javax.swing.JMenuItem openMenuItem;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JMenu editMenu;
    private javax.swing.JMenuItem aboutMenuItem;
    private javax.swing.JMenuItem contentsMenuItem;
    private javax.swing.JMenu helpMenu;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JMenuItem deleteMenuItem;
    private javax.swing.JTable jTable1;
    // End of variables declaration
}

Similar Messages

  • JTable can't display column names and scroll bar in JDialog !!

    Dear All ,
    My flow of program is JFrame call JDialog.
    dialogCopy = new dialogCopyBay(frame, "Bay Name Define", true, Integer.parseInt(txtSourceBay.getText()) ,proVsl ,300 ,300);
    dialogCopy.setBounds(0, 0, 300, 300);
    dialogCopy.setVisible(true);        Then,I set the datasource of JTable is from a TableModel.
    It's wild that JTable can diplay the data without column names and scroll bar.
    I have no idea what's going wrong.Cause I follow the Sun Tutorial to code.
    Here with the code of my JDialog.
    Thanks & Best Regards
    package com.whl.panel;
    import com.whl.vslEditor.vslDefine;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.Frame;
    import javax.swing.JDialog;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.table.AbstractTableModel;
    public class dialogCopyBay extends JDialog {
        vslDefine glbVslDefine;
        int lvCnt = -1;
        JTable tableCopyBay;
        int bgnX = 0;
        int bgnY = 30;
        int tableWidth = 100;
        int tableHeight = 100;
        public dialogCopyBay(Frame frame, String title, boolean modal, int sourceBay,
                vslDefine pVslDefine, int ttlWidth, int ttlHeight) {
            super(frame, title, true);
            Container contentPane = getContentPane();
            System.out.println("dialogCopyBay Constructor");
            glbVslDefine = null;
            glbVslDefine = pVslDefine;
            copyBayModel copyBay = new copyBayModel((glbVslDefine.getVslBayStructure().length - 1),sourceBay);
            tableCopyBay = new JTable(copyBay);
            tableCopyBay.setPreferredScrollableViewportSize(new Dimension(tableWidth, tableHeight));
            JScrollPane scrollPane = new JScrollPane(tableCopyBay);
            scrollPane.setViewportView(tableCopyBay) ;
            tableCopyBay.setFillsViewportHeight(true);
            tableCopyBay.setBounds(bgnX, bgnY, tableWidth, tableHeight);
            tableCopyBay.setBounds(10, 10, 100, 200) ;
            contentPane.setLayout(null);
            contentPane.add(scrollPane);
            contentPane.add(tableCopyBay);
        class copyBayModel extends AbstractTableModel {
            String[] columnNames;
            Object[][] dataTarget;
            public copyBayModel(int rowNum ,int pSourceBay) {
                columnNames = new String[]{"Choose", "Bay Name"};
                dataTarget = new Object[rowNum][2];
                for (int i = 0; i <= glbVslDefine.getVslBayStructure().length - 1; i++) {
                    if (pSourceBay != glbVslDefine.getVslBayStructure().getBayName() &&
    glbVslDefine.getVslBayStructure()[i].getIsSuperStructure() == 'N') {
    lvCnt = lvCnt + 1;
    dataTarget[lvCnt][0] = false;
    dataTarget[lvCnt][1] = glbVslDefine.getVslBayStructure()[i].getBayName();
    System.out.println("lvCnt=" + lvCnt + ",BayName=" + glbVslDefine.getVslBayStructure()[i].getBayName());
    public int getRowCount() {
    return dataTarget.length;
    public int getColumnCount() {
    return columnNames.length;
    public String getColumnName(int col) {
    return columnNames[col];
    public Object getValueAt(int rowIndex, int columnIndex) {
    return dataTarget[rowIndex][columnIndex];
    public Class getColumnClass(int c) {
    return getValueAt(0, c).getClass();
    public boolean isCellEditable(int row, int col) {
    if (col == 1) {
    // Bay Name Not Allow To modify
    return false;
    } else {
    return true;
    public void setValueAt(Object value, int row, int col) {
    dataTarget[row][col] = value;
    fireTableCellUpdated(row, col);

    Dear DB ,
    I am not sure what you mean.
    Currently,I don't undestand which code is error.
    And I also saw some example is add JTable and JScrollPane in JDialog.
    Like Below examle in Sun tutorial
    public class ListDialog extends JDialog implements MouseListener, MouseMotionListener{
        private static ListDialog dialog;
        private static String value = "";
        private JList list;
        public static void initialize(Component comp,
                String[] possibleValues,
                String title,
                String labelText) {
            Frame frame = JOptionPane.getFrameForComponent(comp);
            dialog = new ListDialog(frame, possibleValues,
                    title, labelText);
         * Show the initialized dialog. The first argument should
         * be null if you want the dialog to come up in the center
         * of the screen. Otherwise, the argument should be the
         * component on top of which the dialog should appear.
        public static String showDialog(Component comp, String initialValue) {
            if (dialog != null) {
                dialog.setValue(initialValue);
                dialog.setLocationRelativeTo(comp);
                dialog.setVisible(true);
            } else {
                System.err.println("ListDialog requires you to call initialize " + "before calling showDialog.");
            return value;
        private void setValue(String newValue) {
            value = newValue;
            list.setSelectedValue(value, true);
        private ListDialog(Frame frame, Object[] data, String title,
                String labelText) {
            super(frame, title, true);
    //buttons
            JButton cancelButton = new JButton("Cancel");
            final JButton setButton = new JButton("Set");
            cancelButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    ListDialog.dialog.setVisible(false);
            setButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    ListDialog.value = (String) (list.getSelectedValue());
                    ListDialog.dialog.setVisible(false);
            getRootPane().setDefaultButton(setButton);
    //main part of the dialog
            list = new JList(data);
            list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
            list.addMouseListener(new MouseAdapter() {
                public void mouseClicked(MouseEvent e) {
                    if (e.getClickCount() == 2) {
                        setButton.doClick();
            JScrollPane listScroller = new JScrollPane(list);
            listScroller.setPreferredSize(new Dimension(250, 80));
    //XXX: Must do the following, too, or else the scroller thinks
    //XXX: it's taller than it is:
            listScroller.setMinimumSize(new Dimension(250, 80));
            listScroller.setAlignmentX(LEFT_ALIGNMENT);
    //Create a container so that we can add a title around
    //the scroll pane. Can't add a title directly to the
    //scroll pane because its background would be white.
    //Lay out the label and scroll pane from top to button.
            JPanel listPane = new JPanel();
            listPane.setLayout(new BoxLayout(listPane, BoxLayout.Y_AXIS));
            JLabel label = new JLabel(labelText);
            label.setLabelFor(list);
            listPane.add(label);
            listPane.add(Box.createRigidArea(new Dimension(0, 5)));
            listPane.add(listScroller);
            listPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
    //Lay out the buttons from left to right.
            JPanel buttonPane = new JPanel();
            buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.X_AXIS));
            buttonPane.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
            buttonPane.add(Box.createHorizontalGlue());
            buttonPane.add(cancelButton);
            buttonPane.add(Box.createRigidArea(new Dimension(10, 0)));
            buttonPane.add(setButton);
    //Put everything together, using the content pane's BorderLayout.
            Container contentPane = getContentPane();
            contentPane.add(listPane, BorderLayout.CENTER);
            contentPane.add(buttonPane, BorderLayout.SOUTH);
            pack();
        public void mouseClicked(MouseEvent e) {
            System.out.println("Mouse Click");
        public void mousePressed(MouseEvent e) {
            throw new UnsupportedOperationException("Not supported yet.");
        public void mouseReleased(MouseEvent e) {
            throw new UnsupportedOperationException("Not supported yet.");
        public void mouseEntered(MouseEvent e) {
            throw new UnsupportedOperationException("Not supported yet.");
        public void mouseExited(MouseEvent e) {
            throw new UnsupportedOperationException("Not supported yet.");
        public void mouseDragged(MouseEvent e) {
            throw new UnsupportedOperationException("Not supported yet.");
        public void mouseMoved(MouseEvent e) {
            throw new UnsupportedOperationException("Not supported yet.");
         * This is here so that you can view ListDialog even if you
         * haven't written the code to include it in a program.
    }

  • Updates to JTables and resizing of columns

    I'm building an application that has many tables that all use table models that I have created. All of the table models extend DefaultTableModel. Before entering any data in the tables i set the size of the columns. Below is an example of how I do this...
          //tcm = table column model
          tcm.getColumn(0).setPreferredWidth(100);
          tcm.getColumn(1).setPreferredWidth(100);
          tcm.getColumn(2).setPreferredWidth(100);
          tcm.getColumn(3).setPreferredWidth(100);
          tcm.getColumn(4).setPreferredWidth(172);
          tcm.getColumn(5).setPreferredWidth(172);
          My problem is everytime I update the table with new data the columns keep adjusting themselves to the width of the largest piece of data in the particular column. In order to keep the size of the columns I want I've been resizing the columns with the above code everytime I update the table. Can someone tell me how to set the column sizes once and have them remain that way?

    I'm sorry to hear that you're having problems customising your Spotify for Mac application. I'm sure Spotify do value your custom and will take your suggestion to return this feature. For now, I think posting your idea in the Ideas forum would be best to get your idea out there and upvoted by fellow community members wishing for the return of this feature. You can submit your idea at: https://community.spotify.com/t5/forums/postpage/board-id/ideas_submissions Take care and let me know how it goes!

  • Hiding few columns before displaying alv grid output

    Hi All,
    I struck up at hiding few columns before displaying alv output. I have used used FM: REUSE_ALV_GRID_DISPLAY. By using this i am displaying 29 fields to the output. But before displaying the output i want to hide few columns among them, and also those fields have to be avialable for further selection by the user by using layout.
    Kindly help me in this,
    Regards
    Srinivas K

    Hi,
    In field catalog set NO_OUT='X' for all the columns you want to hide. They will be available when changing layout for ALV, so you can show them at any time.
    Regards
    Marcin

  • Updating a JTable when using an AbstractTableModel

    Hi,
    I have tried to create a JTable with an AbstractTableModel but I am obviously missing something in all the tutorials and examples as I cannot get the table to update when using my model.
    My application reads data in from a CSV file that is selectable at run time, but I have written a small app that demonstrates the problem I am having.
    If you uncomment the DefaultTableModel lines of code all is OK, but I need to use my Abstract Class as I intend to colour certain rows and add a Boolean column, that I would like to display as a CheckBox and not just the String representation.
    Any help would be great as I am tearing my hair out here!!
    My Test Class
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.util.*;
    public class TestTable extends JFrame implements ActionListener
    private JPanel jpTestTable = new JPanel();          
    private Vector vColumnNames = new Vector();
    private Vector vCellValues = new Vector();
    private DefaultTableModel dtmTestTable;
    private CustomTableModel ctmTestTable;
    private JTable jtTestTable;
    private JScrollPane jspTestTable;
    private JButton jbGo = new JButton();
         public TestTable()
         dtmTestTable = new DefaultTableModel();
         ctmTestTable = new CustomTableModel();
         //jtTestTable = new JTable( dtmTestTable );  //using this instead of my CustomModel works fine
         jtTestTable = new JTable( ctmTestTable );
         jtTestTable.setAutoCreateRowSorter(true);
         jtTestTable.setFillsViewportHeight( true );
         jspTestTable = new JScrollPane( jtTestTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS ,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER );
         jspTestTable.setBounds( 10, 10, 350, 400 );
         jspTestTable.setBorder( BorderFactory.createLoweredBevelBorder() );
         jbGo.setText( "Go" );
         jbGo.setBorder( BorderFactory.createRaisedBevelBorder() );
         jbGo.setBounds( 125, 430, 100, 25 );
         jbGo.addActionListener(this);
         jpTestTable.setLayout( null );
         jpTestTable.setBounds( 0, 0, 375, 500 );     
         jpTestTable.add( jspTestTable );
         jpTestTable.add( jbGo );
         this.setTitle( "Test Table" );
         this.getContentPane().setLayout( null );
         this.setBounds( 200, 50, 375, 500 );
         this.getContentPane().add( jpTestTable );
         this.setResizable( false );
         public void actionPerformed( ActionEvent e )
         updateTable();
         public void updateTable()
         vColumnNames.add( "Please" );
         vColumnNames.add( "work" );
         vColumnNames.add( "you" );
         vColumnNames.add( "git!" );
         vColumnNames.trimToSize();
         Vector vRow = new Vector();
              for( int i = 0; i < 10; i++ )
                   for( int x = 0; x < vColumnNames.size(); x++ )
                        vRow.add( "" + i + "" + x );
              vCellValues.add( vRow );
         //dtmTestTable.setDataVector( vCellValues, vColumnNames );  //using this instead of my CustomModel works fine
         ctmTestTable.setDataVector( vCellValues, vColumnNames );
         public void processWindowEvent(WindowEvent e)
         super.processWindowEvent(e);
              if(e.getID() == WindowEvent.WINDOW_CLOSING)
              exit();
         public void exit()
         System.exit( 0 );     
         public static void main(String args[])
         TestTable tt = new TestTable();
         tt.setVisible( true );
    }And my CustomTableModel Class
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.*;
    import java.util.*;
    public class CustomTableModel extends AbstractTableModel
    protected Vector columnIdentifiers  = new Vector();
    protected Vector dataVector = new Vector();
         public CustomTableModel()
         public CustomTableModel( Vector data, Vector columnNames )
         setDataVector( data, columnNames );
         public int getColumnCount()
         return columnIdentifiers.size();
         public int getRowCount()
         return dataVector.size();
         public String getColumnName( int col )
         return "" + columnIdentifiers.get( col );
         public Object getValueAt( int row, int col )
         Vector vRow = new Vector();
         vRow = (Vector) dataVector.get( row );
         return (Object) vRow.get( col );
         public Class getColumnClass(int c)
         return getValueAt(0, c).getClass();
         public boolean isCellEditable(int row, int col)
              if (col < 2)
                   return false;
              else
                   return true;
         public void setValueAt( Object value, int row, int col )
         Vector vTemp = (Vector) dataVector.get( row );
         Vector<Object> vRow = new Vector<Object>();
              for( int i = 0; i < vTemp.size(); i++ )
                   vRow.add( (Object) vTemp.get( i ) );
         vRow.remove( col );
         vRow.add( col, value );
         vRow.trimToSize();     
         dataVector.remove( row );
         dataVector.add( row, vRow );
         dataVector.trimToSize();
         fireTableCellUpdated(row, col);
         public void setDataVector( Vector data, Vector columnNames )
         columnIdentifiers  = (Vector) columnNames.clone();
         dataVector = (Vector) data.clone();
         fireTableDataChanged();
    }I have just tried adding the following code after reading another example, but same result - arrrrrrrgggggggghhhhhhhhh!!!!
    ctmTestTable = (CustomTableModel) jtTestTable.getModel();
    ctmTestTable.fireTableDataChanged();Edited by: Mr_Bump180 on Jul 28, 2008 2:51 PM

    Hi camickr,
    Well that is good news as my Abstact class is about as much good as an ashtray on a motorbike. I think I must have misread or misunderstood the Table Tutorials as I thought I had to use an Abstrat class to get colurs based on conditions and to get Check Boxes to represent Boolean variables.
    I am clearly struggling with this concept - which I have never used before - do you know of any tutorials, that explain how to update a JTable with file data at runtime, as all the ones I have looked at set it as part of the java code - which is no good to me.
    Also am I overriding the DefaultTableModel Class correctly - I have written a seperate Model class but wounder if I need to include it in with my JTable class. I was trying to make it generic so I didn't have to write one for each JTable - but as I can't get it to work I should perhaps try to walk before I run.
    I'm not asking for the code, but just a guide to how close I am to where I want to be, and some links to tutorials that are closer to what I want to achieve. I will reread the Java Table Tutorial tonight - and you never know the penny may drop all on it's own this time!!!
    Thanks

  • Hiding a column while keeping the data in the TableModel

    Hello
    I am reading data in from a database and I add the data from the resultSet to
    a vector of vectors.
    e.g my table
    user_id | user_fname | user_lname | prj_id | prj_name
    I am reading in the above information but I dont want to
    display the id fields i.e
    the user_id and
    the prj_id fields
    to the user but I need to keep them in the vector inside my tablemodel
    for futher database manipulation.
    I've looked at threads saying to set the width of the column to 0 is this the best way???
    Could someone please share with me a way to do the above.
    Thank you very much

    Figure out how to call the removeColumn method on your JTable. Calling the method only removes the column viewed (JTable), not the actual column in the (DefaultTable) Model.
    If you go for the proposed "do it so small it cant be seen" solution, you have to "lock" the colum width so users can't do it bigger manually with the mouse...

  • Changing the Column Header and Hiding the Column dynamically???

    Hi friends..
    I'm new to OBIEE field. I'm working in a OBIEE project that requires to dynamically change the column header, and dynamically hide the column depending on the prompt value.
    I know we can dynamically change the table header using the presentation variable but I couldn't do that same thing with column header.
    I searched some forums that suggest to use java script for this purpose but I'm not able to do the same also. If anyone had same issue before please help.

    toony, I'm not sure it's possible to do all that you want exactly the way you want, but here are some ideas you can pursue.
    To dynamically change column headers without javascript, check this blog out...
    http://oraclebizint.wordpress.com/2008/01/25/oracle-bi-ee-101332-dynamic-column-headers-using-presentation-variables-sets-and-conditional-formatting/
    As far as dynamically hiding a column, I don't think you can do this, but since you don't provide any details on how the PV is supposed to hide a column based on the value, are you talking about hiding a column for one PV value and another (different) column for a different PV value? Or are you talking about hiding one column when a PV has certain values and displaying it when the PV has a different set of values?
    I have managed to create both scenarios via a work-around, but the procedures require some writing so I don't want to put both. Please detail how you want your PV to "hide" a column or columns.
    P.S. I don't think column selectors will do the trick for you. Basically column selectors work like this: Say you have a report using Sales Region ID, Region Name, and Sales. Now let's say you want the user to choose if he/she wants to see annual sales, or quarter sales or weekly sales, etc. The column selector view would allow you to put the various columns (Year Sales, Quarter Sales, Weekly Sales) as an option the user can select. Once selected, the sales figure will change for the time period selected. For an example of how this is done, check out the section in this "Oracle by Example" link.
    Waited too long to publish this... Madan beat me to it, so there is some overlap here...
    http://www.oracle.com/technology/obe/obe_bi/bi_ee_1013/saw/saw.html
    Edited by: LC143 on Oct 27, 2008 9:21 AM

  • How to Update the JTable Content

    Hi Friends
    In my Program i have a Form having a JTable with shows some content on it. Now when the User Click on the Row it will ask where he wants to Edit that rows content. If the User gives Yes. then the Another JDialog opens with the Selected rows Data.
    Now when the User makes changes in the Data and Clicks on the Edit Button. It Should Show the Entered Data on the JTable immediatly.
    I am Posting my working Code. It works fine. But only the Updating the Newly entered Data to the JTable is not done.
    import javax.swing.*;
    import java.util.*;
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.table.*;
    public class EditTable extends JDialog implements ActionListener,MouseListener
         private JRadioButton rby,rbn,rbr,rbnore,rbnorest;
         private ButtonGroup bg;
         private JPanel exportpanel;
         private JButton btnExpots;
         JTable table;
         JScrollPane scroll;
         public EditTable()throws Exception
              setSize(550,450);
              setTitle("Export Results");
              this.setLocation(100,100);
              String Heading[]={"BOOK ID","NAME","AUTHOR","PRICE"};
              String records[][]={{"B0201","JAVA PROGRAMING","JAMES","1234.00"},
                               {"B0202","SERVLET PROGRAMING","GOSLIN","1425.00"},
                               {"B0203","PHP DEVELOPMENT","SUNITHA","123"},
                               {"B0204","PRIAM","SELVI","1354"},
                               {"B0205","JAVA PROGRAMING","JAMES","1234.00"},
                               {"B0206","SERVLET PROGRAMING","GOSLIN","1425.00"},
                               {"B0207","PHP DEVELOPMENT","SUNITHA","123"},
                               {"B0208","PRIAM","SELVI","1354"}};
              btnExpots= new JButton("Export");
              btnExpots.addActionListener(this);
              btnExpots.setBounds(140,200,60,25);
              table = new JTable();
              table.addMouseListener(this);
              scroll=new JScrollPane(table);
              ((DefaultTableModel)table.getModel()).setDataVector(records,Heading);
              System.out.println(table.getModel());
              exportpanel= new JPanel();
              exportpanel.add(btnExpots,BorderLayout.SOUTH);
              exportpanel.add(scroll);
              getContentPane().add(exportpanel);
              setVisible(true);
          public void actionPerformed(ActionEvent ae)
         public static void main(String arg[]) throws Exception
              EditTable ex= new EditTable();
           public void mouseClicked(MouseEvent me)
              Object obj=me.getSource();
              if(obj==table)
                        JTable source=(JTable)me.getSource();
                        int row = source.rowAtPoint(me.getPoint());
                        int column = source.columnAtPoint(me.getPoint());
                        System.out.println("Working Point"+row+"and"+column);
                        Object value1 = source.getValueAt(row,0);     
                        Object value2 = source.getValueAt(row,1);
                        Object value3 = source.getValueAt(row,2);
                        Object value4 = source.getValueAt(row,3);
                        String bkId=value1.toString();
                        String bkNm=value2.toString();
                        String bkAuthr=value3.toString();
                        String bkAuthrCd=value4.toString();
                        int opt = JOptionPane.showConfirmDialog(this,"Do you Really Want to Edit this Book?","Edit Books",JOptionPane.YES_NO_OPTION);
                        if(opt==JOptionPane.YES_OPTION)
                             try
                                  editForm  editfrm= new editForm ();
                                  editfrm.setVisible(true);
                                  editfrm.setVisible(true);
                                  editfrm.txtbookID.setText(""+bkId);
                                  editfrm.txtbookName.setText(""+bkNm);
                                  editfrm.txtbookAuthorName.setText(""+bkAuthr);
                                  editfrm.txtPrice.setText(""+bkAuthrCd);
                             catch(Exception ex)
                                  ex.printStackTrace();
        public void mousePressed(MouseEvent e) {
        public void mouseReleased(MouseEvent e) {
        public void mouseEntered(MouseEvent e) {
        public void mouseExited(MouseEvent e) {
    class editForm extends JDialog implements ActionListener
         JLabel lblbookID,lblbookName,lblbookAuthorName,lblPrice;
         JTextField txtbookID,txtbookName,txtbookAuthorName,txtPrice;
         JButton btnEdit,btnClose;
         JPanel editPanel;
              public editForm()
                   setSize (350,400);
                   this.setTitle("Edit Books");
                   this.setLocation(100,135);
                   lblbookID= new JLabel("Book ID:");
                   lblbookID.setBounds (15, 15, 100, 20);
                   lblbookName= new JLabel("Book Name:");
                   lblbookName.setBounds (15, 45, 100, 20);
                   lblbookAuthorName= new JLabel("Author Name:");
                   lblbookAuthorName.setBounds (15, 75, 100, 20);
                   lblPrice= new JLabel("Price:");
                   lblPrice.setBounds (15, 105, 100, 20);
                   Font fnt = new Font("serif",Font.BOLD,18);
                   txtbookID= new JTextField();
                   txtbookID.setFont(fnt);
                   txtbookID.setEditable(false);
                   txtbookID.setBounds (120, 15, 175, 20);
                   txtbookName= new JTextField();
                   txtbookName.setFont(fnt);
                   txtbookName.setBounds (120, 45, 175, 20);
                   txtbookAuthorName= new JTextField();
                   txtbookAuthorName.setFont(fnt);
                   txtbookAuthorName.setBounds (120, 75, 175, 20);
                   txtPrice= new JTextField();
                   txtPrice.setFont(fnt);
                   txtPrice.setBounds (120, 105, 175, 20);
                   btnEdit = new JButton("Edit");
                   btnEdit.addActionListener(this);
                   btnEdit.setBounds (50, 295, 100, 25);
                   btnEdit.setMnemonic(KeyEvent.VK_E);
                   btnClose= new JButton("Close");
                   btnClose.addActionListener(this);
                   btnClose.setBounds (170, 295, 100, 25);
                   btnClose.setMnemonic(KeyEvent.VK_C);
                   editPanel = new JPanel();
                   editPanel.setLayout(null);
                   editPanel.add(lblbookID);
                   editPanel.add(lblbookName);
                   editPanel.add(lblbookAuthorName);
                   editPanel.add(lblPrice);
                   editPanel.add(txtbookID);
                   editPanel.add(txtbookName);
                   editPanel.add(txtbookAuthorName);
                   editPanel.add(txtPrice);
                   editPanel.add(btnEdit);
                   editPanel.add(btnClose);
                   getContentPane().add(editPanel);
                public void actionPerformed(ActionEvent ae)
    }Could anyone Please Run my code and Help me to Update the JTable Record.
    Thank you for your Help
    Cheers
    Jofin

    Your EditForm needs acces to the TableModel and the current row you are editing. Then when the user clicks the save button you simply use the TableModel.setValueAt(...) method to update the model and the table will be repainted automatically.

  • Refreshing JTable contents (rows and columns) handling.

    Hi,
    I have a general question related to refreshing the contents of JTable and handling some application specific requirements.In our application we are planning to refresh the contents of JTable automatically after certain period of time by fetching data from database and update the JTable contents or user has clicked refresh button.
    But following scenarios we are planning to handle when refresh is called automatically or user has clicked refresh button.
    1) User is working with data of JTable. Like rows of JTable has checkBoxes and user selects them and doing operation like viewing the details of selected rows in new details dialog. So if refreshing is done then the selection will be lost if I update the whole data in JTable.
    a)Will it be possible to append the data at the end of JTable rows without disturbing the existing JTable contents.
    b) Is it feasible to compare the data of existing rows and newly fetched rows and update only the rows whose values are changed in database or update specifically updated columns. But this comparision for finding changed values will result in performance problems.So are there any other alternatives of doing this, ideas are most welcome.
    c) Simple way is to alert the user that data will be updated and everything will be refreshed will be the choice in worst case.
    I guess many may have encountered such problems and may have solved it depending on the product requirements.
    Ideas and suggestions are most welcome.
    Regards.

    Hi,
    Here are my views and my assumptions.
    Assumptions :
    1) Your JTable is populated with list of Objects.
    2) Your tables in database is having columns like created date, created time, updated date updated time
    3) Order by clause for all the time will remain same.
    If these assumptions are correct then I think you can achieve your goal.
    Here how it is.
    Your application session will maintain last db hit time and will maintain for every hit that applicate made to fetch data from db.
    When object is created on the server side once it fetch data from table it will compare the created date/time or update date/time with the session varibale that holds last visit date/time. Based on this flag need to be set to indicate if this item is added/updated/deleted since last visit.
    And when all these object is returned to your client, the table model will iterate through the list and based on object index in the list and and if object is changed will update only that perticular row.
    Hope this is what you want to achieve.
    Regards

  • Insert/update japanese langunage data in a column of datatype varchar2(..)

    Hello,
    I am using ORACLE DATABASE 11g (EE) and RHEL 5.
    I want to insert/update japanese language data in a column which has the datatype as varchar2(256).
    I tried to change the NLS_LANGUAGE and NLS_TERRITORY parameters with 'ALTER SESSION set ...' command but no effect.
    I tried to bounce back ( shutdown and startup ) the DB but still no effect.
    I tried to inset the NLS_LANGUAGE and NLS_TERRITORY in init.ora file but still no use.
    If anybody knows the detail steps which i have mentioned above .... let me know. Might be that i am wrong in my method.
    Can you please guide me how to change the language of DB for a perticular session to japanese ???
    Thanks in advance...
    Edited by: VJ4 on May 9, 2011 6:21 PM

    VJ4 wrote:
    Thanks for the info.
    Yes i tried with UNISTR function and was able to insert the data successfully.
    but the point is that we can't remember unicode for each of the letter. It's their any method that we can directly insert japanese character using an insert.
    As you said :-
    Note that changing database character set is something complicated that requires many steps.
    Can you please provide me some links or some stuffs to study about the detail steps of chaining database character set.
    I have gone through the Oracle online documentation.. if you can pin point any good link in it you can else provide me some other stuff.
    Thanks .You will need to convert your database characterset to AL32UTF8. This is not a trivial exercise if your database already has data in it. See these MOS Docs
    Changing the NLS_CHARACTERSET to AL32UTF8 / UTF8 (Unicode)          (Doc ID 260192.1)
    AL32UTF8 / UTF8 (Unicode) Database Character Set Implications          (Doc ID 788156.1)
    http://download.oracle.com/docs/cd/E11882_01/server.112/e10729/ch11charsetmig.htm#g1011430
    HTH
    Srini

  • Display Columns from WBS and Activities in the same Report

    Does anyone know how to display Columns from a WBS and an Activity together so that they can be output to Excel?
    I need WBS Code, Actual Start, Actual Finish and Performance % Complete from the WBS and Activity Codes from Activities.
    I can produce them in a report but this gives me all the activities in a heirarchical format which then necessitates deleting the activity lines in Excel
    The Performance % complete which I want is available in Activities at the Summary Level but the Activity Codes are not at this level
    I could put the Activity Codes in as Project Codes at the WBS level but this will require a lot of maintenance
    Maybe someone knows an easy way to do this?
    John
    Edited by: user9088233 on Feb 3, 2010 11:50 PM

    user9088233,
    Your request interested me so I gave it the old college try. There are several ways to go about this task but here's one that is fairly quick and easy.
    I carefully read your description of what you need from P6. I've built a test layout using the fields that you outlined. Here's what I came up with. This should bypass the issue of having to create a P6 export. My solution is to build a customized layout in P6 and copy that info and paste it into an Excel spreadsheet.+
    Open P6
    Open neccessary projects & open a new layout containing these columns:
    ....Project, WBS,Activity ID, Activity Name, Perf. %, & (any codes or user defined codes)
    Group & Sort by: Project, WBS
    ....*Display Options* = "Show Group Totals" & "Show Summaries Only", Choose "OK"
    ....*Edit*, Select, All, Copy
    Open Excel
    ....Paste Highlighted data into your new worksheet.
    Hope this helps but it's usually hard to understand exactly what you need unless I can view your data,
    Good Luck & let me know how it turns out,
    p3_scheduler
    Edited by: p3_scheduler on Feb 8, 2010 2:40 PM

  • Update values in AlV grid display after entering value

    Hi,
         I have an issue in ALV grid display.
        Let me explain.
        i have 8 fields to display in which one is editiable.
       Fields are: date
                       material,
                       material Description,
                       Opening Stock,
                       Closing stock-  (  this field is editiable)
                       Closing stock,
                       Received Stock,
                       Actual production.
    Actual production = Closing stock + removal stock
                                 - receipt stock - opening stock.
    when i change the value of closing stock and press enter, actual production should get update, the new values should display.
    Thany you in advance.

    Hi,
    Please refer the code below:
    REPORT z_demo_alv_jg.*******************************************************************
    * TYPE-POOLS                                                      *
    TYPE-POOLS: slis. *******************************************************************
    * INTERNAL TABLES/WORK AREAS/VARIABLES     *
    DATA: i_fieldcat TYPE slis_t_fieldcat_alv,
          i_index TYPE STANDARD TABLE OF i WITH HEADER LINE,
          w_field TYPE slis_fieldcat_alv,
          p_table LIKE dd02l-tabname,
          dy_table TYPE REF TO data,
          dy_tab TYPE REF TO data,
          dy_line TYPE REF TO data.*******************************************************************
    * FIELD-SYMBOLS                                                   *
    FIELD-SYMBOLS: <dyn_table> TYPE STANDARD TABLE,
                   <dyn_wa> TYPE ANY,
                   <dyn_field> TYPE ANY,
                   <dyn_tab_temp> TYPE STANDARD TABLE.*******************************************************************
    * SELECTION SCREEN                                                *
    PARAMETERS: tabname(30) TYPE c,
                lines(5)  TYPE n.*******************************************************************
    * START-OF-SELECTION                                              *
    START-OF-SELECTION.* Storing table name
      p_table = tabname.* Create internal table dynamically with the stucture of table name
    * entered in the selection screen
      CREATE DATA dy_table TYPE STANDARD TABLE OF (p_table).
      ASSIGN dy_table->* TO <dyn_table>.
      IF sy-subrc <> 0.
        MESSAGE i000(z_zzz_ca_messages) WITH ' No table found'.    LEAVE TO LIST-PROCESSING.
      ENDIF.
    * Create workarea for the table
      CREATE DATA dy_line LIKE LINE OF <dyn_table>.
      ASSIGN dy_line->* TO <dyn_wa>.* Create another temp. table
      CREATE DATA dy_tab TYPE STANDARD TABLE OF (p_table).
      ASSIGN dy_tab->* TO <dyn_tab_temp>.  SORT i_fieldcat BY col_pos.* Select data from table
      SELECT * FROM (p_table)
      INTO TABLE <dyn_table>
      UP TO lines ROWS.  REFRESH <dyn_tab_temp>.* Display report
      CALL FUNCTION 'REUSE_ALV_LIST_DISPLAY'
        EXPORTING
          i_callback_program       = sy-repid
          i_structure_name         = p_table
          i_callback_user_command  = 'USER_COMMAND'
          i_callback_pf_status_set = 'SET_PF_STATUS'
        TABLES
          t_outtab                 = <dyn_table>
        EXCEPTIONS
          program_error            = 1
          OTHERS                   = 2.  IF sy-subrc <> 0.  ENDIF.*&-----------------------------------------------------------------*
    *&      Form  SET_PF_STATUS
    *       Setting custom PF-Status
    *      -->RT_EXTAB   Excluding table
    FORM set_pf_status USING rt_extab TYPE slis_t_extab.  SET PF-STATUS 'Z_STANDARD'.ENDFORM.                    "SET_PF_STATUS*&----------------------------------------------------------------*
    *&      Form  user_command
    *       Handling custom function codes
    *      -->R_UCOMM      Function code value
    *      -->RS_SELFIELD  Info. of cursor position in ALV
    FORM user_command  USING    r_ucomm LIKE sy-ucomm
                               rs_selfield TYPE slis_selfield.* Local data declaration
      DATA: li_tab TYPE REF TO data,
            l_line TYPE REF TO data.* Local field-symbols
      FIELD-SYMBOLS:<l_tab> TYPE table,
                    <l_wa>  TYPE ANY.* Create table
      CREATE DATA li_tab TYPE STANDARD TABLE OF (p_table).
      ASSIGN li_tab->* TO <l_tab>.* Create workarea
      CREATE DATA l_line LIKE LINE OF <l_tab>.
      ASSIGN l_line->* TO <l_wa>.  CASE r_ucomm.*   When a record is selected
        WHEN '&IC1'.*     Read the selected record
          READ TABLE <dyn_table> ASSIGNING <dyn_wa> INDEX
          rs_selfield-tabindex.      IF sy-subrc = 0.*       Store the record in an internal table
            APPEND <dyn_wa> TO <l_tab>.*       Fetch the field catalog info
            CALL FUNCTION 'REUSE_ALV_FIELDCATALOG_MERGE'
              EXPORTING
                i_program_name         = 'Z_DEMO_PDF_JG'
                i_structure_name       = p_table
              CHANGING
                ct_fieldcat            = i_fieldcat
              EXCEPTIONS
                inconsistent_interface = 1
                program_error          = 2
                OTHERS                 = 3.
            IF sy-subrc = 0.*         Make all the fields input enabled except key fields
              w_field-input = 'X'.          MODIFY i_fieldcat FROM w_field TRANSPORTING input
              WHERE key IS INITIAL.        ENDIF.*       Display the record for editing purpose
            CALL FUNCTION 'REUSE_ALV_LIST_DISPLAY'
              EXPORTING
                i_callback_program    = sy-repid
                i_structure_name      = p_table
                it_fieldcat           = i_fieldcat
                i_screen_start_column = 10
                i_screen_start_line   = 15
                i_screen_end_column   = 200
                i_screen_end_line     = 20
              TABLES
                t_outtab              = <l_tab>
              EXCEPTIONS
                program_error         = 1
                OTHERS                = 2.        IF sy-subrc = 0.*         Read the modified data
              READ TABLE <l_tab> INDEX 1 INTO <l_wa>.*         If the record is changed then track its index no.
    *         and populate it in an internal table for future
    *         action
              IF sy-subrc = 0 AND <dyn_wa> <> <l_wa>.
                <dyn_wa> = <l_wa>.
                i_index = rs_selfield-tabindex.
                APPEND i_index.
              ENDIF.
            ENDIF.      ENDIF.*   When save button is pressed
        WHEN 'SAVE'.*     Sort the index table
          SORT i_index.*     Delete all duplicate records
          DELETE ADJACENT DUPLICATES FROM i_index.      LOOP AT i_index.*       Find out the changes in the internal table
    *       and populate these changes in another internal table
            READ TABLE <dyn_table> ASSIGNING <dyn_wa> INDEX i_index.
            IF sy-subrc = 0.
              APPEND <dyn_wa> TO <dyn_tab_temp>.
            ENDIF.      ENDLOOP.*     Lock the table
          CALL FUNCTION 'ENQUEUE_E_TABLE'
            EXPORTING
              mode_rstable   = 'E'
              tabname        = p_table
            EXCEPTIONS
              foreign_lock   = 1
              system_failure = 2
              OTHERS         = 3.      IF sy-subrc = 0.*       Modify the database table with these changes
            MODIFY (p_table) FROM TABLE <dyn_tab_temp>.        REFRESH <dyn_tab_temp>.*       Unlock the table
            CALL FUNCTION 'DEQUEUE_E_TABLE'
              EXPORTING
                mode_rstable = 'E'
                tabname      = p_table.      ENDIF.
      ENDCASE.  rs_selfield-refresh = 'X'.ENDFORM.                    "user_command
    Thanks,
    Sriram Ponna.

  • Update all rows in a View Column via one Apex Form field

    Appreciate any helpful answers to this query.
    I have an Apex App (4.x) where I have a view: PRICE_MODEL_CRA_V
    In the view, I have the following applicable columns:
    COUNTRY
    GRADE
    SALARY
    In the form I have the following fields
    :P16_COUNTRY (DROPDOWN)
    :P16_GRADE (DROPDOWN)
    :P16_SALARY (Number)
    In my app, I have a form with an Update button. I am simply trying to get Apex to update all rows in the salaray column in the view, where the country and grade match.
    I've the following code for the Update button:
    UPDATE PRICE_MODEL_CRA_V
    SET SALARY = :P16_SALARY
    WHERE COUNTRY = :P16_COUNTRY
    AND GRADE = :P16_GRADE
    The option I have chosen in condition type is:
    Value of Item / Column expression is NOT Null (as there are values in the column)
    Also tried SQL Expression and it does not like..says that there is No Expression.
    Thanks again if anyone can help :)

    Hi,
    Sorry I realize now that piece of information was not well supported.
    If I choose SQL Expression for Condition Type in my Form Page and I try to Apply Changes
    Apex says this..
    •Failed to parse SQL query!
    ORA-00936: missing expression
    I was assuming that I need to have the colon for the items in the form where I am wanting Apex to grab the values entered by the user. I tried them without the colons with the SQL Expression condition and same result.
    UPDATE PRICE_MODEL_CRA_V
    SET SALARY = P16_SALARY
    WHERE COUNTRY = P16_COUNTRY
    AND GRADE = P16_GRADE
    I did put 1-1/0 in my expression field and applied changes and then tried ot submit the form and it does not produce an error, so perhaps it is not being called? Where would I start with troubleshooting that?
    Thanks,

  • Hiding Table Columns with the Spry Element Selector

    I am trying to set up a toggle button that will show/hide
    rows >1 when clicked. I've used Adobe's
    "Hiding
    Table Columns with the Spry Element Selector" example and it
    worked fine with an HTML list, until I linked to actual XML data.
    Now it works in reverse. What gives?
    Here's the example:
    http://a44.awardspace.com/testing/toggleShowHideRows.htm

    That's what I started with. Same result:
    http://a44.awardspace.com/testing/toggleShowHideRows.htm

  • Hiding a column in the ALV in a webdynpro component(standrad one)

    Hi,
       i have an requirement of hiding a column inside a ALV output of a web dynpro component which is a standrad one. please help me finding the way to do the same.
    thanks,
    selvakumar M.

    data: l_ref_usage type ref to if_wd_component_usage.
    l_ref_usage = wd_this->wd_CpUse_Alv( ).
    if l_ref_usage->has_active_component( ) = abap_false.
      l_ref_usage->create_component( ).
    endif.
    DATA: l_ref_INTERFACECONTROLLER TYPE REF TO IWCI_SALV_WD_TABLE .
    l_ref_INTERFACECONTROLLER =   wd_This->wd_CpIfc_Alv( ).
      data:
        l_VALUE type ref to Cl_Salv_Wd_Config_Table.
      l_VALUE = l_ref_INTERFACECONTROLLER->Get_Model(
    data: lr_column type ref to CL_SALV_WD_COLUMN.
    lr_column =
    l_value->IF_SALV_WD_COLUMN_SETTINGS~GET_COLUMN( 'CARRID' ).
    lr_column->set_visible( CL_WD_UIELEMENT=>E_VISIBLE-NONE ).
    Abhi

Maybe you are looking for

  • Installing Oracle 8.1.7 with PS on Win 2000 cluster

    Sorry for bad English. I'm have problem. I have Oracle 8.1.7 with PS. I need setup Oracle with Parallel Server on cluster with Windows 2000 AS, but during setup Oracle no found cluster. In documentation talk about need Operation System Depend layer f

  • Xdim_member  - How to use it

    Hi, Does  xdim_member  is still available for BPC 7.5 SP04 ? Im trying to make a change in my  scripts, taking as a base this: acc1 = account.x.category.budget acc2 = account.y.category.budget acc3 = account.z.category.budget now: xdim_member categor

  • How do I find my Apple ID?

    How do I find my  Apple ID?

  • Piped streams, data lines and threads - what's the bug?

    Please, help! What is wrong here and what should I do to make it running? Strictly speaking, one thread becomes blocked (in) and another runs in a short circuit (out). The code is:     TargetDataLine stdin;     SourceDataLine stdout;     PipedInputSt

  • Displaying feed backs in Captivate 7 multiple choice quizzes

    Hi, I am running different quiz slides in Captivate 7 and I want students after clicking on the submit button get the correct answer. I could dispaly the answer to the students but when they chose the right answer, I want them to get the answer and t