JScrollPanel Problem

I am trying to create a results page for some testing software. The page has a JScrollPanel that contains a JPanel. On that JPanel I am using a GridBagLayout so that I can present the Q#, question, correct answer, thier answer, and the next row down will contain an explination of my answer that is spanned across all 4 columns.
The problem is that when I do this I would like to force the JScrollPane to only be as wide as the screen and force it to streatch downward as much as is needed. However if I just let the layout managers take care of things the TextAreas continue to expand horizontally and are not forced into multiple lines. If I set a preferred area on the JPanel then I think I am getting pretty close to the result that I want however there are no scroll bars on the scrollpane. When When I force the scrollbars to show up they show up blank as if there is nothing up or down, but I can see that the there must be something both up and down as it will show me the middle range of questions on the screen and cut off the first couple and last couple of questions.
I have included the code below of what is happen when this form is created. I am not adverse to changing the layout if anyone has a suggestion of what might work better, but this seamed like the best layout to me.
Thanks in advance for any advice.
Jason
    public frmResults(frmBook book, Quiz q, Student user) {
        initComponents();
        GridBagConstraints gridBagConstraints;
        _quiz = q;
        _student = user;
        _bookForm = book;
        _bookForm.setVisible(false);
        int _rows = _quiz.get_maxSize();
        panHolder.setLayout(new GridBagLayout());
        //make sure that the area of the text is not wider than the screen
        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
        int w = this.getSize().width;
        dim.width = (dim.width-w)/2;
        dim.height = 5000; //I have tried many diffrent things here to no avail.
        panHolder.setPreferredSize(dim);
        int _y = 0;
        //load form with all of the questions
        for (int i=1; i<_rows; i++){
            Question _tmp = _quiz.get_QuestionAt(i);
            //Label for Question Number
            JLabel lblNum = new JLabel(i + ". ");
            gridBagConstraints = new java.awt.GridBagConstraints();
            gridBagConstraints.fill = gridBagConstraints.BOTH;
            gridBagConstraints.anchor = gridBagConstraints.NORTHWEST;
            gridBagConstraints.insets = new Insets(1,1,1,1);
            gridBagConstraints.gridx = 0;
            gridBagConstraints.gridy = _y;   
            //gridBagConstraints.weightx = .05;
            panHolder.add(lblNum, gridBagConstraints);
            //label for question text
            JLabel lblQuestion = new JLabel(_tmp.getQuestion());
            gridBagConstraints.gridx = 1;
            gridBagConstraints.gridy = _y;
            gridBagConstraints.weightx = 1;
            panHolder.add(lblQuestion, gridBagConstraints);
            //text area to input aswer
            JTextArea _txtAns = new JTextArea();
            JTextArea _txtExplain= new JTextArea(_quiz.getExplination(i));
            JTextArea _txtGivenAns = new JTextArea();
            _txtAns.setLineWrap(true);
            _txtGivenAns.setLineWrap(true);
            _txtAns.setWrapStyleWord(true);
            _txtGivenAns.setWrapStyleWord(true);
            _txtExplain.setLineWrap(true);
            _txtExplain.setWrapStyleWord(true);
            String _ans = _quiz.getResult(i, _student.getId());
            _txtAns.setText(removeQuotes(_ans));
            //format answerGiven
            String _ansGiven = _quiz.getAnswerGiven(i, _student.getId());
            _txtGivenAns.setText(_ansGiven);
            //set correct colors
            if(_ans.equals("Correct")){
                _txtAns.setForeground(new java.awt.Color(0,128,0));
                _txtExplain.setForeground(new java.awt.Color(0,128,0));
            else{
                _txtAns.setForeground(java.awt.Color.red);
                _txtExplain.setForeground(java.awt.Color.red);
            //add txtAns
            gridBagConstraints.gridx = 2;
            gridBagConstraints.gridy = _y;      
            gridBagConstraints.weightx = 0;
            panHolder.add(_txtAns, gridBagConstraints);
            //add txtAnswerGiven
            gridBagConstraints.gridx = 3;
            gridBagConstraints.gridy = _y;      
            //gridBagConstraints.weightx = .1;
            panHolder.add(_txtGivenAns, gridBagConstraints);
            //on the next line give explination
            _y++;
            gridBagConstraints.gridy = _y;
            gridBagConstraints.gridx = 1;
            gridBagConstraints.gridwidth = 4;           
            panHolder.add(_txtExplain, gridBagConstraints);
            _y++;
        this.setExtendedState(Frame.MAXIMIZED_BOTH);     
        dim.height = panHolder.getHeight();
        jScrollPane1.setMaximumSize(dim);
        jScrollPane1.setPreferredSize(dim);
        jScrollPane1.getViewport().setPreferredSize(dim);
        pack();
        panHolder.revalidate();
        jScrollPane1.revalidate();
        jScrollPane1.getViewport().revalidate();
    }

Actually in the example I posted panHolder is the panel that is inside of the scrollpane. panHolder is the one that I am attempting to tweak. However I have also tried tweaking the size of the scroll pane in order to solve the problem with no luck.
Essentialy what I want to do is force the scrollpane to not be larger than the screen. However it seams that no matter what I try to set prefered size on it causes the scrollpane to think that it should not scroll anywhere.
I will try to put together an example this afternoon to better demonstrate what is going on.
Thanks for the quick reply.
Jason

Similar Messages

  • JScrollpanel Top align problem

    Hi,ALL
    I have a JPanel holds two Objects(JTree and JList);
    So
    The main JPanel is created with FlowLayout.LEFT
    I create two JScrollPanel to hold JTree and JList,
    since JTree is long and JList is short.
    so everytime JList is in the middle of the JScrollPanel.
    I want to align them from top, how to add a Viewport to JScrollPanel from TOP-align, not automatically CENTER-align?
    Thanks in avanced

    At the risk of sounding like the Office Paperclip... it looks like you're writing an explorer.
    If so, use a JSplitPane. Set the left component to a JScrollPane containing a JTree and the right component to a JScrollPane containing a JList.

  • JScrollPanel basic problem

    Hi,
    would be grateful if someone could help out with this basic problem:
    I'm using a JTextArea that displays additional text added using the append() method in a java2 1.4 program, but I need it to automatically scroll down to show the latest line of text added whereas the panel by default requires the user to scroll down.
    Thanks,
    Allan.

    try looking at setCaretPosition(int position).

  • Layout Problem in swings

    I have an Layout problem. My Applications consists of a label and a panel in which some more labels are present.
    The panel should contain the scrollbar in order to view all the label that excced the size of the panel.This label and a panel should be adjacent to each other.
    My problem is, I am not getting the scroll bar to the panel when I am adding the label that excced the size of the panel, when I am adding the label adjacent to this label.

    Did you use JScrollPanel? If not, use it.

  • Problems with JList & JTable in Netbeans 5.5

    Hi,
    Netbeans provides good GUI building provider.
    But when i am adding JList inside panel
    and trying to add elements its giving error.
    So how to modify read only code in netBeans 5.5 generated code. ??
    There is problem accessing JList variable to be modify.
    HOW TO ACHIEVE THIS ????
    because When you add JList in your GUI Part.
    Netbeans generates code automatically.
    we can't change it.
    HOW TO DO it... ???

    I have had similar trouble.
    In NetBeans Guieditor, JList and JTable are automatically created in a JScrollPanel. This is good as it saves you lots of formatting.
    PROBLEM: when you click/select the JTable or JList in the GUI Editor the Properties box (right hand side ) only shows properties for the JScrollPane.
    So you will only be able to edit Init code etc for the JScrollPane
    SOLUTION: The "Members View" is a list of members (Panels, Objects, etc) on the left hand side of the screen.
    The JScrollPane is listed there. You simply click on this to expand and select the JTable/JList that it contains.
    When you select the JTable/JList the Properites window (right side of screen) now shows the properties for the component you really want to deal with.
    The code options are very powerful.

  • Problem with ScrollPanel

    Following is my code. I have created the components and added then to JPanel and then that JPanel is added the JScrollPanel.
    My scroll bars are not working. Please see my code and tell me how they will work.
    You have to enter an integer in the first text feld and then to clink the button "Create text fields." The problem is that when the text fileds are created the scrollbars don't work.
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    * Author Waheed-Ul-Haq ( BS(CS)-8 )
    * Round Robin Scheduling.
    public class Samulation2
         JPanel pane;
         JLabel label1;
         JTextField entProcesfld;
         JTextField quantumTF;
         JButton buttCreat;
         JButton buttReslt;
         JLabel usrProcesID[];
         JTextField usrArivTam[];
         JTextField usrBrstTam[];
         JTextField usrTurnTam[];
         JTextField usrRespTam[];
         JTextField usrWaitTam[];
         int processes;
         int startTam[];
         int complitionTam[];
         int remainJob[];
         int totalCompTam;
         Dimension area;
         public JComponent createComponents()
         pane = new JPanel();
         pane.setLayout (null);
         label1 = new JLabel();     //Label for to tell user to enter no of Processes.
         label1.setText("Enter the no. of Processes");
         pane.add(label1);
         label1.setBounds(20, 25, 150, label1.getPreferredSize().height);
         entProcesfld = new JTextField();     //TextField to enter no of processes.
         entProcesfld.setToolTipText("Enter the no of Processes.");
         pane.add(entProcesfld);
         entProcesfld.setBounds(180, 25, 100, entProcesfld.getPreferredSize().height);
         JLabel quantumLab = new JLabel();     //Label for the Quantiun.
         quantumLab.setText ("Enter the Quantum");
         pane.add (quantumLab);
         quantumLab.setBounds (300, 25, 110, quantumLab.getPreferredSize ().height);
         quantumTF = new JTextField();
         quantumTF.setToolTipText ("Quantum");
         pane.add (quantumTF);
         quantumTF.setBounds (415, 25, 100, quantumTF.getPreferredSize ().height);
         buttCreat = new JButton();          //Button to create the TextFields.
         buttCreat.setText("Create TextFields");
         pane.add(buttCreat);               //Adding cutton to Jpane.
         buttCreat.setBounds(new Rectangle(new Point(120, 60), buttCreat.getPreferredSize()));
         buttCreat.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        buttCreatActionPerformed(e);
                   } } );          //ActionListenr to Create the TextFields.
         buttReslt = new JButton();          //Button to show the result of the Scheduling.
         buttReslt.setText("View Results");
         pane.add(buttReslt);               //Adding button to Jpane.
         buttReslt.setBounds(new Rectangle(new Point(275, 60), buttReslt.getPreferredSize()));
         buttReslt.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        buttResltActionPerformed(e);
                   } } );          //ActionListener to Show the results of Scheduling.
         return pane;
         }     //-------END of Component createComponents()--------//
         private void buttCreatActionPerformed(ActionEvent e)     //Action to Create the TextFields.
                   processes = Integer.parseInt (entProcesfld.getText ());
                   System.out.println (processes);
                   JLabel Labproces = new JLabel();     //Label of Processes.
                   Labproces.setText("Processes");
                   pane.add(Labproces);
                   Labproces.setBounds(new Rectangle(new Point(15, 105), Labproces.getPreferredSize()));
                   JLabel labArivTam = new JLabel();     //Label of Arival time.
                   labArivTam.setText("Arrial Time");
                   pane.add(labArivTam);
                   labArivTam.setBounds(new Rectangle(new Point(90, 105), labArivTam.getPreferredSize()));
                   JLabel labBrsTam = new JLabel();     //Label of Burst Time.
                   labBrsTam.setText("Burst Time");
                   pane.add(labBrsTam);
                   labBrsTam.setBounds(new Rectangle(new Point(165, 105), labBrsTam.getPreferredSize()));
                   JLabel labTurnTam = new JLabel();     //Label of TurnAround Time.
                   labTurnTam.setText("TurnAround");
                   pane.add(labTurnTam);
                   labTurnTam.setBounds(new Rectangle(new Point(240, 105), labTurnTam.getPreferredSize()));
                   JLabel labResTam = new JLabel();     //Label of Response Time.
                   labResTam.setText("Response Time");
                   pane.add(labResTam);
                   labResTam.setBounds(new Rectangle(new Point(315, 105), labResTam.getPreferredSize()));
                   JLabel labWaitTam = new JLabel();     //Label of Waiting Time.
                   labWaitTam.setText("Waiting Time");
                   pane.add(labWaitTam);
                   labWaitTam.setBounds(new Rectangle(new Point(410, 105), labWaitTam.getPreferredSize()));
                   //----Creating Dynamic JLabels------//
                   usrProcesID  = new JLabel[processes];     /* Makes an array */
                   int yXis = 125;          //Variable for Y-axix of JLabel.
                   for(int i=0; i<processes; i++)      /* i takes each value from 0 to processes-1 */
                    usrProcesID[i] = new JLabel("P" + i);      /* Makes a JLabel at an array place */
                    pane.add(usrProcesID);      /* Adds a JLabel (rather than an array) */
    usrProcesID[i].setBounds(new Rectangle(new Point(28, yXis), usrProcesID[i].getPreferredSize()));
    yXis = yXis + 25;     /* Increses the Y-axis to show JLabels. */
    }     //EndFor     
    //-------End Dynamic JLabels---------//               
                   //-----Creating Dynamic Arival Time TextFields-----//
                   usrArivTam = new JTextField[processes];          /* Makes an array */
                   yXis = 125;          //Variable for Y-axix of JTextField.
                   for(int i=0; i<processes; i++)      /* i takes each value from 0 to processes-1 */
    usrArivTam[i] = new JTextField();     /* Makes a JTextField at an array place */
    usrArivTam[i].setToolTipText("Enter Arival Time.");
    pane.add(usrArivTam[i]);      /* Adds a JTestField (rather than an array) */
    usrArivTam[i].setBounds(100, yXis, 35, usrArivTam[i].getPreferredSize().height);
    yXis = yXis + 25;     /* Increses the Y-axis to show JTextFields. */
    }     //EndFor     
    //-----End Dynamic Arival Time TextFields.-----//
                   //-----Creating Dynamic Burse Time TextFields-----//
                   usrBrstTam = new JTextField[processes];          /* Makes an array */
                   yXis = 125;          //Variable for Y-axix of JTextField.
                   for(int i=0; i<processes; i++)      /* i takes each value from 0 to processes-1 */
    usrBrstTam[i] = new JTextField();     /* Makes a JTextField at an array place */
    usrBrstTam[i].setToolTipText("Enter Burst Time.");
    pane.add(usrBrstTam[i]);      /* Adds a JTestField (rather than an array) */
    usrBrstTam[i].setBounds(180, yXis, 35, usrBrstTam[i].getPreferredSize().height);
    yXis = yXis + 25;     /* Increses the Y-axis to show JTextFields. */
    }     //EndFor     
    //-----End Dynamic Burst Time TextFields.-----//
    //-----Creating Dynamic TurnAroud Time TextFields-----//
                   usrTurnTam = new JTextField[processes];          /* Makes an array */
                   yXis = 125;          //Variable for Y-axix of JTextField.
                   for(int i=0; i<processes; i++)      /* i takes each value from 0 to processes-1 */
    usrTurnTam[i] = new JTextField();     /* Makes a JTextField at an array place */
    usrTurnTam[i].setEditable(false);
    pane.add(usrTurnTam[i]);      /* Adds a JTestField (rather than an array) */
    usrTurnTam[i].setBounds(260, yXis, 35, usrTurnTam[i].getPreferredSize().height);
    yXis = yXis + 25;     /* Increses the Y-axis to show JTextFields. */
    }     //EndFor     
    //-----End Dynamic TurnAround Time TextFields.-----//
    //-----Creating Dynamic Response Time TextFields-----//
                   usrRespTam = new JTextField[processes];          /* Makes an array */
                   yXis = 125;          //Variable for Y-axix of JTextField.
                   for(int i=0; i<processes; i++)      /* i takes each value from 0 to processes-1 */
    usrRespTam[i] = new JTextField();     /* Makes a JTextField at an array place */
    usrRespTam[i].setEditable(false);
    pane.add(usrRespTam[i]);      /* Adds a JTestField (rather than an array) */
    usrRespTam[i].setBounds(340, yXis, 35, usrRespTam[i].getPreferredSize().height);
    yXis = yXis + 25;     /* Increses the Y-axis to show JTextFields. */
    }     //EndFor     
    //-----End Dynamic Response Time TextFields.-----//
    //-----Creating Dynamic Waiting Time TextFields-----//
                   usrWaitTam = new JTextField[processes];          /* Makes an array */
                   yXis = 125;          //Variable for Y-axix of JTextField.
                   for(int i=0; i<processes; i++)      /* i takes each value from 0 to processes-1 */
    usrWaitTam[i] = new JTextField();     /* Makes a JTextField at an array place */
    usrWaitTam[i].setEditable(false);
    pane.add(usrWaitTam[i]);      /* Adds a JTestField (rather than an array) */
    usrWaitTam[i].setBounds(430, yXis, 35, usrWaitTam[i].getPreferredSize().height);
    yXis = yXis + 25;     /* Increses the Y-axis to show JTextFields. */
    }     //EndFor     
    //-----End Dynamic Waiting Time TextFields.-----//
         }     //-----END of buttCreatActionPerformed(ActionEvent e)--------//
         private void buttResltActionPerformed(ActionEvent e)     //Action to Show results of scheduling.
              // TODO code here
    }     //------END of void buttResltActionPerformed(ActionEvent e)---------//
         private static void createAndShowGUI()
    //Make sure we have nice window decorations.
    JFrame.setDefaultLookAndFeelDecorated(true);
    //Create and set up the window.
    JFrame frame = new JFrame("Round Robin Scheduling.... (RR)");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Samulation2 application = new Samulation2();
    //Create and set up the content pane.
    JComponent components = application.createComponents ();
    components.setOpaque (true);
    int vertSB = ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;
              int horzSB = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS;
              JScrollPane scrollPane = new JScrollPane(components, vertSB, horzSB);
    scrollPane.setPreferredSize (new Dimension(555,455));
    frame.getContentPane ().add (scrollPane,null);
    //Display the window.
    frame.pack();
    frame.setVisible(true);
    }     //------END Of void createAndShowGUI()--------//
         public static void main(String[] args)
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
         }     //---------End of main()----------------//
    }     //--------END of class Samulation2----------//

    I have added a new line. If u are asking for this line.
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class Samulation2
         JPanel pane;
         JLabel label1;
         JTextField entProcesfld;
         JButton buttCreat;
         JLabel usrProcesID[];
         int processes;     
         Dimension area;
         public JComponent createComponents()
         pane = new JPanel();
         pane.setLayout (null);
         label1 = new JLabel();     //Label for to tell user to enter no of Processes.
         label1.setText("Enter the no. of Processes");
         pane.add(label1);
         label1.setBounds(20, 25, 150, label1.getPreferredSize().height);
         entProcesfld = new JTextField();     //TextField to enter no of processes.
         entProcesfld.setToolTipText("Enter the no of Processes.");
         pane.add(entProcesfld);
         entProcesfld.setBounds(180, 25, 100, entProcesfld.getPreferredSize().height);
         buttCreat = new JButton();          //Button to create the TextFields.
         buttCreat.setText("Create TextFields");
         pane.add(buttCreat);               //Adding cutton to Jpane.
         buttCreat.setBounds(new Rectangle(new Point(120, 60), buttCreat.getPreferredSize()));
         buttCreat.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        buttCreatActionPerformed(e);
                   } } );          //ActionListenr to Create the TextFields.
         //****************************NEW LINE************************\\
         pane.setPreferredSize(new Dimension(555, 455));
         return pane;
         }     //-------END of Component createComponents()--------//
         private void buttCreatActionPerformed(ActionEvent e)     //Action to Create the TextFields.
                   processes = Integer.parseInt (entProcesfld.getText ());
                   JLabel Labproces = new JLabel();     //Label of Processes.
                   Labproces.setText("Processes");
                   pane.add(Labproces);
                   Labproces.setBounds(new Rectangle(new Point(15, 105), Labproces.getPreferredSize()));
                   //----Creating Dynamic JLabels------//
                   usrProcesID  = new JLabel[processes];     /* Makes an array */
                   int yXis = 125;          //Variable for Y-axix of JLabel.
                   for(int i=0; i<processes; i++)      /* i takes each value from 0 to processes-1 */
                    usrProcesID[i] = new JLabel("P" + i);      /* Makes a JLabel at an array place */
                    pane.add(usrProcesID);      /* Adds a JLabel (rather than an array) */
    usrProcesID[i].setBounds(new Rectangle(new Point(28, yXis), usrProcesID[i].getPreferredSize()));
    yXis = yXis + 25;     /* Increses the Y-axis to show JLabels. */
    }     //EndFor     
    //-------End Dynamic JLabels---------//               
         }     //-----END of buttCreatActionPerformed(ActionEvent e)--------//
         private static void createAndShowGUI()
    //Make sure we have nice window decorations.
    JFrame.setDefaultLookAndFeelDecorated(true);
    //Create and set up the window.
    JFrame frame = new JFrame("Round Robin Scheduling.... (RR)");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Samulation2 application = new Samulation2();
    //Create and set up the content pane.
    JComponent components = application.createComponents ();
    components.setOpaque (true);
    int vertSB = ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;
              int horzSB = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS;
              JScrollPane scrollPane = new JScrollPane(components, vertSB, horzSB);
    scrollPane.setPreferredSize (new Dimension(555,455));
    frame.getContentPane ().add (scrollPane,null);
    //Display the window.
    frame.pack();
    frame.setVisible(true);
    }     //------END Of void createAndShowGUI()--------//
         public static void main(String[] args)
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
         }     //---------End of main()----------------//
    }     //--------END of class Samulation2----------//

  • JTable setViewportView problems

    Hey there.
    Just a small question. I've made an application. A part of it is a JScrollPanel with a JTable. I update the JTable with the method setViewportView everytime i need to.
    The problem is that i have a combobox in one of my coloumns. On my combo i have a popupmenulistener. In the method popupmenuwillbecomeinvisible i have implemented some code and also a call to the method setViewportView. Everytime i use this combo i get an exception. nullpointer exception in JComponent. It's only when i use the combo because i call the method setViewportView ellswhere....so any idea what could be my problem??
    Thanks!!
    :o) Ellyton

    hmmm, sometimes doing a redesign is painfull in the short term but invaluable in the mid/long term. it might allow you to change/extend your code (aside from debugging is much easier).
    in general when using Swing you should make a clear distinction between your data model (table model, tree model, list model etc) and your control (JTable, JTree, Jlist, etc). that way, changing your data, like in your case, becomes very easy, as well as accessing it in different ways.
    you say, you have to "update the entire table everytime...", what do you mean by this? the table data? if so, simply change the content of your array/vector in the table model and fire a tableDataChanged event. the JTable will redraw itself with the new/changed data.
    thomas

  • Layout problem - Huge headache

    Hi guys,
    So I'm having this problem with placed images/generated shapes shifting down the page when going from design mode to preview mode and it's giving me a huge headache.
    Here's how it looks in Design mode:
    Here's how it looks when I preview:
    Any help on this would be amazing as I cannot figure it out myself. I will say I do have a few embedded HTML's on the Master for Twitter, Facebook and a JotForm. Could these cause the issues as it seems to happen on every page not just one.

    Did you use JScrollPanel? If not, use it.

  • Problem while trying to control a JScrollpane

    Hi,
    I am working on a JTable inside a JScrollpanel... So there's a horizontal scrollbar at the bottom of the frame.
    My JTable displays a planning, and is loaded by database requests.
    My table is divided into "pages" which are a group of columns. When the JTable asks for a cell of a page (to display it), and that the page has not yet been loaded then, a request is automatically sent to the database.
    The correct behaviour should be :
    1. Add an empty page to the model and call tableChanged() to notify the JTable
    2. The JTable asks for a cell
    3. Send a request to the data base
    4. Fill in the page with the response
    5. Since that page is located on the left hand side, another empty page should also be added on the left (but should not be visible). Call tableChanged() to notify the JTable
    6. But since that page is also located on the right hand side, another empty page should also be added on the right (but should not be visible). Call tableChanged() to notify the JTable
    7. Then for example if the user goes to the left (with the scrollbar or with the keyboard arrows), it will make the left empty page visible. So a request is launched, response managed, and an empty page added to the left...and so on...
    My problem is that when I add a page to the left, the JScollbar position is automatically set (by Swing ?) to zero.
    So the left empty page becomes automatically visible, the request sent, and the new empty page added... scrollbar to zero automatically... and this goes on and on and there is no end!
    I haven't got the code (I'm not at my office)... but I've tried everything to block the JScrollbar....
    Can I add columns to my model (and to the JTable) without the automatic reset of the JScrollbar ???
    I would like the scrollbar to be resized systematically to reflect the new size of the table while the visible columns remain the same and at the same place on the screen.
    Thanks
    Arnaud

    Ok.... didn't work :-(
    One of the main problem is that the addColumn() methods only append a column to the end (the right) of the table... so they are half-useless (half because sometimes the user wants to go right)
    I didn't try anything with scrollRectToVisible(), because I don't want to search for the right rectangle to display...
    I really think that the whole conception of the table in Java is done for easily managing rows... but not columns... There are no methods to manage columns... and in the Javadoc, I see that the only methods wich manage columns always call tableChanged()
    But there's something interesting : the user of my planning can change the cell layout by changing what is displayed, and the number of information displayed. This automatically change the cells' sizes... The way I ask the JTable to repaint is a tableChaned() call (repaint() only repaints the cell without updating the size). And when I call tableChanged() in this situation, the JScrollBar is not affected !
    So I think the scrollbar is reset to 0 only when the number of columns is changed. I changed my code to artificially change the number of columns of the TableModel before calling the tableChaned().... didn't work :-(
    My code force the correct position of the scrollbar by calling setValues(), or setValue() and setMaximum(), everytime I need... The position should be correct !
    I think Swing uses a Thread to do paintings, and size computation.... and it's surely my problem : at the end of the fireTableChanged() the Table isn't in its final state.... so setting the scrollbar position at this point is useless...
    What do you think ?

  • Jtable Horizontal ScrollBar problem

    Hi,
    I am having a Jtabel inside a JscrollPanel with horizontal and vertical scrollpane.
    My table model contains say 20 columns.But i am showing only 10 columns hiding the other 10.when i click on the table header i will show the rest of 10.so now the total columns are 20.but when i scroll thehorizantal bar to the see the other 10 coulmns the header for the latest 10 coulmns is not showing properly.
    Is there anybody to help me to sort out this problem.
    Thanks in advance.
    sree

    Hi,
    how ican saw Scrollbar with out Jtable.AUTO_RESIZR_OFF.That i already did.That not the actual problem.any how i solved this problem finally.It is something with TableHeaderRenderer..Any how thanks for ur help.
    sree

  • Problem using JSrollPane

    Hi everyone I have a quick question:
    I have a JTabbedPane object which contains two tabs. Each tab has a JPanel object and each JPanel object has a JScrollPane with JTextArea object. When I update the data in the JTextArea the first time I get the scroll bars but if I change tabs and then go back to the tab with the updated data the scroll bars disappear.
    I thought it was the problem with revalidating so I then added a revalidate statement for the scrollPane everytime I update the data in the JTextField. That didn't make any difference. Then I added a revalidate statement for the scrollPane in a listener method which gets called when tabs change so when you get back to the tab with the data, the scrollpane would revalidate but that still doesn't work.
    What am I doing wrong?

    I can't really write a small example because I have a pretty complicated structure in my application.
    I mean when I write small examples they work perfectly fine. I guess what I'm looking for is just ideas of what you think might cause such a problem.
    The structure of my program is something like this:
    I have a a class Receive, which is a base class
    Then I have 10 other classes which derive from Receive.
    Receive has all the GUI components which have protected access so the derrived classes can access them.
    The derrived classes then have a method which through Data Distribution Services protocols get messages.
    Then a JTextArea object in the base class gets updated by
    textArea.setText(messageString);So then the message appear in the GUI, but when you change tabs and then go back to the previous tab the scrolls are all messed up.
    I set my objects like this
    frame=new JFrame();
    dataPane=new JPanel();
    textArea=new JTextArea();
    scrollPanel=new JScrollPanel(textArea);
    scrollPanel.setPreferedSize(new Dimension(400,300));
    tabPane.addTab("Tab", scrollPanel);
    dataPane.add(tabPane);
    frame.add(dataPane, BorderLayout.CENTER);

  • The gridBagLayout and the JscrollPanel

    Hi:
    1)GridBagLayout
    When I tried to use the GridBagLayout, I found that I can not change the weight of each component added in the container.
    For example,In the contentPanel of the JDialog, I added two sub panels:leftPanel and rightPanel.However the leftPanel and the rightPanel take the same width of the main dialog,I just want the leftPanel take 60% of the width of the JDialog. I have tried to definte the weightx parameter of leftPanel's GridBagContrains,but it seems not work.
    Also I found that if I add a empty Jpanel in a GridBagLayout managed JFrame,it take a small space ,after I add some compontens in the Jpanel, it is resized,
    In fact I want to control the compontent just as the size I wanted using the releative position.That's to say, even the Jpanel is empty,it should take up its own size I setted.
    So is there any ideas?
    2)The JScrollPanel.
    The leftPanel mentioned above is a JScrollPanel,and I want to show some little vector symbols in this panel,the symbols should changed when a JCombox( has been added to the main frame) changed.
    So I set the view port of the JScrollPanel to a new Jpanel(symbolListPanel:used to display the symbols, and each symbol will be draw in a SymbolPanel which extends the Jpanel and override the paint() method). I set this symbolListPanel use the GridBagLayout. I want there are three symbols displayed in each row, so I use the following codes:
    GridBagConstraints c=new GridBagConstraints();
    c.fill=both;c.weightx=c.weighty=1;
    Symbols[] s=getVectorSymbols();
    for(int i=0;i<s.length();i++) {
      c.gridx=i%3;
      c.gridy=i/3;
      symbolListPanel.add(new SymbolPanel(s),c); //
    symbolListPanel.repaint();-----------------------
    Well, when I run the application, the symbols are displayed,when I add 6 symbols, the symbolListPanel is divided to a 2(rows)x3(columns) grid,it looks well,however when I add 9 symbols, the symbolListPanel is divided to a 3(rows)x3(columns) grid,this is no problem,but the ScrollBar is never displayed,also each SymbolPanel is resized smaller to fit the size of the visible space of the leftPanel(JScrollPanel). In fact what I really need is the size SymbolPanel is never changed, when the visible  of the leftPanel is not large enough to show all the symbols, the scrollBar should display.
    BTW, in the SymbolPanel I have used the following method tried to controll the size :setPreferredSize(////);
    setMaximumSize(getPreferredSize);
    setMinimumSize(getPreferredSize) ;I think use the above three method can absolutely control the size of the Symbolpanel (then it can not be resized).
    But it seems not. why?
    3) When I change the combox, the symbols should chang. however the changed symbols can never be  visible  unless I resize the dialog.
    I thought if it is the repaint problem of the dialog. But I have call the  symbolListPanel.repaint() method,it seems that the repaint method of the sub compontent of the symbolListpanel is not called. At last I have to use the following method to make the changed symbols visible:dialog.setVisible(false);
    dialog.setVisible(true); // Set the main dialog unvisible,then set it visible, so all the compontents will be repainted,and it works.
    // However I know this is a stupid method, is there any normal ways ?
    Edited by: apachemaven on 2010-7-25 ??2:08                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    Thanks, I apology for my unpolite.
    The problem is encountered in company, and our working computer is not allowed to communicate with extra hardware such as the portable hardisk.
    So it is not easy to make a simple example... It realated too many other objects which I can not simulate.
    In fact I use the Absolute Positioning to solve the problem(Though it is not a good idea).
    In this form I found another discussion about the GirdBagLayout at [thread.jspa?threadID=5446065&tstart=0|http://forums.sun.com/thread.jspa?threadID=5446065&tstart=0] ,and Sarcommand said:
    A GridBagLayout will try to give every component space according to its preferred size.If so, does it mean I should set the prefered size of each component?
    Here I write a simple test:
    import javax.swing.BorderFactory;
    import javax.swing.JPanel;
    import java.awt.Frame;
    import java.awt.BorderLayout;
    import javax.swing.JDialog;
    import java.awt.GridBagLayout;
    import java.awt.GridBagConstraints;
    import javax.swing.JButton;
    import java.awt.Insets;
    public class GridTest extends JDialog {
         private static final long serialVersionUID = 1L;
         private JPanel jContentPane = null;
         private JPanel leftPanel = null;
         private JPanel rightPanel = null;
         private JButton okButton = null;
         private JButton cancelButton = null;
         public GridTest(Frame owner) {
              super(owner);
              initialize();
         private void initialize() {
              this.setSize(495, 515);
              this.setContentPane(getJContentPane());
              this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
         private JPanel getJContentPane() {
              if (jContentPane == null) {
                   GridBagConstraints gridBagConstraints1 = new GridBagConstraints();
                   gridBagConstraints1.gridx = 1;
                   gridBagConstraints1.weightx = 0.3;
                   gridBagConstraints1.weighty = 1.0;
                   gridBagConstraints1.gridy = 0;
                   GridBagConstraints gridBagConstraints = new GridBagConstraints();
                   gridBagConstraints.gridx = 0;
                   gridBagConstraints.fill = GridBagConstraints.BOTH;
                   gridBagConstraints.weightx = 0.7;
                   gridBagConstraints.weighty = 1.0;
                   gridBagConstraints.gridy = 0;
                   jContentPane = new JPanel();
                   jContentPane.setLayout(new GridBagLayout());
                   jContentPane.add(getLeftPanel(), gridBagConstraints);
                   jContentPane.add(getRightPanel(), gridBagConstraints1);
              return jContentPane;
         private JPanel getLeftPanel() {
              if (leftPanel == null) {
                   leftPanel = new JPanel();
                   leftPanel.setLayout(new GridBagLayout());
                   leftPanel.setBorder(BorderFactory.createTitledBorder("Left"));
              return leftPanel;
         private JPanel getRightPanel() {
              if (rightPanel == null) {
                   GridBagConstraints gridBagConstraints2 = new GridBagConstraints();
                   gridBagConstraints2.gridx = 1;
                   gridBagConstraints2.fill = GridBagConstraints.BOTH;
                   gridBagConstraints2.insets = new Insets(0, 10, 0, 0);
                   gridBagConstraints2.gridy = 0;
                   rightPanel = new JPanel();
                   rightPanel.setLayout(new GridBagLayout());
                   rightPanel.add(getOkButton(), new GridBagConstraints());
                   rightPanel.add(getCancelButton(), gridBagConstraints2);
              return rightPanel;
         private JButton getOkButton() {
              if (okButton == null) {
                   okButton = new JButton();
                   okButton.setText("OK");
              return okButton;
         private JButton getCancelButton() {
              if (cancelButton == null) {
                   cancelButton = new JButton();
                   cancelButton.setText("Cancel");
              return cancelButton;
         public static void main(String[] args) {
              new GridTest(null).setVisible(true);
    }In this test, I want the left panel take the 70% of the widht of the whole dialog,when the dialog first set up, I found the leftpanel take only about 50%, when I resize(increase) the dialog, it seems that the leftpanel's percentge increase.
    However this is not what I want, I set the size of the whole dialog to (495,515),and I want the left take about 70%X495 always.
    So, is there any way using the GridbagLayout?

  • A problem with threads

    I am trying to implement some kind of a server listening for requests. The listener part of the app, is a daemon thread that listens for connections and instantiates a handling daemon thread once it gets some. However, my problem is that i must be able to kill the listening thread at the user's will (say via a sto button). I have done this via the Sun's proposed way, by testing a boolean flag in the loop, which is set to false when i wish to kill the thread. The problem with this thing is the following...
    Once the thread starts excecuting, it will test the flag, find it true and enter the loop. At some point it will LOCK on the server socket waiting for connection. Unless some client actually connects, it will keep on listening indefinatelly whithought ever bothering to check for the flag again (no matter how many times you set the damn thing to false).
    My question is this: Is there any real, non-theoretical, applied way to stop thread in java safely?
    Thank you in advance,
    Lefty

    This was one solution from the socket programming forum, have you tried this??
    public Thread MyThread extends Thread{
         boolean active = true;          
         public void run(){
              ss.setSoTimeout(90);               
              while (active){                   
                   try{                       
                        serverSocket = ss.accept();
                   catch (SocketTimeoutException ste){
                   // do nothing                   
         // interrupt thread           
         public void deactivate(){               
              active = false;
              // you gotta sleep for a time longer than the               
              // accept() timeout to make sure that timeout is finished.               
              try{
                   sleep(91);               
              }catch (InterruptedException ie){            
              interrupt();
    }

  • A problem with Threads and MMapi

    I am tring to execute a class based on Game canvas.
    The problem begin when I try to Play both a MIDI tone and to run an infinit Thread loop.
    The MIDI tone "Stammers".
    How to over come the problem?
    Thanks in advance
    Kobi
    See Code example below:
    import java.io.IOException;
    import java.io.InputStream;
    import javax.microedition.lcdui.Graphics;
    import javax.microedition.lcdui.Image;
    import javax.microedition.lcdui.game.GameCanvas;
    import javax.microedition.media.Manager;
    import javax.microedition.media.MediaException;
    import javax.microedition.media.Player;
    public class MainScreenCanvas extends GameCanvas implements Runnable {
         private MainMIDlet parent;
         private boolean mTrucking = false;
         Image imgBackgound = null;
         int imgBackgoundX = 0, imgBackgoundY = 0;
         Player player;
         public MainScreenCanvas(MainMIDlet parent)
              super(true);
              this.parent = parent;
              try
                   imgBackgound = Image.createImage("/images/area03_bkg0.png");
                   imgBackgoundX = this.getWidth() - imgBackgound.getWidth();
                   imgBackgoundY = this.getHeight() - imgBackgound.getHeight();
              catch(Exception e)
                   System.out.println(e.getMessage());
          * starts thread
         public void start()
              mTrucking = true;
              Thread t = new Thread(this);
              t.start();
          * stops thread
         public void stop()
              mTrucking = false;
         public void play()
              try
                   InputStream is = getClass().getResourceAsStream("/sounds/scale.mid");
                   player = Manager.createPlayer(is, "audio/midi");
                   player.setLoopCount(-1);
                   player.prefetch();
                   player.start();
              catch(Exception e)
                   System.out.println(e.getMessage());
         public void run()
              Graphics g = getGraphics();
              play();
              while (true)
                   tick();
                   input();
                   render(g);
          * responsible for object movements
         private void tick()
          * response to key input
         private void input()
              int keyStates = getKeyStates();
              if ((keyStates & LEFT_PRESSED) != 0)
                   imgBackgoundX++;
                   if (imgBackgoundX > 0)
                        imgBackgoundX = 0;
              if ((keyStates & RIGHT_PRESSED) != 0)
                   imgBackgoundX--;
                   if (imgBackgoundX < this.getWidth() - imgBackgound.getWidth())
                        imgBackgoundX = this.getWidth() - imgBackgound.getWidth();
          * Responsible for the drawing
          * @param g
         private void render(Graphics g)
              g.drawImage(imgBackgound, imgBackgoundX, imgBackgoundY, Graphics.TOP | Graphics.LEFT);
              this.flushGraphics();
    }

    You can also try to provide a greater Priority to your player thread so that it gains the CPU time when ever it needs it and don't harm the playback.
    However a loop in a Thread and that to an infinite loop is one kind of very bad programming, 'cuz the loop eats up most of your CPU time which in turn adds up more delays of the execution of other tasks (just as in your case it is the playback). By witting codes bit efficiently and planning out the architectural execution flow of the app before start writing the code helps solve these kind of issues.
    You can go through [this simple tutorial|http://oreilly.com/catalog/expjava/excerpt/index.html] about Basics of Java and Threads to know more about threads.
    Regds,
    SD
    N.B. And yes there are more articles and tutorials available but much of them targets the Java SE / EE, but if you want to read them here is [another great one straight from SUN|http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html] .
    Edited by: find_suvro@SDN on 7 Nov, 2008 12:00 PM

  • J2ME problem with threads

    Hi all,
    I would like to ask you for a help. I need to write a small program at my university. I started to write a midlet which function would be to countdown time for sports activities. I woul like to start a new thread - the one that counts down - and at the same time make the main thread sleep. After the "countdown" thread finishes, the main thread wakes up and waits for user input. The problem is that when the "countdown" thread finishes his work, I've got Uncaught exception java/lang/NullPointerException. error and the midlet halts.
    Below you can find the code
    import java.lang.*;
    import java.util.*;
    import javax.microedition.lcdui.*;
    import javax.microedition.midlet.*;
    public class intervals extends MIDlet implements CommandListener
    public Display ekran;
    private SweepCanvas sweeper;
    private Form rundy;
    private TextField round0, round1, round2, round3, round4, round5, round6, round7, round8;
    private long czas,x;
    private Command exitCommand;
    private Command addRound;
    private Command delRound;
    private Command start;
    private TextField repeat;
    private Form odliczanie;
    private Alert ostrz;
    Licznik thread;
    String test;
    StringItem test1;
    int parz,i,j,k;
    static int l;
    int ilrund;
    int ilpowt;
    Item sec;
    long sec1;
    public intervals()
        rundy = new Form("Interwa&#322;y sportowe");
        exitCommand = new Command("Wyj&#347;cie", Command.EXIT, 2);
        addRound = new Command("Dodaj","Dodaj rund&#281;", Command.ITEM,1);
        delRound = new Command("Usu&#324;","Usu&#324; ostatni&#261; rund&#281;", Command.ITEM,1);
        start = new Command("Start", Command.ITEM,1);
        odliczanie = new Form("Odliczanie");
        TextField dodaj(TextField kolej)
            kolej=new TextField("Podaj czas (s) rundy "+parz,null, 4, TextField.NUMERIC);//stworzenie nowej instancji do wybierania czasu trwania rundy
            if(rundy.size()==0)
                rundy.insert(rundy.size(),kolej);
                else
                    rundy.insert(rundy.size()-1, kolej);
            return kolej;
        void odliczanie(TextField round)
            monitor m=new monitor();
            k=Integer.parseInt(round.getString());
            ekran.setCurrent(odliczanie);
            thread=new Licznik(k,odliczanie);
            thread.start();
            ekran.setCurrent(rundy);
    public void startApp()// throws MIDletStateChangeException
        rundy.deleteAll();
        repeat = new TextField("Podaj ilo&#347;&#263; powtórze&#324;",null,1,TextField.NUMERIC);
        rundy.addCommand(addRound);
        rundy.addCommand(exitCommand);
        rundy.setCommandListener(this);
        Canvas obrazek = new MyCanvas();
        ekran = Display.getDisplay(this);
        ekran.setCurrent(obrazek);
        czas=System.currentTimeMillis();
        while (System.currentTimeMillis()<czas+1000)
            continue;
        ekran.setCurrent(rundy);
    public void pauseApp()
    public void destroyApp(boolean unconditional)
        notifyDestroyed();
    public void commandAction(Command c, Displayable s)
        if (c == exitCommand)
            destroyApp(false);
            notifyDestroyed();
        else if(c==addRound)
            if(rundy.size()==0)//Sprawdzenie ilo&#347;ci elementów w celu poprawnego wy&#347;wietlania liczby rund w formie
                parz=1;
                else
                parz=rundy.size();
            switch(parz)
                case 1:
                    round0=dodaj(round0);break;
                case 2:
                    round1=dodaj(round1);break;
                case 3:
                   round2= dodaj(round2);break;
                case 4:
                    round3=dodaj(round3);break;
                case 5:
                    round4=dodaj(round4);break;
                default:
                    ostrz=new Alert("Uwaga","Maksymalna liczba rund wynosi 9", null, AlertType.INFO);
                    ostrz.setTimeout(3000);
                    ekran.setCurrent(ostrz);
            if(rundy.size()==1)
                rundy.append(repeat);
                rundy.addCommand(start);
            rundy.addCommand(delRound);
        else if(c==delRound)
            if(rundy.size()!=0)
                rundy.delete(rundy.size()-2);
                if (rundy.size()==1)
                    rundy.deleteAll();
                if(rundy.size()==0)
                    rundy.removeCommand(delRound);
                    rundy.removeCommand(start);
        else if(c==start)
            ilrund=rundy.size()-1;
            if(this.repeat.size()>0)
                ilpowt=Integer.parseInt(this.repeat.getString());
            ekran = Display.getDisplay(this);
            for (i=1; i<=ilpowt;i++)
                odliczanie= new Form("Odliczanie");
                 for (j=0;j<ilrund;j++)
                    switch(j)
                         case 0:
                             odliczanie(round0);
                             break;
                         case 1:
                             odliczanie(round1);
                             break;
                         case 2:
                             odliczanie(round2);
                             break;
                         case 3:
                             odliczanie(round3);
                             break;
                         case 4:
                             odliczanie(round4);
                             break;
                         case 5:
                             odliczanie(round5);
                             break;
                         case 6:
                             odliczanie(round6);
                             break;
                         case 7:
                             odliczanie(round7);
                             break;
                         case 8:
                             odliczanie(round8);
                             break;
    class Licznik extends Thread
        int czas1,k;
        Form forma;
        monitor m;
        public Licznik(int k,Form formap)
            czas1=k;
            forma=formap;
        public synchronized void run()
            while(czas1>0)
                forma.deleteAll();
                forma.append("Czas pozosta&#322;y (s): "+czas1);
                try{Thread.sleep(1000);} catch(InterruptedException e){e.printStackTrace();}
                czas1--;
            if(czas1<=0)
                m.put();
        }and monitor class
    public class monitor
    boolean busy=false;
    synchronized void get()
        if(!busy)
            try
                wait();
            }catch(InterruptedException e){e.printStackTrace();}
        notify();
    synchronized void put()
        if(busy)
            try
            wait();
            }catch(InterruptedException e){e.printStackTrace();}
        busy=true;
        notify();
    }Can anybody help me with this?

    Groovemaker,
    Your Licznik class has a member m of type monitor, which has not been instantiated (in other words is null) hence, when calling m.put() you get NullPointerException. Please also mind, that using Thread.sleep(1000) is not an accurate way of measuring time.
    If I may, please use recommended for Java class naming conventions - some of your names use lower case, while other don't which is confusing to the reader.
    Daniel

Maybe you are looking for