Updating a JScrollPane

Hi, I've a big problem with a JScrollPane. I have a JScrollPane and in it there is a JPanel with a BorderLayout divided in NORTH and CENTER. In the NORHT and CENTER there are other two JPanel. The problem is that I need to add buttons and label to the center panel but when I add these they do not appear. I tried with validate() and repaint() method for the Center JPanel and then use setVieportView but it does not function.
Do someone had these problems with JScrollPane? Here is an example of code just to show what I mean. This is not the code I use, I do not post it cause it too long:
JPanel centerPanel = new JPanel();
     JScrollPane relationsScrollPane = new JScrollPane();
     public JScrollPane getRelationsSP(){
               relationsScrollPane.setAutoscrolls(true);
               relationsScrollPane .setViewportView(getCenterPanel());          
               return relationsScrollPane ;
     public JPanel getCenterPanel() {
          return centerPanel;
public void addDelComponentRelazioni (){     
          centerPanel.removeAll();
          centerPanel.add(add());
          centerPanel.validate();
          centerPanel.repaint();
          relationsScrollPane.invalidate();
          relationsScrollPane.validate();
          relationsScrollPane.repaint();
          relationsScrollPane .setViewportView(centerPanel);                    
     public Box add() {
          Box boxRelations = Box.createVerticalBox();
          JPanel pannello1 = new JPanel();
          JPanel pannello2 = new JPanel(new FlowLayout(FlowLayout.CENTER));
          pannello1.setLayout(new FlowLayout(FlowLayout.LEFT));
          JLabel labelRelazioni = new JLabel("Relations: ");
          pannello1.add(labelRelazioni);
          boxRelations.add(pannello2);
          return boxRelations;
     I dunno why what I add is not shown although if I use the method centerPanel.getComponentCount() and do not use removeAll(), the number of component increases but they are not shown. I hope someone can help me.

well, the code of add() is
public Box add() {
          Box boxRelations = Box.createVerticalBox();
          JPanel pannello1 = new JPanel();
          pannello1.setLayout(new FlowLayout(FlowLayout.LEFT));
          JLabel labelRelazioni = new JLabel("Relations: ");
          pannello1.add(labelRelazioni);
          boxRelations.add(pannello1);
          return boxRelations;
     }

Similar Messages

  • Make a JScrollBar only update its JScrollPane when the user releases it?

    Hi
    I have a JTable inside a JScrollpane. The JTable gets its data from my TableModel using the getValueAt method in the normal way. It is almost working fine. The one thing left to improve is that I don�t want the JTable to keep trying to get its data while the scrollbar is still being dragged. This is primarily because the latency in fetching the data makes the UI unresponsive - the table model does not keep all rows in memory at one time, but keeps a page of data in memory.
    So, just to clarify, I want the behaviour to be that when the user is still adjusting the value of the scroll bar, the thumb position of the scroll bar moves, but the rows displayed in the JTable do not update. When the user releases the scrollbar, the rows should then update.
    I have almost acheived this by having a second, independent scroll bar on the frame, and an adjustment listener listening for events, like this
    public void adjustmentValueChanged(AdjustmentEvent e){
    if (e.getSource() == scrManual){
    if (!scrManual.getValueIsAdjusting()){
      JScrollBar scrTable = scrPaneResults.getVerticalScrollBar();
    int iManValue = scrManual.getValue();
    int iManMax = scrManual.getMaximum();
    float fManWhere = (float)iManValue / (float)iManMax;
    int iTblMax = scrTable.getMaximum();
    int iTblNewValue = (int)(iTblMax * fManWhere);
      scrTable.setValue(iTblNewValue);
    else
    throw new IllegalArgumentException("I don't know how to handle the adjustment event for " + e.getSource());
    }This is actually working fine, except that I don't want there to be two scrollbars - one in the scroll pane and one extra one. But when I try to make the scrollpane's scrollbar invisible, it remains visible.
    Can anyone tell me either
    (a) how to just have a normal JScrollPane scrollbar, but have it only update its viewport when the value is no longer adjusting (ie scrollbar has been released)
    (b) how to make the JScrollPane's scrollbar still effective, but invisible.
    (c) if the JScrollPane has a no scrollbars policy, how to instead in the code I posted above, set the ScrollPane's position directly.
    Whichever is easiest.
    Thanks for your help
    Mark

    Oh how embarassing! I already asked this question before, and answered it myself! Sorry - I think I am losing the plot
    I�ve hacked it. Turns out that the jScrollPane has a getXXXScrollBar method, which even when you�ve hidden the scrollbars, still works. You just use another scroll bar, register a listener for the mouse released event, and update the jScrollPane�s scroll bar to match the value.

  • How to update a jscrollpane as new tables are added?

    Following is the code of a search form which searches the address based on some search criteria and places the result in the form of table on the panel p3 which has scrollpane sp1. every time the user searches the address a new table adds to the panel but the problem is that as new tables are added to the panel and they get out of the panel the scrollpane does not show the scroll Knob on the scroll bar. please give me the solution that how to update the scrollbar as the new tables are being added to the panel?
    import javax.swing.*;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.border.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.Statement;
    public class Search extends JFrame implements ActionListener
         Container c;
         Toolkit tk;
         JLabel l1; int y=30;
         JPanel p1,p2,p3;     
         JRadioButton rbByName,rbBySirName,rbByID,rbByCity,rbByState;
         JButton btSearch,btView;
         ButtonGroup bgSearch;
         JTextField txtSearch;
         ImageIcon i1;
         Connection con;
         Statement st1;
         PreparedStatement pst1;
         ResultSet rs1;
         Object[][] data;
         public Search()
              super("Search-Address Management System");
              c=getContentPane();
              tk=Toolkit.getDefaultToolkit();
              //setLocation(150,100);
              setSize(1024,768);
              c.setLayout(null);
              setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              defineComponents();
              settingBounds();
              addListeners();
              addComponents();
              JScrollBar sb=new JScrollBar();
              JScrollPane sp1=new JScrollPane(p3,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
              sp1.setBounds(30,300,700,380);
              l1.add(sp1);
              setVisible(true);
         public void defineComponents()
              p1=new JPanel();
              p1.setLayout(null);
              p1.setOpaque(false);
              p2=new JPanel();
              p2.setLayout(null);
              p2.setOpaque(false);
              p3=new JPanel();
              p3.setLayout(null);
              //p3.setOpaque(false);
              i1=new ImageIcon("Images/Main1.jpg");
              l1=new JLabel(i1);
              rbByName=new JRadioButton("First Name");
              rbByName.setOpaque(false);
              rbByName.setForeground(Color.CYAN);
              rbBySirName=new JRadioButton("Last Name");
              rbBySirName.setOpaque(false);
              rbBySirName.setForeground(Color.CYAN);
              rbByState=new JRadioButton("State");
              rbByState.setOpaque(false);
              rbByState.setForeground(Color.CYAN);
              rbByCity=new JRadioButton("City");
              rbByCity.setOpaque(false);
              rbByCity.setForeground(Color.CYAN);
              rbByID=new JRadioButton("ID");
              rbByID.setOpaque(false);
              rbByID.setForeground(Color.CYAN);
              btSearch=new JButton("Search");
              bgSearch=new ButtonGroup();
              txtSearch=new JTextField();
              btSearch=new JButton("Search");
              TitledBorder tb=new TitledBorder("Search Criteria");
              TitledBorder tb1=new TitledBorder("Search");
              p1.setBorder(tb);
              tb.setTitleColor(Color.YELLOW);
              p2.setBorder(tb1);
              tb1.setTitleColor(Color.YELLOW);
         public void settingBounds()
              rbByID.setBounds(20,30,50,20);
              rbByName.setBounds(120,30,100,20);
              rbByState.setBounds(20,70,80,20);
              rbByCity.setBounds(120,70,50,20);
              rbBySirName.setBounds(240,30,100,20);
              p1.setBounds(30,40,400,110);
              p2.setBounds(30,180,400,80);
              //p3.setBounds(30,300,700,380);
              p3.setBackground(Color.BLUE);
              l1.setBounds(0,0,1024,768);
              txtSearch.setBounds(50,210,250,25);
              btSearch.setBounds(320,210,80,25);
              rbByID.setSelected(true);
         public void addListeners()
              btSearch.addActionListener(this);
         public void addComponents()
              p1.add(rbByName);
              p1.add(rbBySirName);
              p1.add(rbByState);
              p1.add(rbByCity);
              p1.add(rbByID);
              c.add(txtSearch);
              c.add(btSearch);
              c.add(p1);
              c.add(p2);
              c.add(l1);
              bgSearch.add(rbByID);
              bgSearch.add(rbByName);
              bgSearch.add(rbBySirName);
              bgSearch.add(rbByCity);
              bgSearch.add(rbByState);
         public void drawtable()
              int i=0,rows=0;
              String[] colNames={"ID","First Name","Last Name","City","State","Operation"};
              String stData=txtSearch.getText();
              try
                   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                   con=DriverManager.getConnection("jdbc:odbc:dsnAddress");
                   if(rbByName.isSelected())
                        pst1=con.prepareStatement("select * from tbaddress where fname=?",ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
                        pst1.setString(1,stData);
                   if(rbByID.isSelected())
                        pst1=con.prepareStatement("select * from tbaddress where ID=?",ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
                        pst1.setString(1,stData);
                   if(rbBySirName.isSelected())
                        pst1=con.prepareStatement("select * from tbaddress where LName=?",ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
                        pst1.setString(1,stData);
                   if(rbByCity.isSelected())
                        pst1=con.prepareStatement("select * from tbaddress where City=?",ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
                        pst1.setString(1,stData);
                   if(rbByState.isSelected())
                        pst1=con.prepareStatement("select * from tbaddress where State=?",ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
                        pst1.setString(1,stData);
                   rs1=pst1.executeQuery();
                   rs1.last();
                   rows=rs1.getRow(); // get no. of rows
                   if(rows==0)
                        JOptionPane.showMessageDialog(this,"***No Record Found***",null,JOptionPane.INFORMATION_MESSAGE,null);
                        return;
                   data=new Object[rows][6]; //     makes an empty two dimensional array of
                                                   //     rows and columns to store data
                   rs1.beforeFirst();
                   while(rs1.next())            //     fills the array with data
                        data[0]=rs1.getString("ID");
                        data[i][1]=rs1.getString("Fname");
                        data[i][2]=rs1.getString("LName");
                        data[i][3]=rs1.getString("City");
                        data[i][4]=rs1.getString("State");
                        data[i][5]="View";
                        i++;
              catch(Exception e)
                   System.out.println("ExceptionSearch="+ e);
              MyTableModel tm=new MyTableModel(data,colNames);
              JTable t1=new JTable(tm)
              // Returning the Class of each column will allow different
    // renderers to be used based on Class
    public Class getColumnClass(int column)
    return getValueAt(0, column).getClass();
              JScrollPane sp=new JScrollPane(t1,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
              sp.setBounds(30,y,600,100);
              p3.add(sp);
              y=y+110;
              ButtonColumn buttonColumn = new ButtonColumn(t1, 5);
         }Edited by: erdeepak on Sep 22, 2008 4:12 AM
    Edited by: erdeepak on Sep 22, 2008 4:24 AM
    Edited by: erdeepak on Sep 22, 2008 4:25 AM
    Edited by: erdeepak on Sep 22, 2008 4:30 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    Don't use null layouts. Learn how to use layout managers.
    The basic design of your frame should be something like this:
    JPanel tablePanel = new JPanel( set your desired layout manager here );
    JScrollPane scrollPane = new JScrollPane( tablePanel );Now when you invoke your search code to create a new table the code will be something like:
    JTable table = new JTable(...);
    tablePanel.add( table );
    tablePanel.revalidate();The revalidate() will invoke the layout manager and the new preferred size of the panel will be calculated and then scrollbars will be added if required.
    The key is to use a layout manager and to revalidate the panel containing the tables.

  • Update a JScrollPane

    Hello everybody.
    I have a JScrollPane called imagePanel. When a button is pressed, this code is fire:
                    grafo = new ImageIcon(imagePath);
                    if (pic==null)
                        pic = new JLabel(grafo);
                    else
                        pic.setIcon(grafo);
                    imagePanel.setViewportView(pic);So, I'm displaying the image stored in "imagePath". The first time everything is ok, the problem is that the image file changes when the program is running. I pretended that the code above updates the image and show the new one but just not work! I don't know what's wrong, please help!
    Thanks in advance.

    Thanks for help.
    Here is the code, if "tree.png" changes when the programa is running, the picture doesn't update.
    import javax.swing.*;
    import java.awt.event.*;
    public class ShowTree extends JFrame implements ActionListener{
        private ImageIcon grafo;
        private JLabel pic=null;
        public ShowTree() {
            initComponents();
            updateButton.addActionListener(this);
        public void actionPerformed(ActionEvent ev)
            Object o = ev.getSource();
            if (o==updateButton)
                grafo = new ImageIcon("/images/tree.png");
                   if (pic==null){
                        pic = new JLabel(grafo);
                        imagePane.setViewportView(pic); 
                   }else
                        pic.setIcon(grafo);
        private void initComponents() {
            imagePane = new javax.swing.JScrollPane();
            updateButton = new javax.swing.JButton();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            updateButton.setText("Update");
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(imagePane, javax.swing.GroupLayout.DEFAULT_SIZE, 431, Short.MAX_VALUE)
                        .addComponent(updateButton, javax.swing.GroupLayout.Alignment.TRAILING))
                    .addContainerGap())
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(imagePane, javax.swing.GroupLayout.PREFERRED_SIZE, 268, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(updateButton)
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            pack();
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new ShowTree().setVisible(true);
        private javax.swing.JScrollPane imagePane;
        private javax.swing.JButton updateButton;
    }Thanks in advance.

  • JTextPane inside JScrollPane resizing when updated

    Hiya all,
    I've been struggling with this problem and checking the forums, but didn't find a solution, so I hope someone can help...at least help me for the nice picture :) It has to do with JTextPane's automatically resizing to their content on a GUI update, rather than scrollbars appearing (the desired result).
    Basically, I have a scenario where I am creating a series of multiple choice answers for a question. Each answer consists of a JTextPane inside a JScrollPane, and a JRadioButton, which are all contained in a JPanel (called singleAnswerPanel). So for 2 answers, I would have 2 of these singleAnswerPanels. There is a one large JPanel that contains all the singleAnswerPanels (called allAnswersPanel). This allAnswersPanel is contained in a JScrollPane. Graphically, this looks like:
       |       JPanel (allAnswersPanel) inside a JScrollPane            |
       |                                                                |
       |  ------------------------------------------------------------  |
       | |     JPanel (singleAnswerPanel)                             | |
       | |    ----------------------------------                      | |
       | |   |  JTextPane inside a JScrollPane  |     * JRadioButton  | |
       | |    ----------------------------------                      | |
       | |                                                            | |
       |  ------------------------------------------------------------  |
       |                                                                |
       |                                                                |
       |  ------------------------------------------------------------  |
       | |     JPanel (singleAnswerPanel)                             | |
       | |    ----------------------------------                      | |
       | |   |  JTextPane inside a JScrollPane  |     * JRadioButton  | |
       | |    ----------------------------------                      | |
       | |                                                            | |
       |  ------------------------------------------------------------  |
       |                                                                |
        ----------------------------------------------------------------So above, I show 2 answers that can be filled in with text. So assuming both answer JTextPanes are filled with text beyond their current border (scrollbars appear as expected) and the user wishes to add more answers. I have a button to add another singleAnswerPanel to the containing JPanel (allAnswersPanel), and then I validate the main JScrollPane that contains the allAnswersPanel as it's view. The problem that occurs is the existing single answer JTextPanes resize to the size of their text and the vertical scrollbars (only vertical ones setup) of the JTextPanes dissappear! My intent is to keep the existing JScrollPanes the same size (with their scrollbars) when a new answer is added.
    The code snippet below shows what gets done when a new answer is added:
    private void createAnswer()
        // The panel that will hold the new single answer JTextPane pane
        // (inside a JScrollPane) and radio button.
        JPanel singleAnswerPanel = new JPanel();
        // Create the text pane for the single answer.
        JTextPane singleAnswerTextPane = new JTextPane();
        Dimension dimensions = new Dimension(200, 30);
        singleAnswerTextPane.setPreferredSize(dimensions);
        singleAnswerTextPane.setMaximumSize(dimensions);
        // Create a scroll pane and add the single answer text pane.
        JScrollPane singleAnswerScrollPane =
         new JScrollPane(singleAnswerTextPane);
        // Create a radio button that is associated with the single
        // answer text pane above.
        JRadioButton singleAnswerRadioButton = new JRadioButton();
        // Add the scroll pane and radio button to the panel (for a single
        // answer).
        singleAnswerPanel.add(singleAnswerScrollPane);
        singleAnswerPanel.add(singleAnswerRadioButton);
        // Add the panel holding a single answer to the panel holding
        // all the answers.
        m_allAnswersPanel.add(singleAnswerPanel);
        // Update the display.  m_allAnswersScrollPane is a JScrollPane
        // that has the m_allAnswersPanel (JPanel) as its view.
        m_allAnswersScrollPane.validate();
    }     Sorry for the length of the message, but I really want to solve this problem. So again, when updating the JScrollPane with validate(), the JTextPane for a single answer resizes to it's contents (plain text currently) and loses it's vertical scrollbars, but I want it to stay the same size and maintain the scrollbars.
    Thanks!

    http://java.sun.com/docs/books/tutorial/uiswing/mini/layout.htmlimport javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Random;
    public class Test extends JFrame {
        int cnt=0;
        Random r = new Random();
        String[] nouns = {"air","water","men","idjits"};
        JPanel mainPanel = new JPanel(new GridBagLayout());
        JScrollPane mainScroll = new JScrollPane(mainPanel);
        JScrollBar mainScrollBar = mainScroll.getVerticalScrollBar();
        public Test() {
         setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
         Container content = getContentPane();
         content.add(new JLabel("QuizMaster 2003"), BorderLayout.NORTH);
         content.add(mainScroll, BorderLayout.CENTER);
         JButton jb = new JButton("New");
         content.add(jb, BorderLayout.SOUTH);
         jb.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent ae) {
              JPanel questionPanel = new JPanel(new GridBagLayout());
              questionPanel.add(new JLabel("Question "+cnt++),
                   new GridBagConstraints(0,0,1,1,0.0,0.0,
                        GridBagConstraints.EAST, GridBagConstraints.NONE,
                        new Insets(1,2,1,2),0,0));
              questionPanel.add(new JLabel("Why is there "+
                            nouns[r.nextInt(nouns.length)]+"?"),
                   new GridBagConstraints(1,0,1,1,0.0,0.0,
                        GridBagConstraints.EAST, GridBagConstraints.NONE,
                        new Insets(1,2,1,2),0,0));
              JTextArea jta = new JTextArea();
              JScrollPane jsp = new JScrollPane(jta);
              jsp.setPreferredSize(new Dimension(300,50));
              questionPanel.add(jsp, new GridBagConstraints(0,1,2,1,0.0,0.0,
                        GridBagConstraints.EAST, GridBagConstraints.BOTH,
                        new Insets(1,2,1,2),0,0));
              mainPanel.add(questionPanel, new GridBagConstraints(0,cnt,1,1,0.0,0.0,
                            GridBagConstraints.EAST,GridBagConstraints.NONE,
                            new Insets(0,0,0,0),0,0));
              mainPanel.revalidate();
              mainScroll.getViewport().setViewPosition(new Point(0, mainPanel.getHeight()));
         setSize(400,300);
         show();
        public static void main( String args[] ) { new Test(); }
    }

  • Stop scroll bar in JScrollPane from updating viewport when dragging knob

    Hi,
    Does anyone know if it's possible to stop the JScrollPane from updating the viewport whilst dragging the knob of the scrollbar and only update once released.
    The problem I have is that the view of the scroll panes viewport is a JList that has an underlying model of a RandomAccessFile which can be very large. So when the user is dragging the scrollbars it will be accessing the file system to retrieve the relevant data for the JList.
    I've tried creating my own JScrollBar and adding a AdjustmentListener to ignore events whilst dragging:
    class MyAdjustmentListener implements AdjustmentListener {
    // This method is called whenever the value of a scrollbar is changed,
    // either by the user or programmatically.
    public void adjustmentValueChanged(AdjustmentEvent evt) {
    Adjustable source = evt.getAdjustable();
    // getValueIsAdjusting() returns true if the user is currently
    // dragging the scrollbar's knob and has not picked a final value
    if (evt.getValueIsAdjusting()) {
    // The user is dragging the knob
    return;
    Looking through the JScrollBar code it has a model that will fire adjustment events anyway, which I suppose are being picked up by the JScrollPane somewhere.
    I could use my own JScrollBar and not add it to the scroll pane and process the adjustment events myself and update the JList but I was wondering if there is a better way.
    Many Thanks,
    Martin.

    Two small changes seem to do the trick. You may want to test it thoroughly though ;)import javax.swing.BoundedRangeModel;
    import javax.swing.DefaultBoundedRangeModel;
    import javax.swing.JFrame;
    import javax.swing.JList;
    import javax.swing.JScrollBar;
    import javax.swing.JScrollPane;
    import javax.swing.SwingUtilities;
    public class OneStepScroller {
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             @Override
             public void run() {
                new OneStepScroller().makeUI();
       public void makeUI() {
          Object[] data = new Object[200];
          for (int i = 0; i < data.length; i++) {
             data[i] = "Item Number " + i;
          JList list = new JList(data);
          JScrollPane scrollPane = new JScrollPane(list);
          BoundedRangeModel model = scrollPane.getVerticalScrollBar().getModel();
          final JScrollBar scrollBar = scrollPane.getVerticalScrollBar();
          scrollBar.setModel(new DefaultBoundedRangeModel(model.getValue(),
                model.getExtent(), model.getMinimum(), model.getMaximum()) {
             int oldValue;
             @Override
             public int getValue() {
                // changed here
                if (!getValueIsAdjusting() && !(oldValue == super.getValue())) {
                   oldValue = super.getValue();
                   // added this
                   fireStateChanged();
                return oldValue;
          JFrame frame = new JFrame("");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.setSize(400, 400);
          frame.setLocationRelativeTo(null);
          frame.add(scrollPane);
          frame.setVisible(true);
    }db

  • JScrollPane too lazy to update...

    I have a textpanel with some JScrollPane attached. The text is written, and scrolling automatically, and all is well.
    However: My program is doing very computing intense tasks and can be busy in one method for maybe 10 minutes at a time, and during execution the log will not be updated so the user will have no idea of what is going on until the program finishes and the JScrollPane finally bothers to update.
    I have tried all kinds of things to force an update, but only the text is updating, scrolling is not. I do not want to mess around with threads, it must be a simple way to force an update of the scrollbars?
    Any ideas???
        public class TextOutputPanel extends JPanel
          // A Swing textarea for display of string info
          JTextArea textArea = null;
          public TextOutputPanel()
            setLayout(new BorderLayout());
            // Create an instance of JTextArea
            textArea = new JTextArea();
            textArea.setEditable(false);
            // Add to a scroll pane so that a long list of
            // computations can be seen.
            JScrollPane areaScrollPane = new JScrollPane(textArea);
            add(areaScrollPane,"Center");
            public void clear()
                textArea.setText("");
            public void println(String str)
              textArea.append(str + "\n");
              textArea.setCaretPosition(textArea.getDocument().getLength());
    //Trying all kinds of weird things here to force an update, but nada :(
                textArea.revalidate();
              this.revalidate();
              this.update(this.getGraphics());
            public void print(String str)
              textArea.append(str);
                this.revalidate();
                this.update(this.getGraphics());
        }

    I do not want to mess around with threadsWhy? You will never learn to develop responsive GUI's
    if you don't. Here is a simple example:
    http://forum.java.sun.com/thread.jspa?forumID=57&threa
    dID=437592
    a simple way to force an update of the scrollbars?Typically you can cause scrolling by using:
    textArea.setCaretPosition(
    textArea.getDocument().getLength() );
    but this may not work because I think it adds code to
    the end of the Event Thread which is currently
    executing your long running task.
    Note in my code above I have already included this. It scrolls fine, but does not update the scrolling until my program is finished running, which is way too late, my user will have died a natural death by then.
    I can force update of almost any swing component with update, ro similar, but it does not work with scrolling :(

  • 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

  • Update JScrollBar Extent when JScrollPane Component Changes Preferred Size

    Hi folks,
    I have an interesting, but concise problem that I've been working on for a few days but haven't had any luck.
    In Java 1.5 or Java6, I have a JScrollPane which contains a JPanel. The settings of the scrollbar (for example, the Extent [the width of the "thumb" or "slider" on the scrollbar]) are determined based on the dimension of the underlying contained component, in particular, the Preferred Size.
    My problem is this. The underlying component has a "zoom" capability, such that the actual size of the component can and does change (i.e., zooming out reduces its preferred size).
    Happily, the consequence of this design is that the "size" or extent of the scrollbar sliders/thumbs adjusts to give visual indication of the proportion of the current view (ViewPort View dimension) to the underlying component's dimension.
    The problem is, the scrollbar sliders do NOT automatically update their size in response to programatically changing the JScrollPane's contained component's PreferredSize. They WILL be updated if I RESIZE the parent JFrame manually.
    But for the life of me, I can't get those sliders to update programatically. I've tried repaint(), update, validate(), etc. on the JScrollPane but no luck.
    I've done a debug to get into the stack trace of the Sun code during run time, and there's a lot going on... there's a doLayout(), a reshape() (deprecated), firing various property changes, but I just can't seem to find a good hook into getting the scrollbar to update its internal Bounds model and repaint accordingly. Calling setBounds() on the JScrollPane I think would trigger it, however, looking at the code.. it seems to ignore firing property events and repainting of the bounds themselves didn't actually change (i.e. no action happens if the current dimension and specified dimension in the argument to setBounds() are the same).
    Any ideas here on how to this to get those sliders to update programatically with a new value for the extent?
    Thanks,
    --Mike                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    Understood! It was my intention to give credit and now I'm happy to do so! I've now assigned the Duke Points. Minor usability issue, it was not obvious how to do this the first time (and I did poke around a little before I gave up earlier in the day, reverting to just assigning him the correct question). I've got it now though! Thanks again--definitely knocked out an issue I was having today and allowed me to move on to add'l development work today.
    All the best!
    --Mike                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Update JScrollPane at runtime

    Hi, well my problem is that I have a few JTextFields and an empty JScrollPane, but when something happens (e.i. a JButton is pressed) the text in the JTextFields should be added to the JScrollPane, but instead of that only the text from the last JTextField (in the example JTextField2) is added one time, no matters how many times the button is pressed, so the problem is:
    How to add all the elements (in this case JLabels with the text from the JTextFields)?
    I guess that all the elements are added but the last one overlaps the others.
    Example:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class ScrollUpdate extends JFrame{
         JTextField text1;
         JTextField text2;
         JScrollPane scroll;
         public ScrollUpdate(){
              text1 = new JTextField("Text 1");
              text1.setPreferredSize(new Dimension(100,22));
              text2 = new JTextField("Text 2");
              text2.setPreferredSize(new Dimension(100,22));
              JPanel panel = (JPanel)getContentPane();
              panel.add(text1, BorderLayout.LINE_START);
              scroll = new JScrollPane();
              scroll.setPreferredSize(new Dimension(100,100));
              panel.add(scroll, BorderLayout.LINE_END);
              panel.add(text2, BorderLayout.CENTER);
              JButton update = new JButton("Update");
              update.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent e){
                        JLabel texto1 = new JLabel(text1.getText());
                        texto1.setAlignmentX(CENTER_ALIGNMENT);
                        scroll.getViewport().add(texto1);
                        JLabel texto2 = new JLabel(text2.getText());
                        texto2.setAlignmentX(CENTER_ALIGNMENT);
                        scroll.getViewport().add(texto2);
                        scroll.getViewport().revalidate();
                        scroll.repaint();
              panel.add(update, BorderLayout.PAGE_END);
              pack();
              setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
              setLocationRelativeTo(null);
         public static void main(String args[]){
              java.awt.EventQueue.invokeLater(new Runnable() {
                   public void run() {
                        try {
                             // Set System L&F
                             JFrame.setDefaultLookAndFeelDecorated(true);
                             JDialog.setDefaultLookAndFeelDecorated(true);
                             UIManager.setLookAndFeel(UIManager
                                       .getSystemLookAndFeelClassName());
                        } catch (ClassNotFoundException e) {
                              //handle exception
                        } catch (Exception e) {
                             try {
                                  UIManager
                                            .setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
                             } catch (Exception f) {
                        ScrollUpdate fenster = new ScrollUpdate();
                        fenster.setVisible(true);
    }

    I think that your problem is that you're adding things directly to the viewport rather than to a JPanel that is viewed in the viewport, say one that uses a GridLayout(0, 1). For e.g.,
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class ScrollUpdate extends JFrame {
      JTextField text1;
      JTextField text2;
      JScrollPane scroll;
      private JPanel innerScrolledPanel = new JPanel(new GridLayout(0, 1));
      public ScrollUpdate() {
        text1 = new JTextField("Text 1");
        text1.setPreferredSize(new Dimension(100, 22));
        text2 = new JTextField("Text 2");
        text2.setPreferredSize(new Dimension(100, 22));
        JPanel panel = (JPanel) getContentPane();
        panel.add(text1, BorderLayout.LINE_START);
        scroll = new JScrollPane(innerScrolledPanel);
        scroll.setPreferredSize(new Dimension(100, 100));
        panel.add(scroll, BorderLayout.LINE_END);
        panel.add(text2, BorderLayout.CENTER);
        JButton update = new JButton("Update");
        update.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            JLabel texto1 = new JLabel(text1.getText());
            texto1.setAlignmentX(CENTER_ALIGNMENT);
            innerScrolledPanel.add(texto1);
            JLabel texto2 = new JLabel(text2.getText());
            texto2.setAlignmentX(CENTER_ALIGNMENT);
            innerScrolledPanel.add(texto2);
            innerScrolledPanel.revalidate();
            scroll.repaint();
        panel.add(update, BorderLayout.PAGE_END);
        pack();
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
      public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
          public void run() {
            ScrollUpdate fenster = new ScrollUpdate();
            fenster.setVisible(true);
    }

  • JScrollPane not updating when Jlist values are changed

    Hello,
    I have a utility where I have a JList with file names inside a JScrollpane. When a user changes directories, the file list changes to the fully qualified names of the files contained in the new directory. The idea is to have the file names show up in the viewport by scrolling the horizontal scroll bar all the way to the right.
    Here's a short break down of what my code. Sorry I can't provide a runnable snippet, I'm a lot crunched for time.
    Arrays.sort(fileArray);
    fileList.setListData(fileArray);
    hBar = FileScrollPane.getHorizontalScrollBar();
    hBar.setValue(hBar.getMaximum());
    The problem is that hbar.getMaximum() always seems to be a step behind. I always get the Maximum width from the last list of files. As I traverse down a directory tree this results in the knob always being not quit all the way to the right.
    I've tried running fileList.revalidate() after the setListData.
    I've tried calling FileScrollPane.setViewportView(fileList) after the setListData.
    I've tried setting the setViewPositon using getWidth from fileList.
    I've tried setting fileList.setPreferredSize(null) after the setListData, then setting the Viewport, then calling revalidate.
    Somehow the JScrollPane just isn't picking up that the jList has changed and updating it's scrollbars model accordingly until after I've run setValue.
    So my question summed up is:
    Is there someway to force JScrollPane to realize that the JList has changed and update it's components accordingly?

    I tried the revalidate and repaint and it didn't seem to work. I can't use threads for political reasons. so I wrote up the following code which demonstrates the problem. Notice that you have to click a button twice to get the correct values displayed in standard out. Any help would be greatly appreciated.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    public class TestJListScroll extends JFrame {
      JScrollPane jScrollPane1 = new JScrollPane();
      String[] listValues1 = {"hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh",
                              "hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh",
                              "hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh",
                              "hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh"};
      String[] listValues2 = {"TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT",
                              "TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT",
                              "TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT",
                              "TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT"};
      String[] listValues3 = {"DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD",
                              "DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD",
                              "DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD",
                              "DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD",
                              "DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD"};
      BorderLayout borderLayout1 = new BorderLayout();
      JPanel jPanel1 = new JPanel();
      JList list = new JList();
      JButton button1 = new JButton();
      JButton button2 = new JButton();
      JButton button3 = new JButton();
      public TestJListScroll() {
        try {
          jbInit();
        catch(Exception e) {
          e.printStackTrace();
      public static void main(String[] args) {
        TestJListScroll testJListScroll1 = new TestJListScroll();
        testJListScroll1.setSize(150,300);
        testJListScroll1.setVisible(true);
      private void jbInit() throws Exception {
        jScrollPane1.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        jScrollPane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        this.getContentPane().setLayout(borderLayout1);
        jPanel1.setMinimumSize(new Dimension(10, 75));
        jPanel1.setPreferredSize(new Dimension(10, 75));
        button1.setText("List 1");
        button1.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(ActionEvent e) {
            button1_actionPerformed(e);
        button2.setText("List 2");
        button2.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(ActionEvent e) {
            button2_actionPerformed(e);
        button3.setText("List 3");
        button3.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(ActionEvent e) {
            button3_actionPerformed(e);
        this.getContentPane().add(jScrollPane1, BorderLayout.CENTER);
        this.getContentPane().add(jPanel1, BorderLayout.SOUTH);
        jPanel1.add(button1, null);
        jPanel1.add(button2, null);
        jPanel1.add(button3, null);
        jScrollPane1.getViewport().add(list, null);
        list.addPropertyChangeListener("model", new PropertyChangeListener() {
          public void propertyChange(PropertyChangeEvent e) {
            list_ModelChanged(e);
      void button1_actionPerformed(ActionEvent e) {
        System.out.println("button 1 pressed");
        list.setListData(listValues1);
      void button2_actionPerformed(ActionEvent e) {
        System.out.println("button 2 pressed");
        list.setListData(listValues2);
      void button3_actionPerformed(ActionEvent e) {
        System.out.println("button 3 pressed");
        list.setListData(listValues3);
      private void list_ModelChanged(PropertyChangeEvent e) {
        list.revalidate();
        list.repaint();
        BoundedRangeModel model = jScrollPane1.getHorizontalScrollBar().getModel();
        System.out.println("   file list width = " + list.getWidth());
        System.out.println("   Maximum = " + model.getMaximum());
        System.out.println("   extent = " + model.getExtent());
        model.setValue(model.getMaximum() - model.getExtent());
        System.out.println("   value = " + model.getValue());
    }Thanks,
    Jason

  • JScrollPane update???

    I am using JTextArea object in a JScrollPane object.
    how to make the JScrollPane automatically scroll down to follow the update values in JTextArea?
    Thanks...

    you need to set the Caret position use it as
    txt.setCaretPosition(txt.getText().length());
    where u r adding text in the text area .
    Here txt is the name of your JTextArea Object....

  • Update jscrollpane / viewable area when click on JButton

    Hi all,
    I have a JTable inside a JScrollPane. I use some JButtons to do some row selections on the JTable.
    I would like the viewable area / scroll pane to increment when the row selections are changed using the JButtons. By doing this I wish to see, at the bottom of the scrollpane the row that was selected by the JButton. (i.e. I want the behaviour you get if you select a row then use the arrow keys to move up and down the rows).
    Below is a single class which sets up the table buttons etc. A lot of the length comes from the table's data so don't worry.
    If you run it and click on the "Next team member" button you will see what it currently does.
    package ui;
    import java.awt.BorderLayout;
    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.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.ListSelectionModel;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    import javax.swing.table.AbstractTableModel;
    * Class Window displays a frame in which there is a table and some buttons to
    * manipulate the table.  It is used as an example of manipulating table data.
    public class Window extends JFrame
         * Data members.
         * ========================================================================
         private JTable table;
         private JScrollPane scroller;
         private final static int noButtons= 4;
         private final static String[] buttonNames=
              "Pick for team", "Unpick", "Next team member", "Next non-team member"
         private JButton[] buttons= new JButton[noButtons];
          * End of Data members.
          * ========================================================================
          * Constructor.
          * ========================================================================
         public Window()
              setTitle("Testing table manipulation");
              setSize(1024,300);
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              setLayout(new BorderLayout());
              // Make the table.
              table= makeTable();
              // Create the scroll pane.
              scroller= new JScrollPane(table);
              scroller.setSize(800,300);
              // Create buttons to manipulate the data.
              for (int i= 0; i < noButtons; i++)
                   buttons= new JButton(buttonNames[i]);
                   buttons[i].addActionListener(new ButtonHandler(buttonNames[i]));
              // A panel for the buttons.
              JPanel buttonPanel= new JPanel();
              buttonPanel.setSize(224,300);
              for (int i= 0; i < noButtons; i++)
                   buttonPanel.add(buttons[i]);
              // Add everything to the frame.
              JPanel contentPane= (JPanel)this.getContentPane();
              contentPane.add(scroller,BorderLayout.WEST);     
              contentPane.add(buttonPanel,BorderLayout.EAST);
              // Make visible.
              setVisible(true);
         * End of Constructor.
         * ========================================================================
         * Methods.
         * ========================================================================
         // Makes a table.
         private JTable makeTable()
              // The table model.     
              TableModel tm= new TableModel();
              // The actual table.
              JTable jt= new JTable(tm);
              // The table's selection model.
              jt.getSelectionModel().addListSelectionListener(new RowSelectionListener());
         return jt;
         * End of Methods.
         * ========================================================================
         * Inner classes
         * ========================================================================
         * Inner class TableModel manages the table model for the table in Window.
         * This class contains the real data and methods to manipulate that data.
         private class TableModel extends AbstractTableModel
              // Data.
              Vector<String> columns;
              Vector<Vector> rows;
              public TableModel()
                   columns= new Vector<String>();
                   rows= new Vector<Vector>();
                   columns.add("Surname");
                   columns.add("Firstname");
                   columns.add("SquadNo");
                   columns.add("Position");
                   columns.add("In team?");
                   Vector<Object> v= new Vector<Object>();
                   v.add("McGeady");
                   v.add("Aiden");
                   v.add(46);
                   v.add("AM RLC");
                   v.add(true);
                   rows.add(v);
                   v= new Vector<Object>();
                   v.add("McGovern");
                   v.add("Michael");
                   v.add(47);
                   v.add("GK");
                   v.add(false);
                   rows.add(v);
                   v= new Vector<Object>();
                   v.add("Zurawski");
                   v.add("Maciej");
                   v.add(7);
                   v.add("F C");
                   v.add(true);
                   rows.add(v);
                   v= new Vector<Object>();
                   v.add("McManus");
                   v.add("Stephen");
                   v.add(44);
                   v.add("D LC");
                   v.add(true);
                   rows.add(v);
                   v= new Vector<Object>();
                   v.add("Virgo");
                   v.add("Adam");
                   v.add(4);
                   v.add("D/F RC");
                   v.add(false);
                   rows.add(v);
                   v= new Vector<Object>();
                   v.add("Feguson");
                   v.add("Barry");
                   v.add(6);
                   v.add("DM C");
                   v.add(false);
                   rows.add(v);
                   v= new Vector<Object>();
                   v.add("Boyd");
                   v.add("Kris");
                   v.add(19);
                   v.add("S C");
                   v.add(false);
                   rows.add(v);
                   v= new Vector<Object>();
                   v.add("Prso");
                   v.add("Dado");
                   v.add(9);
                   v.add("S C");
                   v.add(false);
                   rows.add(v);
                   v= new Vector<Object>();
                   v.add("Gordon");
                   v.add("Craig");
                   v.add(1);
                   v.add("GK");
                   v.add(false);
                   rows.add(v);
                   v= new Vector<Object>();
                   v.add("Pressley");
                   v.add("Steven");
                   v.add(4);
                   v.add("D RC");
                   v.add(false);
                   rows.add(v);
                   v= new Vector<Object>();
                   v.add("Hartley");
                   v.add("Paul");
                   v.add(7);
                   v.add("AM RC");
                   v.add(false);
                   rows.add(v);
                   v= new Vector<Object>();
                   v.add("Smith");
                   v.add("John");
                   v.add(10);
                   v.add("AM L");
                   v.add(false);
                   rows.add(v);
                   v= new Vector<Object>();
                   v.add("Smith");
                   v.add("John");
                   v.add(10);
                   v.add("AM L");
                   v.add(false);
                   rows.add(v);
                   v= new Vector<Object>();
                   v.add("Smith");
                   v.add("John");
                   v.add(10);
                   v.add("AM L");
                   v.add(false);
                   rows.add(v);
                   v= new Vector<Object>();
                   v.add("Smith");
                   v.add("John");
                   v.add(10);
                   v.add("AM L");
                   v.add(false);
                   rows.add(v);
                   v= new Vector<Object>();
                   v.add("Smith");
                   v.add("John");
                   v.add(10);
                   v.add("AM L");
                   v.add(false);
                   rows.add(v);
                   v= new Vector<Object>();
                   v.add("Smith");
                   v.add("John");
                   v.add(10);
                   v.add("AM L");
                   v.add(false);
                   rows.add(v);
                   v= new Vector<Object>();
                   v.add("Smith");
                   v.add("John");
                   v.add(10);
                   v.add("AM L");
                   v.add(false);
                   rows.add(v);
                   v= new Vector<Object>();
                   v.add("Smith");
                   v.add("John");
                   v.add(10);
                   v.add("AM L");
                   v.add(false);
                   rows.add(v);
                   v= new Vector<Object>();
                   v.add("Smith");
                   v.add("John");
                   v.add(10);
                   v.add("AM L");
                   v.add(false);
              // AbstractTableModel methods.
              // The number of rows.
              public int getRowCount()
                   return rows.size();
              // The number of columns.
              public int getColumnCount()
                   return columns.size();
              // The value at row, column.
              public Object getValueAt(int row, int column)
                   return (rows.elementAt(row)).elementAt(column);
              // Allows the column names to be set.
              // Also obtains the column name at column.
              public String getColumnName(int column)
                   return columns.elementAt(column);
              // Allows boolean columns to be displayed as checkboxes.
              public Class getColumnClass(int columnIndex)
                   return getValueAt(0,columnIndex).getClass();
              // Is the cell at row, column editable?
              public boolean isCellEditable(int row, int column)
                   return true;
              // Allows the data to be changed.
              public void setValueAt(Object o, int row, int column)
              (rows.elementAt(row)).setElementAt(o, column);
              fireTableDataChanged(); // Very important.     
         * Inner class RowSelectionListener handles selection events on a Window
         * instance's table rows.
         private class RowSelectionListener implements ListSelectionListener
              public void valueChanged(ListSelectionEvent e)
                   //Ignore extra messages.
         if (e.getValueIsAdjusting())
         return;
         ListSelectionModel lsm = (ListSelectionModel)e.getSource();
         if (!lsm.isSelectionEmpty())
         int selectedRow = lsm.getMinSelectionIndex();
         String s= "";
         for (int i= 0; i < table.getColumnCount(); i++)
              s+= (table.getValueAt(selectedRow, i)).toString() + " ";
         System.out.println(s); // Would be appended to the textarea.
         * Inner class buttonHandler handles events from the buttons.
         private class ButtonHandler implements ActionListener
              // Data members.
              private String name;
              // Constructor.
              // Sets the name.
              public ButtonHandler(String nm)
                   name= nm;
              public void actionPerformed(ActionEvent ae)
                   if (name.equals(buttonNames[0])) // "Pick for team"
                        changeStatus(true);
                   else if (name.equals(buttonNames[1])) // "Unpick"
                        changeStatus(false);
                   else if (name.equals(buttonNames[2])) // "Next team member"
                        int row;
                        if (table.getSelectionModel().isSelectionEmpty())
                        row= -1;
                        else
                        row= table.getSelectedRow();
                        // From next row until end of rows, look for correct value.
                        while (true)
                        for (int i= (row+1); i < table.getRowCount(); i++)
                             // The in team? column is the last one.
                             int inTeamColumn= table.getColumnCount()-1;
                             if (((Boolean)table.getValueAt(i,inTeamColumn)).booleanValue() == true)
                                  table.getSelectionModel().setSelectionInterval(i, i);
                                  return;
                        // Go back to the start.
                        row= -1;
                   else if (name.equals(buttonNames[3])) // "Next non-team member"
                        int row;
                        if (table.getSelectionModel().isSelectionEmpty())
                        row= -1;
                        else
                        row= table.getSelectedRow();
                        // From next row until end of rows, look for correct value.
                        while (true)
                        for (int i= (row+1); i < table.getRowCount(); i++)
                             // The in team? column is the last one.
                             int inTeamColumn= table.getColumnCount()-1;
                             if (((Boolean)table.getValueAt(i,inTeamColumn)).booleanValue() == false)
                                  table.getSelectionModel().setSelectionInterval(i, i);
                                  return;
                        // Go back to the start.
                        row= -1;
              // Changes whether they were picked or unpicked.
              // picked = true means they were picked.
              private void changeStatus(boolean picked)
                   int row= table.getSelectedRow();
                   if (row < 0)
                        // Should be a dialogue (or do nothing?)
                        System.out.println("Error! No row was selected.");
                   else
                        for (int i= 0; i < table.getColumnCount(); i++)
                             if (table.getColumnName(i).equals("In team?"))
                                  boolean boolVal= (Boolean)table.getValueAt(row, i);
                                  if (boolVal == !picked)
                                  table.setValueAt(picked, row, i);
                        // Reselect the row.
                        table.getSelectionModel().setSelectionInterval(row, row);
              // Find the next one who has value picked.
              private void findNext(boolean picked)
         * End of Inner Classes.
         * ========================================================================
    * Test program.
    * ========================================================================
         public static void main(String[] args)
              new Window();
         * End of Test program.
         * ========================================================================

    why do you make lots of points that don't help before answering the question?They may not help with the immediate problem, but they may help with future problems, if you take the time to understand what I am saying.
    If I make the points after answering the question, then you probably won't read them.
    You should read about packages - they let you give classes the same name if they are in different packages.Just because you can do something doesn't mean you should
    A class name should be descriptive. Window is not very descriptive.
    Even for a simple text case I would use something like WindowTest.
    If I am just reading your source code and I see a line like the following:
    Window window = new Window();The first thing that comes to mind is that you are trying to create an AWT Window. How do I know that you've given your class a package name? I should not need to look at the package or import statments to know what class you are talking about. Any time you can reduce confusion the better.
    Created my own TableModel because this program is a mock up of a more complicated oneWhy go to all this trouble for a simple demo program? Your question is about scrolling, not the data in the table. I would use:
    JTable table = new JTable(30, 5);The less clutter you have in your demo program. The easier it is for us to see whats happening.
    I mention the DefaultTableModel, because the majority of people who post table related questions on the forum don't fully understand how TableModels work or the flexibility of the DefaultTableModel and end up getting themselves into trouble by trying to unnecessarily extend AbstractTableModel. Remember your last posting was about an incorrect implementation of a TableModel when you couldn't get the column names to work.
    Why don't you use JDK 1.5 - why not download it?JDK1.4 does everthing I want.
    I need generics in my app (booleans, strings and numbers in my vectors) so I use them.You don't need to use Generics. You just decided you wanted to use them. The TableModel still stores Integers and Booleans etc. The compiler just does the conversion for you.
    Another design is to create a class to hold your data and then create a TableModel based on this class. For example here is an example of a TableModel that holds Stock Securities:
    import java.util.*;
    import javax.swing.table.*;
    public class SecurityTableModel extends AbstractTableModel
         List list;
         private static String[] columnNames =
              "Security",
              "Symbol",
              "Exchange",
              "Type",
              "Asset Class",
              "Goal"
         public SecurityTableModel()
              SecurityManager manager = SecurityManager.getSharedInstance();
              list = manager.getList();
              Collections.sort( list );
         public int getColumnCount()
              return columnNames.length;
         public int getRowCount()
              return list.size();
         public String getColumnName(int col)
              return columnNames[col];
         public Object getValueAt(int row, int col)
              Security security = (Security)list.get( row );
              switch (col)
                   case 0: return security.getName();
                   case 1: return security.getSymbol();
                   case 2: return security.getExchange();
                   case 3: return security.getType();
                   case 4: return security.getAssetClass();
                   case 5: return security.getGoal();
              return null;
         public Class getColumnClass(int c)
              return String.class;
         public boolean isCellEditable(int row, int col)
              return false;
         public void xxxsetValueAt(Object value, int row, int col)
    } Your getter and setter of the Security class then convert the data as required.
    who is OP? Original Poster

  • Getting a JScrollPane to update correctly

    Hi. I have a JTextArea in a JScrollPane. Now you can send messages into this textarea, and as the contents grows, I want the scrollpane to adjust and "follow" the textarea as it grows, like in a chat or whatever. There's been a lot of topics on this one, but I can't still make it work. Any ideas?

    Thanks for that tip, Ofcourse I should post the code, there are different ways to set up a scrollpane. I did like this:
    JTextArea area = new JTextArea();
    JScrollPane scroll = new JScrollPane(area);And now it works. If anyone have a similar problem, this is what should be done when the textarea receives new text ( I got it from the forum):
    area.setCaretPosition(area.getText().length());
    area.revalidate();
    area.setPreferredSize(new Dimension(100,y));where y is a way to calculate the needed size of area to display all text.
    Thanks for the help

  • JScrollPane freezes when updating JTable in viewport

    I have the same problem that is described in this bug:
    http://developer.java.sun.com/developer/bugParade/bugs/4495213.html
    I don't understand the workaround. Is that the developer's class (BasicTableUI.java)? Anyone else experiencing this problem? How long does it generally take for these bugs to be fixed?
    Thanks.

    BasicTableUI is one of the JDK's classes:
    javax.swing.plaf.basic.BasicTableUI
    They are suggesting altering the source code for that class and replacing the class in your JVMs standard rt.jar with the modified class.

Maybe you are looking for

  • How to connect a 2008 Apple HD Cinemadisplay to a new MacBook Pro 17"?

    How to connect a 2008 Apple 23" HD Cinema display with a new MacBook Pro 17"?

  • Block release of Purchase Order (of  type contract)

    Hi Experts, I am facing a problem where I have to cancel the release of PO using some FM / BAPI. I was using the FM "BAPI_PO_RESET_RELEASE" to change the release status of PO from 2 (released) to 1(blocked). But this BAPI has some restriction and it

  • NI-DAQmx task works in MAX or DAQ Assistant test panel but not in LabVIEW

    I am attempting to read a single AI channel from a PCI-6024E card via an SCB-68. I have created a NI-DAQmx Analog Input Voltage Task in MAX for this channel, sampling in contiuous aquisition mode at 100 kHz, 10000 samples at a time, with RSE terminal

  • How do i get my sound to work?

    How do i get my sound to come back on? It won't play back any sound even though i press play on itunes, and another music player. Even after I restarted the computer.

  • Key Fig Non Cumulative

    I have 0GIDATE as KF and want to know which option of Non Cumulative to choose between non *** value with non *** value change or noncum value with in-and out flow? I did go through the forum but could not get an appropriate one for a data kf. Basica