Update the scrollbars of a JScrollPane

Hi,
I have a component in a JScrollPane. But when it changes its preferredSize the scrollbars of JScrollPane aren't updated automatically.
I've tried:
myComponent.getParent().repaint(); // JViewPort
myComponent.getParent().getParent().repaint(); // JScrollPaneneither had the desired effect :-(
Can anybody help?
Thanks!
Greez
Puce

It worked with revalidate(), but thanks, it led me on the right path.
But why isn't it called automatically as stated in the Javadoc of JComponent?
A bug?
- Puce

Similar Messages

  • How to change the size of the scrollbar in JScrollPane?

    I set a jtable in the jscrollpane,but the table is very small,so I want to change the size of the scrollbar in the jscrollpane.How can i do?Please help me,Thanks.

    Dropping and re-creating the table is by far the best way (of course you need to unload the table's data to a flat file with ttBulkCp first and then reload it again afterwards).
    a second option is to drop the column and re-add it with the new size but you still need to preserve the data first and put it back afterwards and this is harder for a single column than for a whole table. Also, if you are using replication you should exercise care when using ALTER TABLE to ensure iall replicated copies of the table maintain the same physical structure.
    Chris

  • After updating to ios 6, the music app is missing the scrollbar, genius, and shuffle control

    After updating/upgrading my software to ios 6 on my 3gs, the music app is missing the scrollbar, genius button, and shuffle control.
    its getting frustrating listening to music because i cn't turn off shuffle.

    nevermind, LOL, i feel like an idiot, sigle tapping the screen with a song playing exposed the bar and buttons.

  • Customizing the scrollbar for jScrollpane Component

    Hi,
    Am trying to customize my jScrollpane scrollbars. Would like to at least customize colors.
    Anyone know how to do this? Or know anywhere to read up about this. I am using the Sun One Studio and can't seem to do this at all.
    thanks

    I have the same problem.
    So far I have only managed to change the background of the scrollbars.
    jScrollPane.getVerticalScrollBar().setBackground(color);
    Does anyone know how to further customize the scrollbar?

  • How do you monitor a background thread and update the GUI

    Hello,
    I have a thread which makes its output available on PipedInputStreams. I should like to have other threads monitor the input streams and update a JTextArea embedded in a JScrollPane using the append() method.
    According to the Swing tutorial, the JTextArea must be updated on the Event Dispatch Thread. When I use SwingUtilities.invokeLater () to run my monitor threads, the component is not redrawn until the thread exits, so you don't see the progression. If I add a paint () method, the output is choppy and the scrollbar doesn't appear until the thread exits.
    Ironically, if I create and start new threads instead of using invokeLater(), I get the desired result.
    What is the correct architecture to accomplish my goal without violating Swing rules?
    Thanks,
    Brad
    Code follows:
    import java.lang.*;
    import java.io.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.*;
    import java.awt.event.*;
    public class SystemCommand implements Runnable
         private String[] command;
         private PipedOutputStream pipeout;
         private PipedOutputStream pipeerr;
         public SystemCommand ( String[] cmd )
              command = cmd;
              pipeout = null;
              pipeerr = null;
         public void run ()
              exec ();
         public void exec ()
              // --- Local class to redirect the process input stream to a piped output stream
              class OutputMonitor implements Runnable
                   InputStream is;
                   PipedOutputStream pout;
                   public OutputMonitor ( InputStream i, PipedOutputStream p )
                        is = i;
                        pout = p;
                   public void run ()
                        try
                             int inputChar;
                             for ( ;; )
                                  inputChar = is.read();
                                  if ( inputChar == -1 ) { break; }
                                  if ( pout == null )
                                       System.out.write ( inputChar );
                                  else
                                       pout.write ( inputChar );
                             if ( pout != null )
                                  pout.flush ();
                                  pout.close ();
                             else
                                  System.out.flush();
                        catch ( Exception e ) { e.printStackTrace (); }     
              try
                   Runtime r = Runtime.getRuntime ();
                   Process p = r.exec ( command );
                   OutputMonitor out = new OutputMonitor ( p.getInputStream (), pipeout );
                   OutputMonitor err = new OutputMonitor ( p.getErrorStream (), pipeerr );
                   Thread t1 = new Thread ( out );
                   Thread t2 = new Thread ( err );
                   t1.start ();
                   t2.start ();
                   //p.waitFor ();
              catch ( Exception e ) { e.printStackTrace (); }
         public PipedInputStream getInputStream () throws IOException
              pipeout = new PipedOutputStream ();
              return new PipedInputStream ( pipeout );
         public PipedInputStream getErrorStream () throws IOException
              pipeerr = new PipedOutputStream ();
              return new PipedInputStream ( pipeerr );
         public void execInThread ()
              Thread t = new Thread ( this );
              t.start ();
         public static JPanel getContentPane ( JTextArea ta )
              JPanel p = new JPanel ( new BorderLayout () );
              JPanel bottom = new JPanel ( new FlowLayout () );
              JButton button = new JButton ( "Exit" );
              button.addActionListener ( new ActionListener ( )
                                       public void actionPerformed ( ActionEvent e )
                                            System.exit ( 0 );
              bottom.add ( button );
              p.add ( new JScrollPane ( ta ), BorderLayout.CENTER );
              p.add ( bottom, BorderLayout.SOUTH );
              p.setPreferredSize ( new Dimension ( 640,480 ) );
              return p;
         public static void main ( String[] argv )
              // --- Local class to run on the event dispatch thread to update the Swing GUI
              class GuiUpdate implements Runnable
                   private PipedInputStream pin;
                   private PipedInputStream perr;
                   private JTextArea outputArea;
                   GuiUpdate ( JTextArea textArea, PipedInputStream in )
                        pin = in;
                        outputArea = textArea;
                   public void run ()
                        try
                             // --- Reads whole file before displaying...takes too long
                             //outputArea.read ( new InputStreamReader ( pin ), null );
                             BufferedReader r = new BufferedReader ( new InputStreamReader ( pin ) );
                             String line;
                             for ( ;; )
                                  line = r.readLine ();
                                  if ( line == null ) { break; }
                                  outputArea.append ( line + "\n" );
                                  // outputArea.paint ( outputArea.getGraphics());
                        catch ( Exception e ) { e.printStackTrace (); }
              // --- Create and realize the GUI
              JFrame f = new JFrame ( "Output Capture" );
              f.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );
              JTextArea textOutput = new JTextArea ();
              f.getContentPane().add ( getContentPane ( textOutput ) );
              f.pack();
              f.show ();
              // --- Start the command and capture the output in the scrollable text area
              try
                   // --- Create the command and setup the pipes
                   SystemCommand s = new SystemCommand ( argv );
                   PipedInputStream stdout_pipe = s.getInputStream ();
                   PipedInputStream stderr_pipe = s.getErrorStream ();
                   // --- Launch
                   s.execInThread ( );
                   //s.exec ();
                   // --- Watch the results
                   SwingUtilities.invokeLater ( new GuiUpdate ( textOutput, stdout_pipe ) );
                   SwingUtilities.invokeLater ( new GuiUpdate ( textOutput, stderr_pipe ) );
                   //Thread t1 = new Thread ( new GuiUpdate ( textOutput, stdout_pipe ) );
                   //Thread t2 = new Thread ( new GuiUpdate ( textOutput, stderr_pipe ) );
                   //t1.start ();
                   //t2.start ();
              catch ( Exception e ) { e.printStackTrace (); }
              

    Thanks for pointing out the SwingWorker class. I didn't use it directly, but the documentation gave me some ideas that helped.
    Instead of using invokeLater on the long-running pipe-reader object, I run it on a normal thread and let it consume the output from the background thread that is running the system command. Inside the reader thread I create a tiny Runnable object for each line that is read from the pipe, and queue that object with invokeLater (), then yield() the reader thread.
    Seems like a lot of runnable objects, but it works ok.

  • Setting the scrollbar to be by default in the middle of the scrollpane

    I was wondering if there was a way to set the JScrollBar to be at the middle of the scrollpane by default. I have a handle to the scrollbar and can determine the min and max of it's range, but I don't see a place to set the scrollbar position.

    This is a runnable stand-alone app.
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowListener;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.Component;
    import java.awt.Color;
    import java.awt.Font;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.util.*;
    public class MarketBook extends JFrame implements WindowListener,
                                                      ActionListener{
         protected final int ROW_HEIGHT = 15;
         protected final int NUM_ROW = 14;
         protected final int PREF_WIDTH = 200;
         protected final int PREF_HEIGHT = 150;
         protected final int BID_COL = 1;
         protected final int OFFER_COL = 2;
         private String instrument;
         private String mkbkID;
         private String[] instArray = {"Item1", "Item2", "Item3"};
         private String[] colNames = {"Qty", "Bid", "Offer", "Qty"};
         private Vector<String> instrumentsList = new Vector<String>();
         private DefaultTableModel dm = new DefaultTableModel(colNames, NUM_ROW);
         private DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
         JPanel contentPane = new JPanel();
         JPanel topPanel = new JPanel();
         JComboBox instList = new JComboBox(instArray);
         JTable bidOffer = new JTable(){
              public boolean isCellEditable(int row, int column){
                        return false;
         JScrollPane bidOfferScroll = new JScrollPane(bidOffer);
         public MarketBook(String _mkbkID, Vector<String> _instList){
              super(_instList.firstElement());
              this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
              this.mkbkID = _mkbkID;
              this.instrumentsList = _instList;
              this.instrument = instrumentsList.firstElement();
              buildGUI();
         private void buildGUI(){
              TableColumn tc = null;
              contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
              bidOfferScroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
              bidOfferScroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
              bidOfferScroll.setPreferredSize(new Dimension(PREF_WIDTH,PREF_HEIGHT));
              System.err.println("Max: " + bidOfferScroll.getVerticalScrollBar().getMaximum());
              System.err.println("Min: " + bidOfferScroll.getVerticalScrollBar().getMinimum());
              System.err.println("Extent: " + bidOfferScroll.getVerticalScrollBar().getVisibleAmount());
              System.err.println("Value: " + bidOfferScroll.getVerticalScrollBar().getValue());
              bidOfferScroll.getVerticalScrollBar().setValueIsAdjusting(true);
              bidOfferScroll.getVerticalScrollBar().setValue(50);
              System.err.println("Value: " + bidOfferScroll.getVerticalScrollBar().getValue());
              System.err.println("Model: " + bidOfferScroll.getVerticalScrollBar().getModel());          
                        bidOfferScroll.getVerticalScrollBar().getMaximum()-
                        bidOfferScroll.getVerticalScrollBar().getMinimum())/2);*/
              topPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
              topPanel.add(instList);
              instList.addActionListener(this);
              bidOffer.getTableHeader().setFont(new Font(null, Font.BOLD, 12));
              bidOffer.setAlignmentX(JTable.CENTER_ALIGNMENT);
              bidOffer.setModel(dm);
              bidOffer.getColumnModel().getColumn(0).setPreferredWidth(40);
              bidOffer.getColumnModel().getColumn(1).setPreferredWidth(60);
              bidOffer.getColumnModel().getColumn(2).setPreferredWidth(60);
              bidOffer.getColumnModel().getColumn(3).setPreferredWidth(40);               
              bidOffer.setRowHeight(ROW_HEIGHT);
              // Set table renderer
              for(int i = 0; i < bidOffer.getColumnCount(); i++){
                   tc = bidOffer.getColumnModel().getColumn(i);
                   tc.setCellRenderer(new CustomTableCellRenderer());
              contentPane.add(topPanel);
              contentPane.add(bidOfferScroll);
              JFrame.setDefaultLookAndFeelDecorated(true);
              this.setContentPane(contentPane);
              this.pack();
              this.setVisible(true);
         public void actionPerformed (ActionEvent e){
              JComboBox cb = (JComboBox)e.getSource();
              String selectedItem = (String)cb.getSelectedItem();
              updateSelectedInst(selectedItem);
         public void windowActivated(WindowEvent arg0) {
              // TODO Auto-generated method stub
         public void windowClosed(WindowEvent arg0) {
              // TODO Auto-generated method stub
         public void windowClosing(WindowEvent arg0) {
              // TODO Auto-generated method stub
              this.setVisible(false);
              this.dispose();
              System.exit(0);
         public void windowDeactivated(WindowEvent e) {
              // TODO Auto-generated method stub
         public void windowDeiconified(WindowEvent e) {
              // TODO Auto-generated method stub
         public void windowIconified(WindowEvent e) {
              // TODO Auto-generated method stub
         public void windowOpened(WindowEvent e) {
              // TODO Auto-generated method stub
         // Perform all updates necessary when new instrument is selected
         private void updateSelectedInst(String inst){
              this.setTitle(inst);
         class CustomTableCellRenderer extends DefaultTableCellRenderer{
              public Component getTableCellRendererComponent(JTable table,
                        Object value, boolean isSelected, boolean hasFocus,
                        int row, int column){
                   Component cell = super.getTableCellRendererComponent(table,
                                       value, isSelected, hasFocus, row, column);
                   if (column == BID_COL){
                        cell.setBackground(Color.red);
                   else if (column == OFFER_COL){
                        cell.setBackground(Color.blue);
                   //cell.setFont(f)
                   return cell;
         public static void main(String args[]){
              Vector<String> tempVector = new Vector<String>();
              tempVector.add("item1");
              tempVector.add("item2");
              MarketBook marketBook1 = new MarketBook("mkbk1", tempVector);
    }

  • Not Updating the Values in the JComboBox and JTable

    Hi Friends
    In my program i hava Two JComboBox and One JTable. I Update the ComboBox with different field on A Table. and then Display a list of record in the JTable.
    It is Displaying the Values in the Begining But when i try to Select the Next Item in the ComboBox it is not Updating the Records Eeither to JComboBox or JTable.
    MY CODE is this
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.DefaultComboBoxModel.*;
    import javax.swing.table.*;
    import java.sql.*;
    import java.util.*;
    public class SearchBook extends JDialog implements ActionListener
         private JComboBox comboCategory,comboAuthor;
         private JSplitPane splitpane;
         private JTable table;
         private JToolBar toolBar;
         private JButton btnclose, btncancel;
         private JPanel panel1,panel2,panel3,panel4;
         private JLabel lblCategory,lblAuthor;
         private Container c;
         //DefaultTableModel model;
         Statement st;
         ResultSet rs;
         Vector v = new Vector();
         public SearchBook (Connection con)
              // Property for JDialog
              setTitle("Search Books");
              setLocation(40,110);
              setModal(true);
              setSize(750,450);
              // Creating ToolBar Button
              btnclose = new JButton(new ImageIcon("Images/export.gif"));
              btnclose.addActionListener(this);
              // Creating Tool Bar
              toolBar = new JToolBar();
              toolBar.add(btnclose);
              try
                   st=con.createStatement();
                   rs =st.executeQuery("SELECT BCat from Books Group By Books.BCat");
                   while(rs.next())
                        v.add(rs.getString(1));
              catch(SQLException ex)
                   System.out.println("Error");
              panel1= new JPanel();
              panel1.setLayout(new GridBagLayout());
              GridBagConstraints c = new GridBagConstraints();
              c.fill = GridBagConstraints.HORIZONTAL;
              lblCategory = new JLabel("Category:");
              lblCategory.setHorizontalAlignment (JTextField.CENTER);
              c.gridx=2;
              c.gridy=2;
              panel1.add(lblCategory,c);
              comboCategory = new JComboBox(v);
              comboCategory.addActionListener(this);
              c.ipadx=20;
              c.gridx=3;
              c.gridwidth=1;
              c.gridy=2;
              panel1.add(comboCategory,c);
              lblAuthor = new JLabel("Author/Publisher:");
              c.gridwidth=2;
              c.gridx=1;
              c.gridy=4;
              panel1.add(lblAuthor,c);
              lblAuthor.setHorizontalAlignment (JTextField.LEFT);
              comboAuthor = new JComboBox();
              comboAuthor.addActionListener(this);
              c.insets= new Insets(20,0,0,0);
              c.ipadx=20;
              c.gridx=3;
              c.gridy=4;
              panel1.add(comboAuthor,c);
              comboAuthor.setBounds (125, 165, 175, 25);
              table = new JTable();
              JScrollPane scrollpane = new JScrollPane(table);
              //panel2 = new JPanel();
              //panel2.add(scrollpane);
              splitpane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,panel1,scrollpane);
              splitpane.setDividerSize(15);
              splitpane.setDividerLocation(190);
              getContentPane().add(toolBar,BorderLayout.NORTH);
              getContentPane().add(splitpane);
         public void actionPerformed(ActionEvent ae)
              Object obj= ae.getSource();
              if(obj==comboCategory)
                   String selecteditem = (String)comboCategory.getSelectedItem();
                   displayAuthor(selecteditem);
                   System.out.println("Selected Item"+selecteditem);
              else if(obj==btnclose)
                   setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
              else if(obj==comboAuthor)
                   String selecteditem1 = (String)comboAuthor.getSelectedItem();
                   displayavailablity(selecteditem1);
                   //System.out.println("Selected Item"+selecteditem1);
                   System.out.println("Selected Author"+selecteditem1);
         private void displayAuthor(String selecteditem)
              try
              {     Vector data = new Vector();
                   rs= st.executeQuery("SELECT BAuthorandPublisher FROM Books where BCat='" + selecteditem + "' Group By Books.BAuthorandPublisher");
                   System.out.println("Executing");
                   while(rs.next())
                        data.add(rs.getString(1));
                   //((DefaultComboBoxModel)comboAuthor.getModel()).setVectorData(data);
                   comboAuthor.setModel(new DefaultComboBoxModel(data));
              catch(SQLException ex)
                   System.out.println("ERROR");
         private void displayavailablity(String selecteditem1)
                   try
                        Vector columnNames = new Vector();
                        Vector data1 = new Vector();
                        rs= st.executeQuery("SELECT * FROM Books where BAuthorandPublisher='" + selecteditem1 +"'");     
                        ResultSetMetaData md= rs.getMetaData();
                        int columns =md.getColumnCount();
                        String booktblheading[]={"Book ID","Book NAME","BOOK AUTHOR/PUBLISHER","REFRENCE","CATEGORY"};
                        for(int i=1; i<= booktblheading.length;i++)
                             columnNames.addElement(booktblheading[i-1]);
                        while(rs.next())
                             Vector row = new Vector(columns);
                             for(int i=1;i<=columns;i++)
                                  row.addElement(rs.getObject(i));
                             data1.addElement(row);
                             //System.out.println("data is:"+data);
                        ((DefaultTableModel)table.getModel()).setDataVector(data1,columnNames);
                        //DefaultTableModel model = new DefaultTableModel(data1,columnNames);
                        //table.setModel(model);
                        rs.close();
                        st.close();
                   catch(SQLException ex)
    }Please check my code and give me some Better Solution
    Thank you

    You already have a posting on this topic:
    http://forum.java.sun.com/thread.jspa?threadID=5143235

  • Resizing a JList with variable row heights, not updating the "picture"

    Firstly I would like to apologize for posting this Swing question here, but I was unable to find the Swing category, if someone could direct me to that I would be most grateful.
    Ok, so in abstract what I am trying to do is have a JList with resizable rows to act as a row header for a JTable (exactly like the row headers in OO Calc or MS Excel).
    What I have is a RowHeaderRenderer:
    public class RowHeaderRenderer extends JLabel implements ListCellRendererand it has a private member:
    private Vector<Integer>        _rowHeights            = new Vector<Integer>();which contains a list of all the variable row heights.
    Then there is my getListCellRendererComponent method:
        public Component getListCellRendererComponent(    JList         list,
                                                          Object        value,
                                                          int           index,
                                                          boolean       isSelected,
                                                          boolean       cellHasFocus)
            // Make sure the value is not null
            if(value == null)
                this.setText("");
            else
                this.setText(value.toString());
            // This is where height of the row is actually changed
            // This method is fed values from the _rowHeights vector
            this.setPreferredSize(new Dimension(this.getPreferredSize().width, _rowHeights.elementAt(index)));
            return this;
        }And then I have a row header:
    public class RowHeader extends JList implements TableModelListener, MouseListener, MouseMotionListenerand you may be interested in its constructor:
        public RowHeader(JTable table)
            _table = table;
            _rowHeaderRenderer = new RowHeaderRenderer(_table);
            this.setFixedCellWidth                        (50);
            this.setCellRenderer                        (_rowHeaderRenderer);
            // TODO: grab this value from the parent view table
            JScrollPane panel = new JScrollPane();
            this.setBackground(panel.getBackground());
            this.addMouseMotionListener                    (this);
            this.addMouseListener                        (this);
            this.setModel                                (new DefaultListModel());
            table.getModel().addTableModelListener        (this);
            this.tableChanged                            (new TableModelEvent(_table.getModel()));
        }and as you can see from my mouse dragged event:
        public void mouseDragged(MouseEvent e)
            if(_resizing == true)
                int resizingRowHeight = _rowHeaderRenderer.getRowHeight(_resizingRow);
                _rowHeaderRenderer.setRowHeight(_resizingRow, resizingRowHeight + (e.getPoint().y - _cursorPreviousY));
                _cursorPreviousY = e.getPoint().y;  
        }all I am doing is passing the rowHeaderRenderer the values the currently resizing row should be, which works fine. The values are being changed and are accurate.
    The issue I am having is that while this dragging is going on the row does not appear to be resizing. In other words the "picture" of the row remains unchanged even though I change the values in the renderer. I tried calling:
    this.validate();and
    this.repaint();at the end of that mousedDragged method, but to no avail, neither of them worked.
    Again, I verified that I am passing the correct data in the RowHeaderRenderer.
    So, anyone have any ideas how I should get the image of the RowHeader (JList) to update after calling my MouseDragged event?
    Thank you for your time,
    Brandon

    I was able to fix this some time ago. Here is the solution:
         public void mouseDragged(MouseEvent e)
              if(_resizing == true)
                   int newHeight = _previousHeight + (e.getPoint().y - _cursorPreviousY);
                   if(newHeight < _minRowHeight)
                        newHeight = _minRowHeight;
                   _rowHeaderRenderer.setRowHeight(_resizingRow, newHeight);
                   _table.setRowHeight(_resizingRow, newHeight);
              this.updateUI();
         }

  • Can we hide the scrollbars scrollbar  or r  there any tools which

    acts like scrollpane without scrollbar

    I am not sure I understand what you want (a little more detailed information would make it easier to help). If you are using a JScrollpane you can control the visibility of the Scrollbars with the methods setVerticalScrollBarPolicy(int) and setHoricontalScrollBarPolicy(int). See also:
    http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/JScrollPane.html

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

  • Doing new JTable doesn't "update" the table on the screen

    Hello
    I am writing a program in java/swing which has several "layers" of panels. In the constructor method of the frame (using JInternalFrame) I create a new instance of JTable, place it inside JScrollPane which is then inside JSplitPane and then place that as the frame content pane.
    In this program I run an sql command and the table is the result from that. Every time I execute a query it should update the table with the new results.
    What is bothering me now is that when I execute a query I call new JTable() on the variable that held the JTable() object created on startup. When I create a new instance of JTable() and place it in this variable nothing seems to happen. What I need is some kind of "refresh" button. I tried to construct the whole window again but then the program started behaving odd so I gave up that method.
    So, does anyone know how to do this?
    The code behind this class can be found at http://www.heilabu.net/kari/Session.java (little commented, sorry :/)
    You can see the table being constructed in the constructTable() method.
    If I am a bit unclear I apologize, don't know all these technical words in english ;)
    Thanks in advance!

    You really need to use a table model. The table you created is great and once that is in you shouldn't mess with it. Instead, when you create the table be sure to create it sort of like this:
    DefaultTableMode dtm = new DefaultTableModel(<various constrcutors use the one suited for you>);
    JTable table = new JTable(dtm);
    To set different data on the table set it in the table model and then refresh the table, also through the table model. This works perfectly every time.
    dtm.setDataVector(---) <- 2 methods, one for vectors and one for arrays...
    dtm.fireTableChanged();
    the folowing code shows exactly how to use it
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class RandomTable extends JFrame
    GridBagLayout gbl = new GridBagLayout();
    JPanel buttonPanel = new JPanel(gbl);
    JTable table = null;
    DefaultTableModel dtm = null;
    JScrollPane tableSP = new JScrollPane();
    JButton randomButton = new JButton("Randomize");
    Object[] headers = { "a", "b", "c", "d", "e" };
    public RandomTable()
    this.getContentPane().setLayout(gbl);
    randomButton.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent evt)
    dtm.setDataVector(randomStrings(), headers);
    this.dtm = new DefaultTableModel();
    this.table = new JTable(dtm);
    this.dtm.setDataVector(randomStrings(), headers);
    this.tableSP.getViewport().add(table);
    this.buttonPanel.add(randomButton, new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
    this.getContentPane().add(buttonPanel, new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0,GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(3, 6, 6, 6), 0, 0));
    this.getContentPane().add(tableSP, new GridBagConstraints(1, 1, 1, 1, 1.0, 1.0,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(6, 6, 3, 6), 0, 0));
    this.setSize(300, 300);
    public Object[][] randomStrings()
    Random rand = new Random();
    int rowCount = Math.abs(rand.nextInt())%50;
    int colCount = headers.length;
    Object[][] array = new Object[rowCount][colCount];
    for(int row = 0; row < rowCount; row++)
    for(int col = 0; col < colCount; col++)
    array[row][col] = Long.toString(Math.abs(rand.nextLong())%100);
    return array;
    public static void main(String[] args)
    RandomTable rt = new RandomTable();
    rt.setVisible(true);
    }

  • Update the tree

    Hi,
    I want to update the tree in the thread when I click the button. I tried it. But it is not updating the tree.
    I am putting my code beow, please correct me !!!
    import java.awt.BorderLayout;
    import java.awt.EventQueue;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Vector;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTree;
    import javax.swing.tree.DefaultMutableTreeNode;
    public class UserTree extends JFrame {
          DefaultMutableTreeNode root;
          JButton btn = new JButton("Click");
          Vector v ;
         public UserTree(){
               v = new Vector();
               v.add("A");
               v.add("B");
               root = new DefaultMutableTreeNode("Users" );
              for(int i = 0;i < v.size();i++){
                         root.add(new DefaultMutableTreeNode(v));
               JScrollPane js = new JScrollPane( new JTree( root ) );
               getContentPane().add( js );
               getContentPane().add(btn,BorderLayout.SOUTH);
               setSize(400,400);
               setDefaultCloseOperation(EXIT_ON_CLOSE);
              btn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent e) {
                        // TODO Auto-generated method stub
                        new UpdateThread(v).start();
          * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              UserTree ut = new UserTree();
              ut.setVisible(true);
         class UpdateThread extends Thread{
              Vector vector;
              public UpdateThread(Vector v){
                   this.vector = v;
         public void run() {
              // TODO Auto-generated method stub
              EventQueue.invokeLater(new Runnable(){
                   public void run() {                    
                        for(int i=0;i < 5;i++){                         
                             v.add(""+i);               
    }

    Hi corlettk.
    Nice to see u again....
    I can update the JList while I am using DefaultListModel, but I cant update the JTree when using the vector.
    Now whenI clicked the button it is getting hanged the window...
    import java.awt.BorderLayout;
    import java.awt.EventQueue;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Random;
    import javax.swing.DefaultListModel;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JList;
    import javax.swing.JScrollPane;
    public class TableEx extends JFrame{
         JList list;
         JButton btn = new JButton("Click");
         DefaultListModel listModel ;
         public TableEx(){
              listModel = new DefaultListModel();
              list = new JList(listModel);
              JScrollPane sc = new JScrollPane(list);
              getContentPane().add(sc);
              getContentPane().add(btn,BorderLayout.SOUTH);
              btn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent ae){
                        System.out.println("hello");
                        new UpdateThread(listModel).start();
              setSize(300,200);
         public static void main(String arg[]){
              TableEx ex = new TableEx();
              ex.setVisible(true);
         class UpdateThread extends Thread{
              DefaultListModel listModel;
              UpdateThread(DefaultListModel list){
                   this.listModel = list;
              public void run(){
                   final Random random= new Random();
                   while(true){
                   EventQueue.invokeLater(new Runnable(){
                        public void run(){
                        int      i =random.nextInt();
                             if(listModel.contains(""+i)){
                                  listModel.removeElement(""+i);
                             }else{
                                  listModel.addElement(""+i);
         }Edited by: bhanu on Aug 26, 2008 12:21 PM

  • Reskinning the Scrollbar Component in CS3

    I'm looking to completely reskin the scrollbar component, but
    I'm having problems doing so.
    I know all about editing the symbols/art that compose the
    scroller, and I'm having a few unique issues:
    A) Is it possible to change the width of the component
    itself? Changing the symbols doesn't seem to change that part.
    B) Is it possible to completely remove the "arrows"? I only
    want the scroller to be the drag up and down widget (not the arrows
    as well).
    C) Is it possible to define how close/far from the content
    the scroller is placed?
    D) Basically what I'm trying to recreate is a scroller that's
    a simple rectangle, and nothing else... it can be dragged up and
    down and it will scroll the content.

    You can change the width and skin of the CS3 components using
    an unofficial update to the components provided by gskinner
    (www.gskinner.com). gskinner was involved in creating the Flash CS3
    components along with Adobe (www.adobe.com) and I think Metaliq
    (www.metaliq.com). The unofficial update can be found at
    http://www.gskinner.com/blog/archives/2007/05/variable_scroll.html
    .

  • I am trying to open CR2 files from a Cannon EOS 1DX camera in Photoshop CS6 and I have already updated the Camera Raw Plug in but Photoshop is still giving me the cannot open files dialog box? Help?

    I am trying to open CR2 files from a Cannon EOS 1DX camera in Photoshop CS6 and I have already updated the Camera Raw Plug in but Photoshop is still giving me the cannot open files dialog box? Help?

    Canon 1DX support was added to ACR in version 6.7, 7.1.  An updated CS6 should be at level ACR 8.6.  If your ACR is not at level 8.6 try using CS6 menu Help>Updates.  If that does not install ACR 8.6 try downloading the ACR and DNG 8.6 converter and see if ACR 8.6 will install into your CS6.
    Adobe - Adobe Camera Raw and DNG Converter : For Windows
    Adobe - Adobe Camera Raw and DNG Converter : For Macintosh

  • Error while updating the content in workflow

    Hi,
    I'm getting an error while updating the content in workflow thru the checkout option. i.e. contributor checks in the content - reviewer rejects the content - then contributor checks out and modifies the content as per the reviewer's remarks and while checking in the following error occurs
    Content Server Request Failed
    Unable to check in content item 'HO000128' for workflow. Unable to execute service method 'checkInUpdateRevByID'. (System Error: Runtime error: java.lang.NullPointerException
    at intradoc.server.DocServiceHandler.checkInRevByID(DocServiceHandler.java:248)
    at intradoc.server.DocServiceHandler.checkInUpdateRevByID(DocServiceHandler.java:240)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:585)
    at intradoc.common.IdcMethodHolder.invokeMethod(ClassHelperUtils.java:617)
    at intradoc.common.ClassHelperUtils.executeMethodReportStatus(ClassHelperUtils.java:293)
    at intradoc.server.ServiceHandler.executeAction(ServiceHandler.java:79)
    at intradoc.server.Service.doCodeEx(Service.java:490)
    at intradoc.server.Service.doCode(Service.java:472)
    at intradoc.server.ServiceRequestImplementor.doAction(ServiceRequestImplementor.java:1360)
    at intradoc.server.Service.doAction(Service.java:452)
    at intradoc.server.ServiceRequestImplementor.doActions(ServiceRequestImplementor.java:1201)
    at intradoc.server.Service.doActions(Service.java:447)
    at intradoc.server.ServiceRequestImplementor.executeSubServiceCode(ServiceRequestImplementor.java:1071)
    at intradoc.server.Service.executeSubServiceCode(Service.java:3497)
    at intradoc.server.ServiceRequestImplementor.executeServiceEx(ServiceRequestImplementor.java:942)
    at intradoc.server.Service.executeServiceEx(Service.java:3492)
    at intradoc.server.Service.executeService(Service.java:3476)
    at intradoc.server.DocServiceHandler.determineWorkflowCheckin(DocServiceHandler.java:3833)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:585)
    at intradoc.common.IdcMethodHolder.invokeMethod(ClassHelperUtils.java:617)
    at intradoc.common.ClassHelperUtils.executeMethodReportStatus(ClassHelperUtils.java:293)
    at intradoc.server.ServiceHandler.executeAction(ServiceHandler.java:79)
    at intradoc.server.Service.doCodeEx(Service.java:490)
    at intradoc.server.Service.doCode(Service.java:472)
    at intradoc.server.ServiceRequestImplementor.doAction(ServiceRequestImplementor.java:1360)
    at intradoc.server.Service.doAction(Service.java:452)
    at intradoc.server.ServiceRequestImplementor.doActions(ServiceRequestImplementor.java:1201)
    at intradoc.server.Service.doActions(Service.java:447)
    at intradoc.server.ServiceRequestImplementor.executeSubServiceCode(ServiceRequestImplementor.java:1071)
    at intradoc.server.Service.executeSubServiceCode(Service.java:3497)
    at intradoc.server.ServiceRequestImplementor.executeServiceEx(ServiceRequestImplementor.java:942)
    at intradoc.server.Service.executeServiceEx(Service.java:3492)
    at intradoc.server.Service.executeService(Service.java:3476)
    at intradoc.server.Service.doSubService(Service.java:3465)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:585)
    at intradoc.common.IdcMethodHolder.invokeMethod(ClassHelperUtils.java:617)
    at intradoc.common.ClassHelperUtils.executeMethodEx(ClassHelperUtils.java:279)
    at intradoc.common.ClassHelperUtils.executeMethod(ClassHelperUtils.java:264)
    at intradoc.server.Service.doCodeEx(Service.java:507)
    at intradoc.server.Service.doCode(Service.java:472)
    at intradoc.server.ServiceRequestImplementor.doAction(ServiceRequestImplementor.java:1360)
    at intradoc.server.Service.doAction(Service.java:452)
    at intradoc.server.ServiceRequestImplementor.doActions(ServiceRequestImplementor.java:1201)
    at intradoc.server.Service.doActions(Service.java:447)
    at intradoc.server.ServiceRequestImplementor.executeActions(ServiceRequestImplementor.java:1121)
    at intradoc.server.Service.executeActions(Service.java:433)
    at intradoc.server.ServiceRequestImplementor.doRequest(ServiceRequestImplementor.java:635)
    at intradoc.server.Service.doRequest(Service.java:1707)
    at intradoc.server.ServiceManager.processCommand(ServiceManager.java:359)
    at intradoc.server.IdcServerThread.run(IdcServerThread.java:197))
    Please help to resolve.
    Thanks in advance
    Prasad

    I also get error while updating the content in workflow thru the checkout option as reviewer. i.e. contributor checks in the content - then reviewer either updates the metadata or checks out and modifies the content and while checking in the following error occurs
    Content Server Request Failed
    Unable to update the content item information for 'HO000128'.
    The content ID must be specified.
    Please help to resolve.
    Thanks in advance
    Prasad

Maybe you are looking for

  • Fn+b keys don't work after installing Win7 Ultimate (HP Envy 14 BE)

    Fn+b keys don't work after installing Win7 Ultimate (HP Envy 14 BE)  --not able to use the Beats Speakers. Any software updates I need to install? This question was solved. View Solution.

  • How to Call a WebDynpro application through html page.

    I have created a webDynpro application.How can i call this application through a html page? Thanks Pankaj Kumar

  • Send picture via 3G instead of MMS

    Now I have a Asha 311. In the past when sending pictures via my phone(Nokia X model) was via MMS, extra paid but was included into my subscription at the provider. Now I see when sending a picture it uses automatically 3G connection, is this the only

  • I think my ZEN MICRO is bro

    One day my ZEN MICRO stopped working after a few days of lagging. Now it just starts up and tries to rebuild the library, but it only gets a little bit done then it shuts off after awhile. I've tried clean up and that doesn't work. Does anybody have

  • What language is JAVA written in?

    Hi, What language is JAVA written in? Please give me a simple and short answer for my question. God Bless, Bruce