Scrollbars In JTextArea

Please see the link below for visual guide.
http://pollscanada.com/screenshot.html
I have my TextArea in the middle of the application which displays film titles when the user clicks on a category in the JComboBox further down on the left where it has the entry Science Fiction.
When the user clicks on another category, the scrollbars stay at the same level, so the the user does not see the top of the next chosen category list.
Is there a way to make the srollbars go back to the top after clicking on another entry in the JComboBox?

Thank you for your response. It works.
   public void setTitleList(String file_name) {
     try {
       FileReader fileReader = new FileReader(file_name);
            list.read(fileReader, file_name);
           scroller.getVerticalScrollBar().setValue(0);
           } catch(FileNotFoundException fex) {}
                catch(IOException ioex ) {}
  }

Similar Messages

  • Adding scrollbars in jtextarea

    can any one tell me the method of adding scrollbars in jtextarea such that they are enabled when required means initially disabled but when the text goes long they are enabled.
    farhan

    Add ur JTextArea in a JScrollPane by doing this :
    JScrollPane jsp = new JScrollPane(JScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    //then add ur Jtext hereMaz -

  • How to move the scrollBar to JTextArea's top?

    I defined a JTextArea inside a JScrollPane, then I read a .txt file through a Reader into that JTextArea (by setText(...)). Now the scroll bar at bottom. I need move the vertical scrollBar to the top.
    Please help me to do this.
    Thanks

    you can use the method setCaretPosition in JTextArea
    and pass the posotion in the text to place the Caret

  • Setting scrollbar in jtextarea

    hi
    Consider a JSplitPanel. in that split panel i have added jtree as the left component, and jScrollpane as the right component. if the user click a node in the jtree, i use the setDividerLocation method to divide the splite pand and add a jscrollpane at right side. in that jscrollpane i added a jtext area with the horizontal scrollbar option which will show always. thing is working well. scrollbar showing when the jscrollpane get visible. the problem is if the text of the text area is go beyond than the jtextarea viewport there is no change in scrollbar. it is showing lik dummy scrollbar without any changes.
    What i have to do to activate the scrollbar if the text in the jtextarea execde it view area?

    I devided JScrollPane Vertically. i added a jtree as left side component of JScrollPane. i did't add anythin in the right side. <br>
    if the user click a node in the JTree which is added in the left side of the jScrollpane, then i add a new jscrollpane as the right side component.<br>
    In that jscrollpane i added a JText area.<br>
    The JTextArea which i created earlier set the vertical scroll bar policy as always. so the vertical scrollbar will be shown always. <br>
    The above things working correctly.<br>
    What is wrong is,<br>
    if the user type any text more than text area, the scrollbar should be activated lik in our forums(text area). But it dos't happen to me. the empty jscrollbar is displayed eventhough the user enter more data that can't be displayed in the jtext area.<br>
    MyAction is,<br>
    if the user click the jtree, i call the setDivider location to devide the JSplitpane. so the left side componet(JTree) uses 200 as width all other width in the screen will be allocated to the JSplitPane(contains the JTextarea).<br>
    My question is,<br>
    why the JScrollbar is not activated are perform correctly eventhough the data which is entered in the JTextArea execedes the row(example 40) which i specified in the constructer when i create the jTextArea?

  • Add scrollbar to JTextArea

    Hello!
    I dont understand why this is not working:
    When I have added the scrollbar I can not print out anything on the JTextArea, if I just add the JTextArea I can print out to it.
    part of my view
              //Display (Do not forget to make the scrollbar after logic is implemented)
              JScrollPane scroll = new JScrollPane(display, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
              JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
              scroll.setLayout(null);
              scroll.setLocation(10, 10);
              scroll.setSize(320, 270);
              //display.setLocation(10, 10);
              //display.setSize(320, 270);
              display.setEditable(false);
              display.setLineWrap(true); //Start a new line instead of making display area bigger
              display.setWrapStyleWord(true); //Words will not split in the middle, the full word will instead show on the next line
              middle_left.add(scroll); //Add to holderThis is how I take inputs that will go into the JTextArea
         // Sets the text displayed on the display area
         public void setDisplayArea(String message){
              display.setText(""+message);
         I must defently be missing something, can you please help me figure out what it is.
    This is part of an assignment, please do not spoonfeed me with code.
    Regards
    Martin

    onslow77 wrote:
    Yes the problem went away when I comment out this line //scroll.setLayout(null);
    Why is it so?
    Can you please explain or guide me to a webpage with an explonation if it is alot to explain.Like abillconsl said, a JScrollPane already has a perfectly good layout manager. So instead it's up to you to explain why you decided to make it have a null layout manager instead.
    If the explanation is "I don't know anything about layout managers so I can't explain that, it just seemed like a good idea at the time" then you should read the [Layout Managers tutorial|http://java.sun.com/docs/books/tutorial/uiswing/layout/using.html].

  • Multiline list again

    So, I have a problem. I was thinking a lot and I've found a solution.
    The problem is: I want to make something like a message history, providing multiline list of message texts. At first I tried to make it via JList with JTextArea-based CellRenderer. Yes, I know not, it's a bad idea. Because JTextArea didn't wrap text in this case. Finaly I tried to simulate JList behavoir by using JPanel with vertical BoxLayout as I've read on one Forum. Ok, It works. But the main problem is: When you're using BoxLayout each JTextArea component that I place on JPanel tries to grab all unused space in my list. For example, at first I have the only JTextArea. It holds all JPanel. After I add another one, I have two JTextAreas but every JTextArea holds half of my JPanel. It looks not very beautiful. Can anyone suggest me, what I'm to do?

    Yes, you're right. This is a code.
    import javax.swing.*;
    import java.util.List;
    import java.util.ArrayList;
    import java.awt.*;
    public class JFullTextList extends JScrollPane
    //  private List areas = new ArrayList();
        private JPanel p = new JPanel();
        public JFullTextList()
            p.setLayout(new BoxLayout(p,BoxLayout.Y_AXIS));
            p.setBackground(Color.WHITE);
            this.getViewport().add(p);
        public void addText(String text)
            JTextArea jta = new JTextArea();
            jta.setLineWrap(true);
            jta.setWrapStyleWord(true);
            jta.setBorder(BorderFactory.createEtchedBorder());
            p.add(jta);
            jta.setText(text);
            //this.add(stub);
    }As you can see there I'm trying to make my SWING component. Just place it somewhere (on JFrame). Interesting result will appear when you're invoking addText() method. First JTextArea grabs all place on my JPanel. Second JTextArea takes one half of the place and now there 2 JTextAreas that still hold all place on my JPanel. The only I want - JTextArea takes not all place but only place needed for text rendering. This is a first issue. The second one is described in my post "Custom scrolling". If you enlarge JFrame width (JFrame still contains my component) All is ok. JTextAreas render text again. But if you'll make width small again, JTextAreas don't render text again. That's why horizontal scrollbar appears (JTextArea still large). I don't want horizontal scroll bar, I want JTextAreas to change their size.

  • Dividing the applet in 2 sections

    Hello
    I have a really simple game in applet. Game runs fine, at the bottom i want to add a scrollbar which will have a textArea in it. So basically i want to divide the applet in 2 parts...top part the game and bottom part the scrollbar. Any tips on how to do this?
    I want the game to run in size (450,500) and then extend the applet's y cordinate by 200 more and in that extra area add the scrollbar. My game is using the init method. When game is over and player double clicks the applet to start the game over....the init method is called again. So i dont think i can add the scrollbar in the init method. Maybe i have to make 2 differnt classes? one for the game and one for the scrollbar? but out of those which will run the final applet?
    As u can tell...kind of confused here. Any help would be appreciated

    the init() method would not be called. The init() method of the applet is
    called automatically when the Applet is loaded.
    you can simply ruse the scrollbar...when the new game start..just set the visibility of the scrollbar to false (so to hide the scrollbar)
    when you need the scrollbar..just set its visibility to true
    for example
    public class Game extends JApplet{
        private JScrollBar scrollbar;
        private JTextArea txtArea;
        private Box mainPanel;
        public void init(){
            // create the component once
            scrollbar = new JScrollBar(); ...
            txtArea = new JTextArea();
            mainPanel = Box.createVerticalBox();
            mainPanel.add(txtArea);
            mainPanel.add(scrollbar);       
            initComponent();
        public void initComponent(){
            showScrollbar();     // hide the scrollbar
            txtArea.setText("");  // clear the text area..so a new game will have a blank textarea
        public void showScrollBar(){ scrollbar.setVisible(true);  }
        public void hidesScrollBar(){ scrollBar.setVisible(false; }
    }

  • How do you add a Vertical scrollbar to a JTextArea?

    How do you add a Vertical scrollbar to a JTextArea? This is what I've tried so far but it hasn't worked. I got that off of someone asking a similiar question here.
    aTextArea = new JTextArea(10, 40);
             JScrollPane scrollPane = new JScrollPane(aTextArea);
             aTextArea.setText( " " );

    JScrollPane(component)
    this constructor will only show the scrollbar (vertical and/or horizontal) as needed..so, if the scrollpane viewport is larger than the component, then it will not show the scrollbar.
    you can force the scrollbar to alway show
    setHorizontalScrollBarPolicy(int policy)
    setVerticalScrollBarPolicy(int policy)

  • Need to make JTextArea scrollbar at top

    I've created a JFrameForm using GUI netbeans 5.0
    When i created a JTextArea.. then i just put a lot of words inside it, then it'll automatically created a scrollbar there.
    The problem i face is when i try to execute it, the scrollbar is at the bottom. How do i make it to start at the top?
    Please help.
    i've asked at the specific forum, jguru.com , but no one is replying. So i hope any of you can help me about it. Its not that i purposely violate the rule of this forum. I apologize firstly.

    Hi try like this,
    jTextArea1.setText("sdfasdf\nasdfasdf\nasdf\nasdf\nasdf\nasdf\nasdf\nasdf\nasdf\nasdf\nasdf");
    jScrollPane1.setViewportView(jTextArea1);
    getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
    getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 140, 100, 90));
    pack();
    jTextArea1.setCaretPosition(0);
    regards
    Dhinakar

  • JTextArea  -- text growing problem, need scrollbar

    thanks again to DrClap's help!! thank you for your hard work of looking up the API document to get the right parameter for me!! thanks.
    i got one more problem... :(
    it is about the appearance of the output text in the JTextArea.
    with my following code, i could not see the scroll bar of the JTextArea and thus some output text can not be seen:
    class aFrame extends JFrame{
    public aFrame(){
    super(s); setSize(400, 300);
    Container c = getContentPane();
    JTextArea ta = new JTextArea();
    ta.setFont(new Font("Monospaced",Font.PLAIN,12));
    c.add(ta);
    for(int i=0; i<1000; i++) ta.append(i+" ");// some output
    // from this for loop can't be seen in the text area of
    // the frame
    // if i declare "ta" as TextArea ta, then scroll bar is
    // automatically set and thus all the output can be
    // seen. but it is not faithful to JFrame if i do so.
    // how to adjust the code in order to show the full
    // set of output?
    // thanks a lot!!!

    You can also download the Java Swing tutorial free. It should be mandatory reading before posting a question on this form.
    http://java.sun.com/docs/books/tutorial/

  • How to ouput into JTextArea

    Hi, I'm creating a Boggle game in Java and I'm in need of help importing what outputs on the 'status' into the JTextArea called 'textL' which is the left text area of the program. If you run the program, it should show a main panel with two text area on each side. I just need words to be sent to the left text area when the 'Submit' or 'Reset' button is clicked. I'm just trying to test out the JText to make sure it works. I've tried coding it myself in the AcitionPerform method, but had no luck. What I have tested was calling my 'text'(JText variable) and having it setText("asdf") when 'button' is clicked, there's not output into the text area.
    All help is greatly appreciated.
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.BorderFactory;
    import javax.swing.Box;
    import javax.swing.BoxLayout;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    // Your Class
    public class Boggle extends JPanel implements ActionListener {
         public final static int NUM_ROWS_COLUMNS = 5;
         private JButton reset;
         private JButton submit;//submit
         //     private JButton clrwrd;
         private JButton arrayofButtons[][] = new JButton[NUM_ROWS_COLUMNS][NUM_ROWS_COLUMNS];
         private JLabel status;
         private JLabel messStatus;
         private JTextArea textL;
         private JTextArea textR;
         private JButton prevButton;
         private int prevRow, prevCol;
         private Lexicon lex = new Lexicon("ENABL.txt");
         // Your Constructor
         public Boggle() {
              BoxLayout ourLayout = new BoxLayout(this, BoxLayout.X_AXIS);
              setLayout(ourLayout);
              JScrollPane scrollLeft = new JScrollPane(buildTextAreaLeft());          
              scrollLeft.setVerticalScrollBar(scrollLeft.createVerticalScrollBar());
              scrollLeft.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
              JPanel MainAreaPanel = new JPanel();
              MainAreaPanel.setLayout(new BoxLayout(MainAreaPanel, BoxLayout.Y_AXIS));
              //                    MainAreaPanel.setPreferredSize(new Dimension(1000, 1000));
              add(scrollLeft);
              add(MainAreaPanel);
              JScrollPane scrollRight = new JScrollPane(buildTextAreaRight());
              scrollRight.setVerticalScrollBar(scrollRight.createVerticalScrollBar());
              scrollRight.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);          
              add(scrollRight);          
              MainAreaPanel.add(buildMainPanel());
              MainAreaPanel.add(buildControlPanel());
              MainAreaPanel.add(buildMessagePanel());
         //Right JTextArea
         private JTextArea buildTextAreaRight(){     
              JTextArea textR = new JTextArea();
              textR = new JTextArea();
              textR.setPreferredSize(new Dimension(300,200));
              textR.setBorder(BorderFactory.createLineBorder(Color.black));
              textR.setLineWrap(true);
              textR.setEditable(true);
              return textR;
         //Left JTextArea
         private JTextArea buildTextAreaLeft(){     
              JTextArea textL = new JTextArea();
              textL= new JTextArea();
              textL.setPreferredSize(new Dimension(300,200));
              textL.setBorder(BorderFactory.createLineBorder(Color.black));
              textL.setLineWrap(true);
              textL.setEditable(true);
              return textL;
         // Your MainPanel
         private JPanel buildMainPanel() {
              JPanel panel = new JPanel();
              GridLayout gridLayout = new GridLayout(0, NUM_ROWS_COLUMNS);
              panel.setLayout(gridLayout);
              for (int row = 0; row < arrayofButtons.length; ++row)
                   for (int column = 0; column < arrayofButtons[0].length; ++column) {
                        char letters = (char)(Math.random()*26+65);
                        //                    System.out.println(letters + 0);
                        arrayofButtons[row][column] = new JButton();
                        arrayofButtons[row][column].setBackground(Color.white);
                        arrayofButtons[row][column].setText(letters+"");// Set your letters
                        // in boxes.
                        arrayofButtons[row][column].setPreferredSize(new Dimension(100, 100));
                        arrayofButtons[row][column].addActionListener(this);
                        // Use actionCommand to store x,y location of button
                        arrayofButtons[row][column].setActionCommand(Integer.toString(row)+ " " + Integer.toString(column));
                        panel.add(arrayofButtons[row][column]);
              //          JTextArea textA = new JTextArea();
              //          panel.add(textA);
              //          BoxLayout ourLayout = new BoxLayout(textA, BoxLayout.X_AXIS);
              //          textA.setLayout(ourLayout);
              //          textA.setPreferredSize(new Dimension (100, 50));
              return panel;
          * Called when user clicks buttons with ActionListeners.
         public void actionPerformed(ActionEvent e) {
              JButton button = (JButton) e.getSource();
              if (button == reset){
                   status.setText("");
                   for (int row = 0; row < arrayofButtons.length; ++row)
                        for (int column = 0; column < arrayofButtons[0].length; ++column){
                             char letters = (char)(Math.random()*26+65);
                             arrayofButtons[row][column].setText(letters+"");
                             arrayofButtons[row][column].setBackground(Color.white);
                             prevButton = null;
                             messStatus.setText("");
              else if (button == submit){
                   boolean b = lex.contains(status.getText());
                   //               System.out.println(lex); // checking what came in.
                   if (b==true){
                        messStatus.setText("'" + status.getText() + "'" + " found. ");
                        status.setText("");
                        textL.setText(status.getText());
                        for (int row = 0; row < arrayofButtons.length; ++row)
                             for (int column = 0; column < arrayofButtons[0].length; ++column){                                   
                                  arrayofButtons[row][column].setBackground(Color.white);
                                  prevButton = null;
                   if (b!=true){
                        messStatus.setText("'" + status.getText() + "'" + " not found. ");
                        status.setText("");
                        for (int row = 0; row < arrayofButtons.length; ++row)
                             for (int column = 0; column < arrayofButtons[0].length; ++column){                                   
                                  arrayofButtons[row][column].setBackground(Color.white);
                                  prevButton = null;
              else {
                   String rowColumn[] = button.getActionCommand().split(" ");
                   int row = Integer.parseInt(rowColumn[0]);
                   int column = Integer.parseInt(rowColumn[1]);
                   if(prevButton == null){
                        prevButton = button;
                        prevRow = row;
                        prevCol = column;
                        arrayofButtons[row][column].setBackground(Color.orange);
                        status.setText(status.getText()+ arrayofButtons[row][column].getText());
                   else{
                        int dist = (int)Math.pow((prevRow - row)*(prevRow - row) + (prevCol - column)*(prevCol - column),0.5);
                        if(dist == 1 && button.getBackground() == Color.white ){
                             prevButton.setBackground(Color.green);
                             arrayofButtons[row][column].setBackground(Color.orange);
                             status.setText(status.getText()+ arrayofButtons[row][column].getText());
                             prevButton = button;
                             prevRow = row;
                             prevCol = column;
                    * when submit button is clicked, grab status and place in messStatus
         // Your Control Panel
         private JPanel buildControlPanel() {
              JPanel panel = new JPanel();
              BoxLayout ourLayout = new BoxLayout(panel, BoxLayout.X_AXIS);
              panel.setLayout(ourLayout);
              //Your reset button
              reset = new JButton("Reset");
              reset.addActionListener(this);
              panel.add(reset);
              //distance of status from Reset button
              JPanel space = new JPanel();
              space.setPreferredSize(new Dimension (10,10));
              panel.add(space);
              //Your status label
              status = new JLabel();
              panel.add(status);
              //the distance from Reset button to Submit button
              JPanel blank = new JPanel();
              blank.setPreferredSize(new Dimension(400, 30));
              panel.add(blank);
              //your Submit button
              submit= new JButton("SUMBIT");
              submit.addActionListener(this);
              panel.add(submit);
              //button panel
              panel.add(Box.createHorizontalGlue());
              JLabel statusLabel = new JLabel();
              panel.add(statusLabel);
              panel.setBorder(BorderFactory.createLineBorder(Color.black));
              return panel;
         private JPanel buildMessagePanel(){
              JPanel messPanel = new JPanel();
              BoxLayout ourLayout = new BoxLayout(messPanel, BoxLayout.X_AXIS);
              messPanel.setLayout(ourLayout);
              messPanel.setPreferredSize(new Dimension(100,50));
              messStatus = new JLabel();
              messPanel.add(messStatus);
              return messPanel;
         // create and show GUI
         private static void createAndShowGUI() {
              // Create and set up the window.
              JFrame frame = new JFrame("BoggleUI");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              // Add contents to the window.
              frame.add(new Boggle());
              // Display the window.
              frame.pack();
              frame.setVisible(true);
         public static void main(String[] args) {
              // Schedule a job for the event-dispatching thread:
              // creating and showing this application's GUI.
              javax.swing.SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        createAndShowGUI();
    }Edited by: user13813121 on Mar 22, 2011 8:39 AM

    I found this code, which is not so different from mine, but a lot simpler easier to understand. I just don't know how this code works even without implementing the Policies for JScroll.
    import java.awt.*;
    import javax.swing.*;
    public class scrollDemo extends JFrame {
        //============================================== instance variables
       JTextArea _resultArea = new JTextArea(6, 20);
        //====================================================== constructor
        public scrollDemo() {
            //... Set textarea's initial text, scrolling, and border.
            _resultArea.setText("Enter more text to see scrollbars");
            _resultArea.setLineWrap(true);
            JScrollPane scrollingArea = new JScrollPane(_resultArea);
            //... Get the content pane, set layout, add to center
            JPanel content = new JPanel();
            content.setLayout(new BorderLayout());
            content.add(scrollingArea, BorderLayout.CENTER);
            //... Set window characteristics.
            this.setContentPane(content);
            this.setTitle("TextAreaDemo B");
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            this.pack();
        //============================================================= main
        public static void main(String[] args) {
            JFrame win = new scrollDemo();
            win.setVisible(true);
    }

  • JTextArea w/Scroll bar wont scroll AND code drops through if statements

    Hi, I'm still having trouble with the text area in the following code. When you run the code, you get the top arrow on the scroll bar, but the bottom is cut off. Also, a big problem is that no matter what choice is selected from the combo box, the code drops through to the last available value each time. Someone on the forums suggested using an array list for the values in the combo box, but I have not been able to figure out how to do that. A quick example would be apprciated.
    Thank you in advance for any help
    //Import required libraries
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
    import java.io.*;
    import java.text.*;
    import java.math.*;
    import java.util.*;
    //Create the class
    public class Week3Assignment407B extends JFrame implements ActionListener
         //Panels used in container
         private JPanel jPanelRateAndTermSelection;         
         //Variables for Menu items
         private JMenuBar menuBar;    
         private JMenuItem exitMenuItem; 
         private JMenu fileMenu; 
         //Variables for user instruction and Entry       
         private JLabel jLabelPrincipal;   
         private JPanel jPanelEnterPrincipal;  
         private JLabel jLabelChooseRateAndTerm; 
         private JTextField jTextFieldMortgageAmt;
         //Variables for combo box and buttons
         private JComboBox TermAndRate;
         private JButton buttonCompute;
         private JButton buttonNew; 
         private JButton buttonClose;
         //Variables display output
         private JPanel jPanelPaymentOutput;
         private JLabel jLabelPaymentOutput;
         private JPanel jPanelErrorOutput;
         private JLabel jLabelErrorOutput;  
         private JPanel jPanelAmoritizationSchedule;
         private JTextArea jTextAreaAmoritization;
         // Constructor 
         public Week3Assignment407B() {            
              super("Mortgage Application");      
               initComponents();      
         // create a method that will initialize the main frame for the GUI
          private void initComponents()
              setSize(700,400);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);      
              Container pane = getContentPane();
              GridLayout grid = new GridLayout(15, 1);
              pane.setLayout(grid);       
              //declare all of the panels that will go inside the main frame
              // Set up the menu Bar
              menuBar = new JMenuBar();
              fileMenu = new JMenu();
              fileMenu.setText("File");        
              exitMenuItem = new JMenuItem(); 
               exitMenuItem.setText("Exit");
              fileMenu.add(exitMenuItem); 
              menuBar.add(fileMenu);       
              pane.add(menuBar);
              //*******************TOP PANEL ENTER PRINCIPAL*****************************//
              // Create a label that will advise user to enter a principle amount
              jPanelEnterPrincipal = new JPanel(); 
              jLabelPrincipal = new JLabel("Amt to borrow in whole numbers");
              jTextFieldMortgageAmt = new JTextField(10);
              GridLayout Principal = new GridLayout(1,2);
              jPanelEnterPrincipal.setLayout(Principal); 
                jPanelEnterPrincipal.add(jLabelPrincipal);
              jPanelEnterPrincipal.add(jTextFieldMortgageAmt);
              pane.add(jPanelEnterPrincipal);
              //****************MIDDLE PANEL CHOOSE INTEREST RATE AND TERM*****************//
              // Create a label that will advise user to choose an Int rate and term combination
              // from the combo box
              jPanelRateAndTermSelection = new JPanel();
              jLabelChooseRateAndTerm = new JLabel("Choose the Rate and Term");
              buttonCompute = new JButton("Compute Mortgage");
              buttonNew = new JButton("New Mortgage");
              buttonClose = new JButton("Close");
              GridLayout RateAndTerm = new GridLayout(1,5);
              //FlowLayout RateAndTerm = new FlowLayout(FlowLayout.LEFT);
              jPanelRateAndTermSelection.setLayout(RateAndTerm);
              jPanelRateAndTermSelection.add(jLabelChooseRateAndTerm);
              TermAndRate = new JComboBox();
              jPanelRateAndTermSelection.add(TermAndRate);
              TermAndRate.addItem("7 years at 5.35%");
              TermAndRate.addItem("15 years at 5.5%");
              TermAndRate.addItem("30 years at 5.75%");
              jPanelRateAndTermSelection.add(buttonCompute);
              jPanelRateAndTermSelection.add(buttonNew);
              jPanelRateAndTermSelection.add(buttonClose);
              pane.add(jPanelRateAndTermSelection);
              //**************BOTTOM PANEL TEXT AREA FOR AMORITIZATION SCHEDULE***************//
              jPanelAmoritizationSchedule = new JPanel();
              jTextAreaAmoritization = new JTextArea(26,50);
              // add scroll pane to output text area
                   JScrollPane scrollBar = new JScrollPane(jTextAreaAmoritization, 
                   JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                     JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
              jPanelAmoritizationSchedule.add(scrollBar);
                pane.add(jPanelAmoritizationSchedule);
              //***************ADD THE ACTION LISTENERS TO THE GUI COMPONENTS*****************//
              // Add ActionListener to the buttons and menu item
              exitMenuItem.addActionListener(this);
              buttonCompute.addActionListener(this);         
              buttonNew.addActionListener(this);
              buttonClose.addActionListener(this);
              TermAndRate.addActionListener(this);
              jTextFieldMortgageAmt.addActionListener(this);
              //*************** Set up the Error output area*****************//
              jPanelErrorOutput = new JPanel();
              jLabelErrorOutput = new JLabel();
              FlowLayout error = new FlowLayout();
              jPanelErrorOutput.setLayout(error);
              pane.add(jLabelErrorOutput);
              setContentPane(pane);
              pack();
              setVisible(true);
         //Display error messages
         private void OutputError(String ErrorMsg){
              jLabelErrorOutput.setText(ErrorMsg);
              jPanelErrorOutput.setVisible(true);
         //create a method that will clear all fields when the New Mortgage button is chosen
         private void clearFields()
              jTextAreaAmoritization.setText("");
              jTextFieldMortgageAmt.setText("");
         //**************CREATE THE CLASS THAT ACTUALLY DOES SOMETHING WITH THE EVENT*****//
         //This is the section that receives the action source and directs what to do with it
         public void actionPerformed(ActionEvent e)
              Object source = e.getSource();
              String ErrorMsg;
              double principal;
              double IntRate;
              int Term;
              double monthlypymt;
              double TermInYears = 0 ;
              if(source == buttonClose)
                   System.exit(0);
              if (source == exitMenuItem) {      
                       System.exit(0);
              if (source == buttonNew)
                   clearFields();
              if (source == buttonCompute)
                   //Make sure the user entered valid numbers
                   try
                        principal = Double.parseDouble(jTextFieldMortgageAmt.getText());
                   catch(NumberFormatException nfe)
                        ErrorMsg = (" You Entered an invalid Mortgage amount"
                                  + " Please try again. Please do not use commas or decimals");
                        jTextAreaAmoritization.setText(ErrorMsg);
                   principal = Double.parseDouble(jTextFieldMortgageAmt.getText());
                    if (TermAndRate.getSelectedItem() == "7 years at 5.35%") ;
                        Term = 7;
                        IntRate = 5.35;
                    if (TermAndRate.getSelectedItem()  == "15 years at 5.5%") ;
                        Term = 15;
                        IntRate = 5.5;
                    if (TermAndRate.getSelectedItem() == "30 years at 5.75%") ;
                        Term = 30;
                        IntRate = 5.75;
                   //Variables have been checked for valid input, now calculate the monthly payment
                   NumberFormat formatter = new DecimalFormat ("$###,###.00");
                   double intdecimal = intdecimal = IntRate/(12 * 100);
                   int months = Term * 12;
                   double monthlypayment = principal *(intdecimal / (1- Math.pow((1 + intdecimal),-months)));
                   //Display the Amoritization schedule
                   jTextAreaAmoritization.setText(" Loan amount of " + formatter.format(principal)
                                                    + "\n"
                                                    + " Interest Rate is " +  IntRate + "%"
                                            + "\n"
                                            + " Term in Years "  + Term
                                            + " Monthly payment "+  formatter.format(monthlypayment)
                                            + "\n"
                                            + "  Amoritization is as follows:  "
                                            + "------------------------------------------------------------------------");
         public Insets getInsets()
              Insets around = new Insets(35,20,20,35);
              return around;
         //Main program     
         public static void main(String[]args) { 
              Week3Assignment407B frame = new Week3Assignment407B(); 
       }

    here's your initComponents with a couple of changes, the problem was the Gridlayout(15,1)
    also, the scrollpane needed a setPreferredSize()
      private void initComponents()
        setSize(700,400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //Container pane = getContentPane();
        JPanel pane = new JPanel();
        //GridLayout grid = new GridLayout(15, 1);
        GridLayout grid = new GridLayout(2, 1);
        pane.setLayout(grid);
        menuBar = new JMenuBar();
        fileMenu = new JMenu();
        fileMenu.setText("File");
        exitMenuItem = new JMenuItem();
        exitMenuItem.setText("Exit");
        fileMenu.add(exitMenuItem);
        menuBar.add(fileMenu);
        //pane.add(menuBar);
        setJMenuBar(menuBar);
        jPanelEnterPrincipal = new JPanel();
        jLabelPrincipal = new JLabel("Amt to borrow in whole numbers");
        jTextFieldMortgageAmt = new JTextField(10);
        GridLayout Principal = new GridLayout(1,2);
        jPanelEnterPrincipal.setLayout(Principal);
          jPanelEnterPrincipal.add(jLabelPrincipal);
        jPanelEnterPrincipal.add(jTextFieldMortgageAmt);
        pane.add(jPanelEnterPrincipal);
        jPanelRateAndTermSelection = new JPanel();
        jLabelChooseRateAndTerm = new JLabel("Choose the Rate and Term");
        buttonCompute = new JButton("Compute Mortgage");
        buttonNew = new JButton("New Mortgage");
        buttonClose = new JButton("Close");
        GridLayout RateAndTerm = new GridLayout(1,5);
        jPanelRateAndTermSelection.setLayout(RateAndTerm);
        jPanelRateAndTermSelection.add(jLabelChooseRateAndTerm);
        TermAndRate = new JComboBox();
        jPanelRateAndTermSelection.add(TermAndRate);
        TermAndRate.addItem("7 years at 5.35%");
        TermAndRate.addItem("15 years at 5.5%");
        TermAndRate.addItem("30 years at 5.75%");
        jPanelRateAndTermSelection.add(buttonCompute);
        jPanelRateAndTermSelection.add(buttonNew);
        jPanelRateAndTermSelection.add(buttonClose);
        pane.add(jPanelRateAndTermSelection);
        jPanelAmoritizationSchedule = new JPanel();
        jTextAreaAmoritization = new JTextArea(26,50);
        JScrollPane scrollBar = new JScrollPane(jTextAreaAmoritization,
          JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
        scrollBar.setPreferredSize(new Dimension(500,100));//<------------------------
        jPanelAmoritizationSchedule.add(scrollBar);
        getContentPane().add(pane,BorderLayout.NORTH);
        getContentPane().add(jPanelAmoritizationSchedule,BorderLayout.CENTER);
        exitMenuItem.addActionListener(this);
        buttonCompute.addActionListener(this);
        buttonNew.addActionListener(this);
        buttonClose.addActionListener(this);
        TermAndRate.addActionListener(this);
        jTextFieldMortgageAmt.addActionListener(this);
        jPanelErrorOutput = new JPanel();
        jLabelErrorOutput = new JLabel();
        FlowLayout error = new FlowLayout();
        jPanelErrorOutput.setLayout(error);
        //pane.add(jLabelErrorOutput);not worrying about this one
        //setContentPane(pane);
        pack();
        setVisible(true);
      }instead of
    if (TermAndRate.getSelectedItem() == "7 years at 5.35%") ;
    Term = 7;
    IntRate = 5.35;
    you would be better off setting up arrays
    int[] term = {7,15,30};
    double[] rate = {5.35,5.50,5.75};
    then using getSelectedIndex()
    int loan = TermAndRate.getSelectedIndex()
    Term = term[loan];
    IntRate = rate[loan];

  • How to create a cell column with JTextArea in JTable

    I am developing an Application using Java Swings. I need to use JTextArea in my JTable. I need the code to do so. I also want to show the scrollbars in the JTextArea.
    Any efforts in this regard would be of great help. Thanks in advance.
    Thanks
    Alagu

    have a look at
    http://forum.java.sun.com/thread.jsp?forum=57&thread=134412

  • Too much data for JTextArea

    Howdy people, I've been stuck on this problem for a while now. I writing a povvy hex-editor, and it works (yay!), but when I open largish files (>= 20kB) it really chokes on it. Not on the conversion from bytes to hex string, but (you guessed it) displaying it in the JTextArea. I've tried a couple of things. Make it a Thread (so it can update a pretty progress bar), I tried appending the data in sections, instead of one giant setText().... No go.
    Here's what I have so far:
    import javax.swing.JTextArea;
    public class DisplayThread extends Thread
        private static final int BUFSIZE = 100000;
        private FileEditor parent;
        private JTextArea textArea;
        private StringBuffer data;
        private ProgressDialog pd;
        public DisplayThread(FileEditor p, JTextArea jta, StringBuffer s, ProgressDialog pr)
            parent = p;
            textArea = jta;
            data = s;
            pd = pr;
        public void run()
            System.out.println("starting DisplayThread");
            long time = System.currentTimeMillis();
            textArea.setText("");
            int len = data.length();
            for(int i=0;i<len;i+=BUFSIZE)
                int n = (i+BUFSIZE<len)?i+BUFSIZE:len;
                textArea.append(data.substring(i,n));
                pd.setProgress(i, len);
            System.out.println("It took " + (System.currentTimeMillis() - time) + "ms by buffering");
            time = System.currentTimeMillis();
            textArea.setText(data.toString());
            System.out.println("It took " + (System.currentTimeMillis() - time) + "ms directly");
            textArea.setEditable(true);
            pd.setVisible(false);
            System.out.println("finishing DisplayThread");
    }At the moment I've got both the "bit-by-bit" display method, and the "one-shot-setText()" methods going to compare times, but check out these times for a 900k file...
    It took 673439ms by buffering
    It took 137628ms directly
    For the first one, that's over 11 mins!!!!
    Anyway, I did searches on what to do in this scenario, one answer was Don't!, the other was "only display what's necessary".
    So...
    I've tried to create a "BufferedJTextArea", and only set the text according to what will be visible in the scrollpane/scrollbar, but it's not working (all sorts of complications with adding a scrollbar to a JTextArea, or adding a JTextArea to a scrollPane....)
    Also, even after it loads all the data into the JTextArea, it takes it's sweet time to repaint...
    Any ideas on how to make it faster? Continue with the "BufferedJTextArea" (if that's the case, that'll be the next question)?
    Or give up and warn ppl not to load files larger than about 15k?
    Thanks ppl,
    Radish21

    But with a JList, you can only have one column, right? That'd mean I have to break up the String with \n all over the place.
    I did look at JTable first, and even tried to use one, but I've never used them before, and now I know why. Too damn difficult.
    I'm getting closer now, but still having hiccups (or is it hiccoughs? :)
    I had to make the class a JPanel itself, that adds a BufferedTextArea to a JScrollPane... it works, so why fix it? ;)
    import javax.swing.JTextArea;
    import javax.swing.JScrollBar;
    import javax.swing.JScrollPane;
    import javax.swing.JPanel;
    import java.awt.event.AdjustmentListener;
    import java.awt.event.AdjustmentEvent;
    public class BufferedJTextArea extends JPanel
        protected BJTextArea textArea;
        protected JScrollPane scrollPane;
        public BufferedJTextArea()
            textArea = new BJTextArea();
            scrollPane = new JScrollPane(textArea);
            scrollPane.getVerticalScrollBar().addAdjustmentListener(textArea);
            setVisible(true);
            setLayout(new java.awt.BorderLayout());
            add(scrollPane, "Center");
        public void setText(String s)
            textArea.setText(s);
        private class BJTextArea extends JTextArea implements AdjustmentListener
            protected static final int BUF_SIZE = 4096; // display 4kB at a time
            protected String data;
            protected int len, startIndex = 0, endIndex = 0;
            private java.awt.FontMetrics fontMetrics;
            private int val = 0;
            public BJTextArea()
                super();
                setLineWrap(true);
                setVisible(true);
                fontMetrics = getFontMetrics(getFont());
            public void adjustmentValueChanged(AdjustmentEvent e)
                val = e.getValue();
                adjustView();
            public void setText(String s)
                data = s;
                len = data.length();
                startIndex = 0;
                if(len <= BUF_SIZE)
                    endIndex = len;
                    super.setText(data);
                else
                    endIndex = -1;
                    val = 0;
                    adjustView();
            protected void adjustView()
                if(endIndex == -1 && startIndex == 0)
                    endIndex = java.lang.Math.min(len, BUF_SIZE);
                    super.setText(data.substring(startIndex, endIndex));
                    return;
                if(len <= BUF_SIZE)
                    return;
                int startLine = scrollPane.getVerticalScrollBar().getValue() / getRowHeight();
                int linesVisible = // haven't worked out what goes here yet
                // Some way to work out whether I need to adjust things.
    }Anyway, thanks for the tips, but I think you're right, I'll stick with the BufferedJTextArea....
    If you have any ideas about checking for if the view is about to get out of range, let me know. Also, I've tried setting the vertical scrollbar's maximum value, but it ignores me (because I need it to be reflect the entire data string, not just the segment displayed). If you have any ideas, they'd be greatly appreciated.
    Cheers,
    Radish21

  • Need Help with scrollbars

    hu..
    i have this JFrane that has a table which has scrollbars...
    i have included in my code setResizable(false) so the user will not be able to maximize the page..
    i have a function AdScroll()[that adds scrollbars] that will be called every time i add ,delete ,update a user ..
    my problem is when i click on the delete and update buttons the user will not be deleted or updated from the table, but when i remove AddScroll() the user will be deleted and updated from the table but the scroll bars will not be added..
    so can some one help me with this problem.
    thankx
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.sql.*;
    import java.io.*;
    import javax.swing.JPanel;
    import java.applet.*;
    import sun.audio.*;
    import java.net.*;
    import java.text.*;
    class UtilityMethods extends JFrame implements ActionListener
      private boolean tabsVisible=false;
      private File fileName;
      private RandomAccessFile output;
      AudioStream voice;
      UtilityMethods utilities;
      Connection conn;
      Statement stat;
      String dsnName, userStatus;
      String appTable = "CUSTOMER";
      Container c = getContentPane();
       JTabbedPane tabs;
        //JScrollPane scrollpane;
      JTable dataTable, addataTable;
      static String[][] tableData, adtableData;
      JScrollPane scrollpane, adscrollpane,vscrollpane;
      JTextField id, name, address, phone, sex, dob, photo,audio,template;
      JTextArea comments;
      JButton search, update, clear, add, delete, close,audio1,faceBrowse,voiceBrowse,voice1;
      JPanel customerPanel, adminPanel;
      JPanel backPanel, inputPanel, middlePanel, buttonPanel1, buttonPanel2, photoHolder;
      JTextField adname, adusername, adpassword;
      JPanel adbackPanel, adinputPanel, admiddlePanel, adbuttonPanel1, adbuttonPanel2, radioPanel;
      JButton adsearch, adupdate, adclear, adadd, addelete, adclose;
      JRadioButton userStat, adminStat, cleared;
      ButtonGroup statusGroup;
      //===================================================================================================
      /*public UtilityMethods()
        makeGUI();
      //Create the GUI:
      void makeGUI()
        c.setLayout(new BorderLayout());
        tabs = new JTabbedPane();
        customerPanel = new JPanel(new BorderLayout());
        adminPanel = new JPanel(new BorderLayout());
    //    voicePanel= new JPanel(new BorderLayout());
        //1. Construct customers tab:
          //The data input section:
        inputPanel      = new JPanel(new GridLayout(4, 4));
         id = new JTextField(20);
                 name = new JTextField(20);
                 address = new JTextField(20);
                 phone = new JTextField(20);
                 sex = new JTextField(20);
                 dob = new JTextField(20);
                 photo = new JTextField(20);
                 audio = new JTextField(20);
                 template = new JTextField(20);
                 faceBrowse = new JButton("...");
                 faceBrowse.setBounds(210, 150, 25, 25);
        inputPanel.add(new JLabel("CPR", JLabel.CENTER));
        inputPanel.add(id);
        inputPanel.add(new JLabel("Name", JLabel.CENTER));
        inputPanel.add(name);
        inputPanel.add(new JLabel("Address", JLabel.CENTER));
        inputPanel.add(address);
        inputPanel.add(new JLabel("Phone", JLabel.CENTER));
        inputPanel.add(phone);
        inputPanel.add(new JLabel("Sex", JLabel.CENTER));
        inputPanel.add(sex);
        inputPanel.add(new JLabel("Date Of Birth", JLabel.CENTER));
        inputPanel.add(dob);
        inputPanel.add(new JLabel("Customer Photo ", JLabel.CENTER));
        inputPanel.add(photo);
        inputPanel.add(new JLabel("Voice ", JLabel.CENTER));
        inputPanel.add(audio);
    customerPanel.add(inputPanel, BorderLayout.NORTH);
          //The buttons section:
        backPanel = new JPanel();
        middlePanel = new JPanel(new BorderLayout());
        buttonPanel1 = new JPanel();
        buttonPanel2 = new JPanel();
        search   = new JButton("SEARCH");
        update   = new JButton("UPDATE");
        clear    = new JButton("CLEAR");
        add      = new JButton("ADD");
        delete   = new JButton("DELETE");
        close    = new JButton("EXIT");
        audio1    =new JButton("Voice");
        //faceBrowse    = new JButton("...");
        //voiceBrowse    =new JButton("...");
        search.setPreferredSize(new Dimension(102, 26));
        update.setPreferredSize(new Dimension(102, 26));
        clear.setPreferredSize(new Dimension(102, 26));
        add.setPreferredSize(new Dimension(102, 26));
        delete.setPreferredSize(new Dimension(102, 26));
        close.setPreferredSize(new Dimension(102, 26));
        audio1.setPreferredSize(new Dimension(102, 26));
        faceBrowse.setPreferredSize(new Dimension(26, 26));
        //voiceBrowse.setPreferredSize(new Dimension(26, 26));
        search.addActionListener(this);
        update.addActionListener(this);
        clear.addActionListener(this);
        add.addActionListener(this);
        delete.addActionListener(this);
        close.addActionListener(this);
        audio1.addActionListener(this);
        //faceBrowse.addActionListener(this);
        //voiceBrowse.addActionListener(this);
        buttonPanel1.add(search);
        //buttonPanel1.add(faceBrowse);
        buttonPanel1.add(update);
        buttonPanel1.add(clear);
        buttonPanel2.add(add);
        buttonPanel2.add(delete);
        buttonPanel2.add(close);
        buttonPanel2.add(audio1);
        //buttonPanel1.add(voiceBrowse);
        middlePanel.add(buttonPanel1, BorderLayout.NORTH);
        middlePanel.add(buttonPanel2, BorderLayout.CENTER);
        photoHolder = new JPanel();
        Icon curPhoto = new ImageIcon("");
        Icon[] custPhotos = {curPhoto};
        JList photosList = new JList(custPhotos);
        photosList.setFixedCellHeight(100);
        photosList.setFixedCellWidth(80);
        photoHolder.add(photosList);
        makeComments();
        backPanel.add(middlePanel);
        backPanel.add(photoHolder);
        backPanel.add(comments);
        customerPanel.add(backPanel, BorderLayout.CENTER);
      pack();
        setVisible(true);
        setSize(500,700);
      } //makeGUI
    void updateTable()
          ResultSet results = null;
          ResultSet results1 = null;
          try
            //Get the number of rows in the table so we know how big to make the data array..
            int rowNumbers  = 0;
            int columnCount = 6;
            results = stat.executeQuery("SELECT COUNT(*) FROM CUSTOMER ");
            if(results.next())
              rowNumbers = results.getInt(1);
            } //if
            if(rowNumbers == 0)
            rowNumbers = 1;
            tableData = new String[rowNumbers][columnCount];
            //Initialize the data array with "" so we avoid possibly having nulls in it later..
            for(int i =0;i<tableData.length;i++)
              for(int j=0;j<tableData[0].length;j++)
              tableData[i][j] = "";
            //Populate the data array with results of the query on the database..
            int currentRow = 0;
            results1 = stat.executeQuery("SELECT * FROM CUSTOMER ORDER BY ID");
            while (results1.next())
              for(int i = 0; i < columnCount; i++)
              tableData[currentRow] = results1.getString(i + 1);
    currentRow++;
    } //while
    //Create the table model:
    final String[] colName = { "CPR", "Name", "Address", "Phone", "Sex", "Date OF Birth" };
    TableModel pageModel = new AbstractTableModel()
    public int getColumnCount()
    return tableData[0].length;
    } //getColumnCount
    public int getRowCount()
    return tableData.length;
    } //getRowCount
    public Object getValueAt(int row, int col)
    return tableData[row][col];
    } //getValueAt
    public String getColumnName(int column)
    return colName[column];
    } //getcolName
    public Class getColumnClass(int col)
    return getValueAt(0, col).getClass();
    } //getColumnClass
    public boolean isCellEditable(int row, int col)
    return false;
    } //isCellEditable
    public void setValueAt(String aValue, int row, int column)
    tableData[row][column] = aValue;
    } //setValueAt
    //dataTable.setValue( new JScrollBar(JScrollBar.HORIZONTAL), 2,1 );
    }; //pageModel
    //Create the JTable from the table model:
    JTable dataTable = new JTable(pageModel);
    // dataTable.setModel();
    /*if (scrollpane != null)
    scrollpane.setVisible(false);
    scrollpane = null;
    } //if*/
    //scrollpane = new JScrollPane(dataTable);
    //scrollpane.setVisible(true);
    if (inputPanel == null)
    makeGUI();
    JScrollPane scrollpane =new JScrollPane(dataTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    dataTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    // Create vertical box for second tab
    Box box = Box.createVerticalBox();
    // Create component for top
    box.add(customerPanel);
    // Place glue between components
    box.add(Box.createVerticalGlue());
    // Create component for middle
    box.add(middlePanel);
    // Place glue between components
    box.add(Box.createVerticalGlue());
    // Create component for middle
    box.add(backPanel);
    // Place glue between components
    box.add(Box.createVerticalGlue());
    // Create component for bottom
    box.add(scrollpane);
    // Add box to JTabbedPane
    tabs.add(box, "Customer");
              setResizable(false);
    id.grabFocus();
    pack();
    repaint();
    adupdateTable();
    } //try
    catch (Exception e)
    System.out.println("Caught updateTable exception: " + e);
    e.printStackTrace();
    } //catch
    } //updatetable
    //===================================================================================================
    //===================================================================================================
    //Update the customer table from the database:
    void updateTable(String userStatus)
    this.userStatus = userStatus;
         updateTable();
         if(userStatus.equals("user"))
         delete.setEnabled(false);
         tabs.setEnabledAt(1, false);
    public void actionPerformed(ActionEvent e)
    FileInputStream fis = null;
    if (e.getSource() == add) //The ADD button.
    //User has not populated all the input fields.
    if(name.getText().equals("")|| address.getText().equals("")|| phone.getText().equals("")|| sex.getText().equals("")|| dob.getText().equals("")|| photo.getText().equals(""))
    JOptionPane.showMessageDialog(null, "Please fill in all the fields","Missing Fields",JOptionPane.INFORMATION_MESSAGE);
    else
    // save the new customer:
    try
    //1. take the customer's data and photo:
    int userId          = Integer.parseInt(id.getText());
    String userName      = name.getText();
    String userAddress      = address.getText();
    String userPhone      = phone.getText();
    String userSex      = sex.getText();
    String userDateBirth      = dob.getText();
    String photoName      = photo.getText();
    String audioName= audio.getText();
    File file           = new File(photoName);
    int fileLength      = (int)file.length();
    //2. Set the user's photo into the photoHolder:
    photoHolder.setVisible(false);
    photoHolder = null;
    comments.setVisible(false);
    comments = null;
    Icon[] custPhotos = {new ImageIcon(photoName)};
    JList photosList = new JList(custPhotos);
    photosList.setFixedCellHeight(100);
    photosList.setFixedCellWidth(80);
    photoHolder = new JPanel();
    photoHolder.add(photosList);
    makeComments();
    //3. Insert the data and photo into the database:
    if(fileLength > 0)
    fis = new FileInputStream(file);
    String query = " INSERT INTO CUSTOMER VALUES('"+userId+"', '"+ userName+ "', '"+ userAddress+ "', " +" '"+ userPhone+ "', '"+ userSex+ "', '"+ userDateBirth+ "', ?,?,? ) ";
    PreparedStatement pstmt = conn.prepareStatement(query);
    pstmt.setBinaryStream(1, fis, fileLength);
              pstmt.setString(2,photoName);
              pstmt.setString(3,audioName);
    pstmt.executeUpdate();
    comments.setText(userName+", added.");
    else
    String query = " INSERT INTO CUSTOMER (id, name, address, phone, sex, dob) VALUES('"+userId+"', '"+userName+"', '"+userAddress+"', '"+userPhone+"', '"+userSex+"', '"+userDateBirth+"') ";
    stat.executeUpdate(query);
    comments.setText("Customer saved without a photo.");
    backPanel.add(photoHolder);
    backPanel.add(comments);
    //updateTable();
    AddScroll();
    } //try
    catch (Exception ee)
    //The danger of putting creating the JOptionPane in here is that it will show the same message regardless of the error.
              JOptionPane.showMessageDialog(null, "Customers CPR already exits!!Please enter another CPR","Invalid",JOptionPane.INFORMATION_MESSAGE);
    System.out.println("Caught exception in add action: " + ee);
    } //catch
    } //if
    }//add button
    void AddScroll()
         JScrollPane scrollpane =new JScrollPane(dataTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    scrollpane.getViewport().add(dataTable);

    hi i tryed the JTable.revalidate() but i still did't work...
    i did this :
    public void actionPerformed(ActionEvent e)
        FileInputStream fis = null;
        if (e.getSource() == add) //The ADD button.
          //User has not populated all the input fields.
          if(name.getText().equals("")|| address.getText().equals("")|| phone.getText().equals("")|| sex.getText().equals("")|| dob.getText().equals("")|| photo.getText().equals(""))
            JOptionPane.showMessageDialog(null, "Please fill in all the fields","Missing Fields",JOptionPane.INFORMATION_MESSAGE);
          else
            // save the new customer:
            try
              //1. take the customer's data and photo:
              int    userId          = Integer.parseInt(id.getText());
              String userName      = name.getText();
              String userAddress      = address.getText();
              String userPhone      = phone.getText();
              String userSex      = sex.getText();
              String userDateBirth      = dob.getText();
              String photoName      = photo.getText();
              String audioName=   audio.getText();
              File   file           = new File(photoName);
              int    fileLength      = (int)file.length();
              //2. Set the user's photo into the photoHolder:
              photoHolder.setVisible(false);
              photoHolder = null;
              comments.setVisible(false);
              comments = null;
              Icon[] custPhotos = {new ImageIcon(photoName)};
              JList photosList = new JList(custPhotos);
              photosList.setFixedCellHeight(100);
              photosList.setFixedCellWidth(80);
              photoHolder = new JPanel();
              photoHolder.add(photosList);
              makeComments();
              //3. Insert the data and photo into the database:
              if(fileLength > 0)
                fis = new FileInputStream(file);
                String query = " INSERT INTO CUSTOMER VALUES('"+userId+"', '"+ userName+ "', '"+ userAddress+ "', " +" '"+ userPhone+ "', '"+ userSex+ "', '"+ userDateBirth+ "', ?,?,? ) ";
                PreparedStatement pstmt = conn.prepareStatement(query);
                pstmt.setBinaryStream(1, fis, fileLength);
                  pstmt.setString(2,photoName);
                  pstmt.setString(3,audioName);
                pstmt.executeUpdate();
                comments.setText(userName+", added.");
              else
                String query = " INSERT INTO CUSTOMER (id, name, address, phone, sex, dob) VALUES('"+userId+"', '"+userName+"', '"+userAddress+"', '"+userPhone+"', '"+userSex+"', '"+userDateBirth+"') ";
                stat.executeUpdate(query);
                comments.setText("Customer saved without a photo.");
              backPanel.add(photoHolder);
              backPanel.add(comments);
              //updateTable();
              dataTable.revalidate();
               AddScroll();
            } //try
            catch (Exception ee)
               //The danger of putting creating the JOptionPane in here is that it will show the same message regardless of the error.
                JOptionPane.showMessageDialog(null, "Customers CPR already exits!!Please enter another CPR","Invalid",JOptionPane.INFORMATION_MESSAGE);
              System.out.println("Caught exception in add action: " + ee);
                ee.printStackTrace();
            } //catch
          } //if
        }//add buttonand i included this function AddScroll() that i will add the scroll bars :
    void AddScroll()
          JScrollPane scrollpane =new JScrollPane(dataTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    scrollpane.getViewport().add(dataTable);
    // AbstractTableModel pageModel  = (AbstractTableModel)dataTable.getModel();
    //            pageModel .fireTableDataChanged();
    //dataTable.updateUI();
    }thankx

Maybe you are looking for