Scrolling in JtextArea ????

Can anybody tell me how to introduce scrolling in JtextArea ???
Following is the skeleton of my code ...
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;         
import java.io.*;
public class Interface extends Frame
             String path;
             JTextField text = new JTextField();
     JButton button = new JButton("Browse");
     JButton executeButton = new JButton("Execute");
     JTextArea area = new JTextArea();
     JPanel P1 = new JPanel();
        public Component createComponents()
                    text.setBounds(30,30,300,20);
             button.setBounds(30,70,80,20);
                     executeButton.setBounds(130,70,80,20);
                     area.setBounds(30,110,540,430);
                P1.setBackground(Color.red);
                P1.setLayout(null);
             P1.add(button);
             P1.add(executeButton);
             P1.add(text);
                P1.add(area);
             return P1;
         public static void main(String[] args)
             JFrame frame = new JFrame("Pseudocode Interpreter");
             Interface app = new Interface();
             Component contents = app.createComponents();
             frame.getContentPane().add(contents);
                frame.setSize(600,600);
                frame.setVisible(true);
                frame.setLocation(50,50);
                     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}Thanks !!!!

I am happy to help use but addind scroll pane is a simple one.
y not u post it in swing ya?.
you can add scrollpane by
JScrollPane jsp=new JScrollPane(new JTextArea(20,20));
yourpanel.add(jsp);
if u still have problem post. u r welcome.
i did not run the below changed code u may try it.it is so simple.....
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
public class Interface extends Frame
     String path;
     JTextField text = new JTextField();
     JButton button = new JButton("Browse");
     JButton executeButton = new JButton("Execute");
     JTextArea area = new JTextArea();
JScrollPane jsp=new JScrollPane(area);
     JPanel P1 = new JPanel();
public Component createComponents()
     text.setBounds(30,30,300,20);
     button.setBounds(30,70,80,20);
     executeButton.setBounds(130,70,80,20);
     jsp.setBounds(30,110,540,430);
     P1.setBackground(Color.red);
     P1.setLayout(null);
     P1.add(button);
     P1.add(executeButton);
     P1.add(text);
     P1.add(jsp);
     return P1;
     public static void main(String[] args)
     JFrame frame = new JFrame("Pseudocode Interpreter");
     Interface app = new Interface();
     Component contents = app.createComponents();
     frame.getContentPane().add(contents);
     frame.setSize(600,600);
     frame.setVisible(true);
     frame.setLocation(50,50);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

Similar Messages

  • Problem in scrolling a JTextArea

    hi,
    I am using a JTextArea to display files. I could scroll smoothly without interruptions when I tested with a 1 kb file. But when I loaded a 300 kb file, the scrolling beacame halted and slow. It was not continuous. Can this be fixed?
    Also I am thinking of displaying files of larger sizes( 1Mb- 5 Mb). In such cases, I thought it would be better to display only parts of the document as i scroll. Could someone please help me with this?
    Thanks,
    ramya

    Hello,
    I hope you would be able to recall my problem - smooth scrolling of loads of text.(Please see my problem -right at the top, as the first post)
    I worked out a way to display only the required text as i scroll. I could not go in for a scrollpane because I would need to deal with MBs of textual data. :(
    Now, I am trying to perform a word search on the text displayed. I do not know how to do this.
    Please help with your suggestions and pointers.
    I have posted the code below.
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.text.*;
    import java.awt.event.*;
    import javax.swing.border.*;
    import javax.swing.text.*;
    public class paint_frame extends JFrame implements AdjustmentListener
    JTextArea text; PlainDocument doc = new PlainDocument();Font f;FontMetrics fm; int ivisible,ivalue;JScrollBar hscroll;
    JViewport view; int width;  columnpanel cp; JScrollBar vscroll;
    paintpanel pp; int ivisible_v; int ivalue_v; VPanel vp; JPanel mp;
    JPanel mmp=new JPanel(new BorderLayout());
        public static void main(String[] args)
            paint_frame pf = new paint_frame();
            pf.setSize(new Dimension(900,900));
            pf.pack();
            pf.setVisible(true);
            pf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        public paint_frame()
           try
           doc.insertString(doc.getLength(),"123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890",null);
           doc.insertString(doc.getLength(),"\n",null);
           doc.insertString(doc.getLength(),"67890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234*",null);
           doc.insertString(doc.getLength(),"\n",null);
           doc.insertString(doc.getLength(),"89012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456*",null);
           doc.insertString(doc.getLength(),"\n",null);
           doc.insertString(doc.getLength(),"12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789*",null);
           doc.insertString(doc.getLength(),"\n",null);
           doc.insertString(doc.getLength(),"12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789*",null);
           doc.insertString(doc.getLength(),"\n",null);
           doc.insertString(doc.getLength(),"12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789*",null);
           doc.insertString(doc.getLength(),"\n",null);
           doc.insertString(doc.getLength(),"12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789*",null);
           doc.insertString(doc.getLength(),"\n",null);
           doc.insertString(doc.getLength(),"12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789*",null);
           doc.insertString(doc.getLength(),"\n",null);
           doc.insertString(doc.getLength(),"12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789*",null);
           doc.insertString(doc.getLength(),"\n",null);
           doc.insertString(doc.getLength(),"02345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789*",null);
           doc.insertString(doc.getLength(),"\n",null);
           doc.insertString(doc.getLength(),"12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789*",null);
            doc.insertString(doc.getLength(),"\n",null);
            doc.insertString(doc.getLength(),"67890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234*",null);
            doc.insertString(doc.getLength(),"\n",null);
            doc.insertString(doc.getLength(),"89012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456*",null);
            doc.insertString(doc.getLength(),"\n",null);
            doc.insertString(doc.getLength(),"12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789*",null);
            doc.insertString(doc.getLength(),"\n",null);
            doc.insertString(doc.getLength(),"12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789*",null);
            doc.insertString(doc.getLength(),"\n",null);
            doc.insertString(doc.getLength(),"12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789*",null);
            doc.insertString(doc.getLength(),"\n",null);
            doc.insertString(doc.getLength(),"12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789*",null);
            doc.insertString(doc.getLength(),"\n",null);
            doc.insertString(doc.getLength(),"12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789*",null);
            doc.insertString(doc.getLength(),"\n",null);
            doc.insertString(doc.getLength(),"12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789*",null);
            doc.insertString(doc.getLength(),"\n",null);
            doc.insertString(doc.getLength(),"00345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789*",null);
           }catch(Exception e){}
            hscroll = new JScrollBar(JScrollBar.HORIZONTAL,0,0,0,0); // set the max value to be the length of the longest seq. in the alignment.
            vscroll = new JScrollBar(JScrollBar.VERTICAL,0,0,0,0);
            pp = new paintpanel();
            view = new JViewport();
            view.setPreferredSize(new Dimension(600,600));
            view.setMaximumSize(new Dimension(600,600));
             vp = new VPanel();
             text = new JTextArea(); view.setView(text);
                      f = new Font("Monospaced",Font.PLAIN,20);
            text.setFont(f);fm = text.getFontMetrics(f); //text.setEditable(false);
           mp = new JPanel(new BorderLayout());
           cp = new columnpanel();
           hscroll.addAdjustmentListener(this);
           vscroll.addAdjustmentListener(this);
           pp.add(view,BorderLayout.CENTER);
           pp.add(hscroll,BorderLayout.SOUTH);
           pp.add(cp, BorderLayout.NORTH);
           view.setView(text);
           JMenuBar bar = new JMenuBar();
           JMenu format = new JMenu("format");
           JMenuItem font = new JMenuItem("font");
           JMenu search = new JMenu("search");
           JMenuItem find = new JMenuItem("find");
           font.addActionListener(new ActionListener()
              public void actionPerformed(ActionEvent e)
                 f = new Font("Monospaced",Font.PLAIN,18);
                 text.setFont(f);
                 fm=text.getFontMetrics(f);
                 //paintframe3.this.revalidate();
                 paint_frame.this.repaint();      // causes the panel to be repainted
           format.add(font);
           bar.add(format);
           mp.add(pp,BorderLayout.CENTER);
           mp.add(vp,BorderLayout.EAST);
          mmp.add(mp,BorderLayout.CENTER);
          //mmp.add(headerview,BorderLayout.WEST);
           getContentPane().add(mmp,BorderLayout.CENTER);
           setJMenuBar(bar);
           System.out.println("\n jpanel added");
        public void adjustmentValueChanged(AdjustmentEvent ae)
        try
           paint_frame.this.repaint();
        }catch(Exception e){}
    class columnpanel extends JPanel
        int alignment_width;
        int window_width;
        int hvalue;int j;String s=""; int v1,v;
      columnpanel()
         setOpaque(true);
         setPreferredSize(new Dimension(view.getSize().width,50));
      public void doLayout()
      public void paintComponent(Graphics g)
         window_width = width;
         g.setColor(Color.white);
         System.out.println(" COLUMN PANEL COLUMN PANEL/*//*" + getSize());System.out.println(" preferred column panel" + getPreferredSize());
         g.fillRect(0,0,getSize().width,getSize().height);
         g.setColor(Color.black);
         g.setFont(f);
          j = fm.charWidth('M');
          v = hscroll.getValue()/fm.charWidth('M');
    for(int i=1;i<=15;i=i+1)
              if(v==0)
                     s=new Integer((i)*10).toString();
                //g.drawString("|", i*j*10-(j+j*v),0+10);
               g.drawString(s, i*j*10-(j+j*v),40);
           else
           if(v!=0)
                s=new Integer((i)*10).toString();
                //g.drawString("|", i*j*10-(j+j*v)+view.getSize().width%j,0+10);
                           g.drawString(s, i*j*10-(j+j*v)+view.getSize().width%j,40);
    }// end of column panel class
    class paintpanel extends JPanel
        paintpanel()
            setSize(new Dimension(800,800));
            setLayout(new BorderLayout());
        public void paintComponent(Graphics g)
            try
              int testwidth = view.getSize().width/fm.charWidth('M');
              int testheight = view.getSize().height/fm.getHeight();
              hscroll.setMaximum(150*fm.charWidth('M'));
              vscroll.setMaximum(30*fm.getHeight());
              hscroll.setVisibleAmount(testwidth*fm.charWidth('M'));
              vscroll.setVisibleAmount(testheight*fm.getHeight());
              hscroll.setUnitIncrement(fm.charWidth('M'));
              vscroll.setUnitIncrement(fm.getHeight());
             hscroll.setBlockIncrement(testwidth*fm.charWidth('M'));
              //hvisibleamount = hscroll.getVisibleAmount();
                text.setText("");
                         text.setText(doc.getText(0,testwidth+(hscroll.getValue()/fm.charWidth('M'))));
                         text.append("\n");
                    text.append(doc.getText((151),testwidth+(hscroll.getValue()/fm.charWidth('M'))));
              text.append("\n");
                text.append(doc.getText(302,testwidth+(hscroll.getValue()/fm.charWidth('M'))));
              text.append("\n");
               text.append(doc.getText(453,testwidth+(hscroll.getValue()/fm.charWidth('M'))));
              text.append("\n");
              text.append(doc.getText(604,testwidth+(hscroll.getValue()/fm.charWidth('M'))));
              text.append("\n");
              text.append(doc.getText(755,testwidth+(hscroll.getValue()/fm.charWidth('M'))));
              text.append("\n");
              text.append(doc.getText(906,testwidth+(hscroll.getValue()/fm.charWidth('M'))));
              text.append("\n");
              text.append(doc.getText(1057,testwidth+(hscroll.getValue()/fm.charWidth('M'))));
              text.append("\n");
              text.append(doc.getText(1208,testwidth+(hscroll.getValue()/fm.charWidth('M'))));
              text.append("\n");
              text.append(doc.getText(1359,testwidth+(hscroll.getValue()/fm.charWidth('M'))));
              text.append("\n");
              text.append(doc.getText(1510,testwidth+(hscroll.getValue()/fm.charWidth('M'))));
              text.append("\n");
              text.append(doc.getText(1661,testwidth+(hscroll.getValue()/fm.charWidth('M'))));
              text.append("\n");
              text.append(doc.getText(1812,testwidth+(hscroll.getValue()/fm.charWidth('M'))));
              text.append("\n");
              text.append(doc.getText(1963,testwidth+(hscroll.getValue()/fm.charWidth('M'))));
              text.append("\n");
              text.append(doc.getText(2114,testwidth+(hscroll.getValue()/fm.charWidth('M'))));
              text.append("\n");
              text.append(doc.getText(2265,testwidth+(hscroll.getValue()/fm.charWidth('M'))));
              text.append("\n");
              text.append(doc.getText(2416,testwidth+(hscroll.getValue()/fm.charWidth('M'))));
              text.append("\n");
              text.append(doc.getText(2567,testwidth+(hscroll.getValue()/fm.charWidth('M'))));
              text.append("\n");
              text.append(doc.getText(2718,testwidth+(hscroll.getValue()/fm.charWidth('M'))));
              text.append("\n");
              text.append(doc.getText(2869,testwidth+(hscroll.getValue()/fm.charWidth('M'))));
              /*text.append("\n");
              text.append(doc.getText(3020,ivalue+ivisible+hscroll.getValue()));
                          text.append("\n");
                          text.append(doc.getText(3171,ivalue+ivisible+hscroll.getValue()));
                          text.append("\n");
                          text.append(doc.getText(3322,ivalue+ivisible+hscroll.getValue()));
                          text.append("\n");
                          text.append(doc.getText(3473,ivalue+ivisible+hscroll.getValue()));
                          text.append("\n");
                          text.append(doc.getText(3624,ivalue+ivisible+hscroll.getValue()));
                          text.append("\n");
                          text.append(doc.getText(3775,ivalue+ivisible+hscroll.getValue()));
                          text.append("\n");
                          text.append(doc.getText(3926,ivalue+ivisible+hscroll.getValue()));
                          text.append("\n");
                          text.append(doc.getText(4077,ivalue+ivisible+hscroll.getValue()));
                          text.append("\n");
                          text.append(doc.getText(4228,ivalue+ivisible+hscroll.getValue()));
                          text.append("\n");
                          text.append(doc.getText(1379,ivalue+ivisible+hscroll.getValue()));*/
            }catch(Exception e){}
    }// end of paint panel class
    class VPanel extends JPanel
         VPanel()
              //setLayout(null);
              setSize(new Dimension(17,pp.getSize().height));
              setBackground(Color.white);
              add(vscroll);
    public void doLayout()
         vscroll.setBounds(0,view.getBounds().y,getSize().width,view.getSize().height);
         //vscroll.setPreferredSize(new Dimension(getSize().width,view.getSize().height));
    public void paintComponent(Graphics g)
         super.paintComponent(g);
              System.out.println("\n vertical panel size" + getSize());
    } // end of VPanel class
    }// end of piant_frame classThank you very much for the time,
    ramya

  • Horizontal Scrolling in JTextArea???

    Hi,
    I have disabled horizontal scrolling in a textarea with this command,
    scrollpane1 = new JScrollPane(ta,ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    where ta is my textarea.
    But whenever i continue typing the text continues in the same line even if the end of the textarea is reached and does not automatically go to the second line. How do i make it continue to the next line as soon as the width of the textarea is reached. Please help.

    This is called wrapping. Check out the JTextArea API:
    setLineWrap(boolean wrap)
    setWrapStyleWord(boolean word)

  • Scroll In JTextArea

    When I add text to textarea the scroll not work to show me the new line that
    have been added.
    I think that will happend by use
    setAutoscrolls(boolean autoscrolls) method
    that is not right
    tell me how I can do that....
    thanks.

    make sure you add the text area to a scroll pane
    ie:
    myScrollPane.add(myTextArea);

  • HELP!!! JTextArea keeps resizing to the size of the frame i have it on!!!1

    I have a Frame that has a panel with a JTextArea in it, but when the text area is displayed (regardless of what size i declare it ) it resizes itself to the size of the frame .. Anbody that can telkl me why it does this, thanks in advance ; )

    okay, i'm back from lunch. maybe this will give you some ideas. i added borders so you could see the outline of the scroll pane as opposed to the top panel which i'm thinking should be called left panel since you have it to the west. it's not meant to represent the best design, only to demonstrate some thoughts.
    import javax.swing.*;
    import java.awt.BorderLayout;
    import java.awt.event.*;
    public class MyFrame extends javax.swing.JFrame {
       private JPanel panel;
       private JScrollPane scroll;
       private JTextArea area;
       /** Creates a new instance of MyFrame */
       public MyFrame() {
          init();
       private void init(){
          setTitle("My Frame");
          panel = new JPanel();
          panel.setBorder(BorderFactory.createTitledBorder("my panel"));
          area = new JTextArea();
          area.setLineWrap(true);
          area.setWrapStyleWord(true);
          area.setRows(15);
          scroll = new JScrollPane(area);
          scroll.setBorder(BorderFactory.createTitledBorder("my scroll"));
          panel.add(scroll);
          getContentPane().add(panel,BorderLayout.WEST);
          setSize(400, 400);
          setLocationRelativeTo(null);
          addWindowListener(new WindowAdapter(){
             public void windowClosing(WindowEvent we) {
                System.exit(0);
          String tmp = "here is some text to test an area";
          for(int i=0;i<50;i++)
             area.append(tmp);
       public static void main(String[] args) {
          new MyFrame().setVisible(true);
    }

  • Saving a JTextArea string to a file

    Hello there, well i have a little problem that i can not figure out. i am creating a swing application that is a text editor. i am new at this so i am reading the api, books etc.. but can not seem to make the application to save. i have followed the format and done it several ways and still i can not make it work. i did notice something that when i initalize the variable JTextArea textArea in the beginning instead of the method initComponent, and by making it static i can write it once, and then open it up and read it. but it mess the application when you save, freezing the window. i am going to attach my code so that you can see what i am doing, please answer as soon as possible i really want this problem to work by now.
    import java.io.*;
    import javax.swing.*;
    public class InternalPanel extends JInternalFrame{
         private static String title = "Untitled ";
         private int width = 400;
         private int height = 300;
         private int x = 15;
         private int y = 15;
         private boolean stateT = true;
         private boolean stateF = false;
         private JScrollPane scroller;
         private JTextArea textArea;
         private static int count;
         public InternalPanel(){
              super(title + (count));               
              initComponent();
         public InternalPanel(File file){
              readerComponent(file);
         private void initComponent(){
              textArea = new JTextArea();
              scroller = new JScrollPane();
              scroller.setViewportView(textArea);
              getContentPane().add(scroller);
              setIconifiable(stateT);
              setMaximizable(stateT);
              setClosable(stateT);
              setResizable(stateT);     
              setSize(width, height);
              setLocation((x * count), (y * count));
              show();
              ++count;
         private void readerComponent(File file){
              initComponent();
              fileReader(file);
         private void fileReader(File file){
              int symblo;
              try{
                   FileReader reader = new FileReader(file);
                   while((symblo = reader.read()) != -1){
                        textArea.read(reader, this);
                        setTitle(file.getName());
                   reader.close();
              }catch(IOException e){
                   System.out.println(e);
         public void fileWriter(File file){     
              String context = textArea.getText();
              System.out.println(context);
              try{               
                   FileWriter writer = new FileWriter(file);
                   writer.write(context);
                   writer.flush();
                   writer.close();
              }catch(IOException e){
                   System.out.println(e);
    }

    Hello there, well i have a little problem that i can not figure out. i am creating a swing application that is a text editor. i am new at this so i am reading the api, books etc.. but can not seem to make the application to save. i have followed the format and done it several ways and still i can not make it work. i did notice something that when i initalize the variable JTextArea textArea in the beginning instead of the method initComponent, and by making it static i can write it once, and then open it up and read it. but it mess the application when you save, freezing the window. i am going to attach my code so that you can see what i am doing, please answer as soon as possible i really want this problem to work by now.
    import java.io.*;
    import javax.swing.*;
    public class InternalPanel extends JInternalFrame{
         private static String title = "Untitled ";
         private int width = 400;
         private int height = 300;
         private int x = 15;
         private int y = 15;
         private boolean stateT = true;
         private boolean stateF = false;
         private JScrollPane scroller;
         private JTextArea textArea;
         private static int count;
         public InternalPanel(){
              super(title + (count));               
              initComponent();
         public InternalPanel(File file){
              readerComponent(file);
         private void initComponent(){
              textArea = new JTextArea();
              scroller = new JScrollPane();
              scroller.setViewportView(textArea);
              getContentPane().add(scroller);
              setIconifiable(stateT);
              setMaximizable(stateT);
              setClosable(stateT);
              setResizable(stateT);     
              setSize(width, height);
              setLocation((x * count), (y * count));
              show();
              ++count;
         private void readerComponent(File file){
              initComponent();
              fileReader(file);
         private void fileReader(File file){
              int symblo;
              try{
                   FileReader reader = new FileReader(file);
                   while((symblo = reader.read()) != -1){
                        textArea.read(reader, this);
                        setTitle(file.getName());
                   reader.close();
              }catch(IOException e){
                   System.out.println(e);
         public void fileWriter(File file){     
              String context = textArea.getText();
              System.out.println(context);
              try{               
                   FileWriter writer = new FileWriter(file);
                   writer.write(context);
                   writer.flush();
                   writer.close();
              }catch(IOException e){
                   System.out.println(e);
    }

  • Install Application - TextArea inside JScrollPane

    I've been working on an install application to install another one of my programs (next/accept/next/ finish type of thing) and had a couple questions and would appreciate any help anyone can give.
    Some Background info:
    I made images and have them display as image icons through jlabels for the buttons and background. The labels have classes applying various mouselisteners (Mousepressed, MouseEntered, MouseExited, etc) changing the images and moving from screen to screen. I have my layout set to null, not for any particular reason, but because I have no formal education in layout managers.
    1) Is there a conical solution to moving through various windows? That is, right now I move through the various 'screens' with a check on an int called state, that gets incremented and decremented through forward and back buttons. I looked at some code given to us on a test by our teacher (we had to find bugs) and saw that he had implemented a fake "state" interface, with constants like "Account_State" to control where you were in the program. This seems a bit easier to read than ints, but is there a correct built in version of his states?
    2) On the second screen I have a license agreement (actually required for the application that gets installed), and a checkbox. The license is held inside of a JTextArea(scroll) inside a JScrollPane(textscroll). The JScrollPane is extending in weird ways. The following is a stripped down version of my code (it runs and demonstrates the problem):
    InstalleApp
    import javax.swing.*;
    import java.awt.*;
    public class InstalleApp {
        public static void main(String args[]) {
            InstalleFrame m = new InstalleFrame();
               Container content = m.getContentPane();
            m.setDefaultCloseOperation(3);
            m.setSize(550, 400);
            m.setUndecorated(true);
            m.setVisible(true);
            m.setTitle("Install");
    }InstalleFrame
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.JFrame;
    import java.awt.event.*;
    import java.awt.Rectangle;
    import java.awt.Font;
    import java.awt.BorderLayout;
    import java.util.*;
    import javax.swing.event.DocumentEvent;
    import javax.swing.event.DocumentListener;
    import java.awt.event.ActionEvent;
    import javax.swing.text.BadLocationException;
    import javax.swing.JSlider;
    import java.awt.Dimension;
    public class InstalleFrame
        extends JFrame implements ActionListener {
      public InstalleFrame() {
        try {
          jbInit();
        catch (Exception ex) {
          ex.printStackTrace();
      public void actionPerformed(ActionEvent e) {
      JScrollPane textscroll;
      private void jbInit() throws Exception {
        this.getContentPane().setLayout(null);
        this.getContentPane().setBackground(UIManager.getColor("window"));
        background.setBounds(new Rectangle(0, 0, 550, 400));
        readcheck.setOpaque(false);
        readcheck.setText("I have read and accept the license agreement");
        readcheck.setBounds(new Rectangle(31, 357, 319, 32));
        scroll.setWrapStyleWord(true);
        scroll.setLineWrap(true);
        scroll.setText(
            "Copyright ? 2006-2007 GonZor228.com \n\nBy using or distributing this " +
            "software (or any work based on the software) you shall be deemed " +
            "to have accepted the terms and conditions set out below.\n\nGonZor228.com " +
            "(\"GonZor\") is making this software freely available on the basis " +
            "that it is accepted as found and that the user checks its fitness " +
            "for purpose prior to use.\n\nThis software is provided \'as-is\', without " +
            "any express or implied warranties whatsoever. In no event will the " +
            "authors, partners or contributors be held liable for any damages, " +
            "claims or other liabilities direct or indirect, arising from the " +
            "use of this software.\n\nGonZor will from time to time make software " +
            "updates available.  However, GonZor accepts no obligation to provide " +
            "any support to free license holders.\n\nGonZor grants you a limited " +
            "non-exclusive license to use this software for any purpose that does " +
            "not violate any laws that apply to your person in your current jurisdiction, " +
            "subject to the following restrictions: \n\n1. The origin of this software " +
            "must not be misrepresented; you must not claim that you wrote the " +
            "original software.\n2. You must not alter the software, user license " +
            "or installer in any way unless given permission to do so.\n3. This " +
            "notice may not be removed or altered from any distribution.\n4. You " +
            "may not resell or charge for the software.\n5. You may not reverse " +
            "engineer, decompile, disassemble, derive the source code of or modify " +
            "[or create derivative work from] the program without the express " +
            "permission of GonZor.\n6. You must not use this software to engage " +
            "in or allow others to engage in any illegal activity.\n7. You may " +
            "not claim any sponsorship by, endorsement by, or affiliation with " +
            "GonZor228.com\n8. You acknowledge that GonZor owns the copyright and " +
            "all associated intellectual property rights relating to the software.\n\n" +
            " This software license is governed by and construed in accordance " +
            "with the laws of Australia and you agree to submit to the exclusive " +
            "jurisdiction of the Australian courts.\n\nBy clicking the \"I agree\" " +
            "button below, you agree to these software license terms. If you disagree " +
            "with any of the terms below, GonZor does not grant you a license " +
            "to use the software ? exit the window.\n\nYou agree that by your installation " +
            "of the GonZor?s software, you acknowledge that you are at least 18 " +
            "years old, have read this software license, understand it, and agree " +
            "to be bound by its terms.\n\nGonZor reserves the right to update and " +
            "change, from time to time, this software license and all documents " +
            "incorporated by reference. You can always find the most recent version " +
            "of this software license at GonZor228.com.  GonZor may change this " +
            "software license by posting a new version without notice to you. " +
            "Use of the GonZor?s software after such change constitutes acceptance " +
            "of such changes.\n\n1.\tOwnership and Relationship of Parties.\n\nThe " +
            "software is protected by copyrights, trademarks, service marks, international " +
            "treaties, and/or other proprietary rights and laws of the U.S. and " +
            "other countries. You agree to abide by all applicable proprietary " +
            "rights laws and other laws, as well as any additional copyright notices " +
            "or restrictions contained in this software license. GonZor owns all " +
            "rights, titles, and interests in and to the applicable contributions " +
            "to the software. This software license grants you no right, title, " +
            "or interest in any intellectual property owned or licensed by GonZor, " +
            "including (but not limited to) the software, and creates no relationship " +
            "between yourself and GonZor other than that of GonZor to licensee.\n\n" +
            "The software and its components contain software licensed from " +
            "GonZor. The licensor software enables the software to perform certain " +
            "functions including, without limitation, access proprietary data " +
            "on third-party data servers as well as GonZor?s own server. You agree " +
            "that you will use the software, and any data accessed through the " +
            "software, for your own personal non-commercial use only. You agree " +
            "not to assign, copy, transfer, or transmit the software, or any data " +
            "obtained through the software, to any third party. Your license to " +
            "use the software, its components, and any third-party data, will " +
            "terminate if you violate these restrictions. If your license terminates, " +
            "you agree to cease any and all use of the software, its components, " +
            "and any third-party data. All rights in any third-party data, any " +
            "third-party software, and any third-party data servers, including " +
            "all ownership rights are reserved and remain with the respective " +
            "third parties. You agree that these third parties may enforce their " +
            "rights under this Agreement against you directly in their own name.\n\n" +
            "2.\tSupport and Software Updates.\n\nGonZor may elect to provide " +
            "you with customer support and/or software upgrades, enhancements, " +
            "or modifications for the software (collectively, \"Support\"), in its " +
            "sole discretion, and may terminate such Support at any time without " +
            "notice to you. GonZor may change, suspend, or discontinue any aspect " +
            "of the software at any time, including the availability of any software " +
            "feature, database, or content. GonZor may also impose limits on certain " +
            "features and services or restrict your access to parts or all of " +
            "the software or the GonZor228.com web site without notice or liability.\n\n" +
            "3.  \tFees and Payments.\n\nGonZor reserves the right to charge fees " +
            "for future use of or access to the software in GonZor?s sole discretion. " +
            "If GonZor decides to charge for the software, such charges will be " +
            "disclosed to you 28 days before they are applied if such fees will " +
            "affect your use of the product.\n\n4.\tDisclaimer of Warranties by " +
            "GonZor.\n\nUse of the software and any data accessed through the software " +
            "is at your sole risk. They are provided \"as is.\"  Any material or " +
            "service downloaded or otherwise obtained through the use of the software " +
            "(such as the \"plug-in\" feature) is done at your own discretion and " +
            "risk, and you will be solely responsible for any damage to your computer " +
            "system or loss of data that results from the download and/or use " +
            "of any such material or service.  GonZor, its officers, directors, " +
            "employees, contractors, agents, affiliates, assigns, and GonZor?s " +
            "licensors (collectively ?Associates?) do not represent that the software " +
            "or any data accessed there from is appropriate or available for use " +
            "outside the Australia.\n\nThe Associates expressly disclaim all warranties " +
            "of any kind, whether express or implied, relating to the software " +
            "and any data accessed there from, or the accuracy, timeliness, completeness, " +
            "or adequacy of the software and any data accessed there from, including " +
            "the implied warranties of title, merchantability, satisfactory quality, " +
            "fitness for a particular purpose, and non-infringement.\n\nIf the " +
            "software or any data accessed there from proves defective, you (and " +
            "not the Associates) assume the entire cost of all repairs or injury " +
            "of any kind, even if the Associates have been advised of the possibility " +
            "of such a defect or damages. Some jurisdictions do not allow restrictions " +
            "on implied warranties so some of these limitations may not apply " +
            "to you.\n\n5. \tLimitation of liability.\n\nThe Associates will not " +
            "be liable to you for claims and liabilities of any kind arising out " +
            "of or in any way related to the use of the software by yourself or " +
            "by third parties, to the use or non-use of any brokerage firm or " +
            "dealer, or to the sale or purchase of any security, whether such " +
            "claims and liabilities are based on any legal or equitable theory." +
            "\n\nThe Associates are not liable to you for any and all direct, incidental, " +
            "special, indirect, or consequential damages arising out of or related " +
            "to any third-party software, any data accessed through the software, " +
            "your use or inability to use or access the software, or any data " +
            "provided through the software, whether such damage claims are brought " +
            "under any theory of law or equity. Damages excluded by this clause " +
            "include, without limitation, those for loss of business profits, " +
            "injury to person or property, business interruption, loss of business " +
            "or personal information. Some jurisdictions do not allow limitation " +
            "of incidental or consequential damages so this restriction may not " +
            "apply to you.\n\nInformation provided through the software may be " +
            "delayed, inaccurate, or contain errors or omissions, and the Associates " +
            "will have no liability with respect thereto. GonZor may change or " +
            "discontinue any aspect or feature of the software or the use of all " +
            "or any features or technology in the software at any time without " +
            "prior notice to you, including, but not limited to, content, hours " +
            "of availability.\n\n6.  \tControlling Law.\n\nThis software license " +
            "and the relationship between you and GonZor is governed by the laws " +
            "of Australia without regard to its conflict of law provisions. You " +
            "and GonZor agree to submit to the personal and exclusive jurisdiction " +
            "of the courts located within Australia. The United Nations Convention " +
            "on the International Sale of Goods does not apply to this software " +
            "license.\n\n7.\tPrecedence.\n\nThis software license constitutes the " +
            "entire understanding between the parties respecting use of the software, " +
            "superseding all prior agreements between you and GonZor.\n\n8.\tSurviving " +
            "Provisions.\n\nSections 1, and 3 through 5, will survive any termination " +
            "of this Agreement.\n\n---------------------------------------------------------------------------------" +
            "---\nIf you accept the terms of the agreements, click I Agree to continue. " +
            " You must accept the agreement to download and use the software. ");
        scroll.setBounds(new Rectangle(36, 36, 478, 305));
        this.getContentPane().add(readcheck);
        readcheck.setVisible(false);
       this.getContentPane().add(scroll);
       textscroll = new JScrollPane (scroll, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                                                JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        textscroll.setBounds(36,36,400,400);
          getContentPane().add( textscroll );
        this.getContentPane().add(background);
      JLabel background = new JLabel();
      JCheckBox readcheck = new JCheckBox();
      JTextArea scroll = new JTextArea();
    }Sorry about all the text for the agreement. I've tried a number of different things I got from searching the forums at different points in the code (setting the number of rows/columns, setting max and min sizes, etc etc) The code above that wraps the text I could have sworn I tried 3 times before it magically worked... I also tried using the awt component for textareas that had the scrollbars built in, but scrapped it after having even more difficulties with that one. I'm trying to get the textbox to only go down about 300 px and 300 px to the right. Using the graphical editor to change it produces a null pointer error at compile time(?!?). Can anyone help me to get the textbox to render as I want it to?
    Edited by: rpk5000 on Jan 27, 2008 9:43 AM

    for instance, boxlayout would work nicely with the installer frame (or dialog)
    import java.awt.Dimension;
    import java.awt.EventQueue;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.BorderFactory;
    import javax.swing.BoxLayout;
    import javax.swing.JButton;
    import javax.swing.JCheckBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.SwingUtilities;
    import javax.swing.UIManager;
    public class InstalleFrame
        public InstalleFrame()
            try
                jbInit();
            catch (Exception ex)
                ex.printStackTrace();
        private JScrollPane textscroll;
        private JPanel contentPane = new JPanel();
        private JLabel background = new JLabel();
        private JCheckBox readcheck = new JCheckBox();
        private JTextArea scroll = new JTextArea();
        private void jbInit() throws Exception
            contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.PAGE_AXIS));
            contentPane.setBackground(UIManager.getColor("window"));
            contentPane.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
            scroll.setWrapStyleWord(true);
            scroll.setLineWrap(true);
            String text = "Copyright ? 2006-2007 GonZor228.com \n\nBy using or distributing this "
                            + "software (or any work based on the software) you shall be deemed "
                            + "to have accepted the terms and conditions set out below.\n\nGonZor228.com "
                            + "(\"GonZor\") is making this software freely available on the basis "
                            + "that it is accepted as found and that the user checks its fitness "
                            + "for purpose prior to use.\n\nThis software is provided \'as-is\', without "
                            + "any express or implied warranties whatsoever. In no event will the "
                            + "authors, partners or contributors be held liable for any damages, "
                            + "claims or other liabilities direct or indirect, arising from the "
                            + "use of this software.\n\nGonZor will from time to time make software "
                            + "updates available.  However, GonZor accepts no obligation to provide "
                            + "any support to free license holders.\n\nGonZor grants you a limited "
                            + "non-exclusive license to use this software for any purpose that does "
                            + "not violate any laws that apply to your person in your current jurisdiction, "
                            + "subject to the following restrictions: \n\n\nblah, blah, blah,..."
                            + "\n\n";
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < 5; i++)
                sb.append(text);
            scroll.setText(sb.toString());
            contentPane.add(readcheck);
            contentPane.add(scroll);
            textscroll = new JScrollPane(scroll,
                    JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                    JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
            textscroll.setPreferredSize(new Dimension(400, 400));
            contentPane.add(textscroll);
            JPanel bottomPane = new JPanel();
            bottomPane.setOpaque(false);
            final JButton okButton = new JButton("OK");
            final JButton cancelButton = new JButton("Cancel");
            okButton.setEnabled(false);
            readcheck.setOpaque(false);
            readcheck.setText("I have read and accept the license agreement");
            readcheck.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    JCheckBox radioBtn = (JCheckBox)e.getSource();
                    if (radioBtn.isSelected())
                        okButton.setEnabled(true);                   
                    else
                        okButton.setEnabled(false);
            okButton.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    // TODO: whatever needs to be done here
            cancelButton.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    SwingUtilities.getWindowAncestor(contentPane).dispose();
            bottomPane.add(readcheck);
            bottomPane.add(okButton);
            bottomPane.add(cancelButton);
            contentPane.add(bottomPane);
            //readcheck.setVisible(false);
            contentPane.add(background);
        public JPanel getContentPane()
            return contentPane;
        public static void main(String[] args)
            EventQueue.invokeLater(new Runnable()
                public void run()
                    InstalleFrame install = new InstalleFrame();
                    JFrame frame = new JFrame("Install");
                    frame.getContentPane().add(install.getContentPane());
                    frame.setDefaultCloseOperation(3);
                    frame.setSize(550, 400);
                    frame.setUndecorated(false);  //**
                    frame.pack();  //**
                    frame.setLocationRelativeTo(null); //**
                    frame.setVisible(true);
    }

  • JOptionPane repeating?

    I have a JOptionPane that promts a user for a selection from an array. The problem is that when the user selects one, the JOptionPane pops up again for another choice. How can I get it to only come up once.
    Here is my code, thanks
    import java.sql.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import Sequencer.*;
    public class DisplayQueryResults extends JFrame {
    // java.sql types needed for database processing
    private Connection connection;
    private Statement statement;
    private ResultSet resultSet;
    private ResultSetMetaData rsMetaData;
    // javax.swing types needed for GUI
    private JTable table;
    private JScrollPane scroller;
    private JTextArea inputQuery;
    private JButton submitQuery;
    private String query;
    public DisplayQueryResults()
    super( "Enter Query. Click Submit to See Results." );
    // Load the driver to allow connection to the database
         try {
         dbConnection conn = new dbConnection();
         connection = conn.dbConnect("135.86.216.201","test","prod","");
                        getTable();
         } catch ( Exception e) {
         System.out.println("Error detected :"+e);
    // If connected to database, set up GUI
    inputQuery =
    new JTextArea( "SELECT * FROM testresult", 4, 30 );
    submitQuery = new JButton( "Submit query" );
    submitQuery.addActionListener(
    new ActionListener() {
    public void actionPerformed( ActionEvent e )
    //getTable();
    JPanel topPanel = new JPanel();
    topPanel.setLayout( new BorderLayout() );
    topPanel.add( new JScrollPane( inputQuery),
    BorderLayout.CENTER );
    topPanel.add( submitQuery, BorderLayout.SOUTH );
    table = new JTable( 4, 4 );
    Container c = getContentPane();
    c.setLayout( new BorderLayout() );
    c.add( topPanel, BorderLayout.NORTH );
    c.add( table, BorderLayout.CENTER );
    getTable();
    setSize( 500, 500 );
    show();
    private void getTable()
    try {
    //String query = "select site,testStage,testName,testDate,testerName,slot,cardSerial,cardType,cardRev,result,failureInfo,failureCode,failureSubCode from testresult";
              //String query = "select * from testresult";
              String queries[] = {"View all available data","View Board history","View Yield"};
              Object selquery = JOptionPane.showInputDialog(null,"Please choose a Query...","Query Selection",JOptionPane.QUESTION_MESSAGE,
                                       null, queries, queries[0]);
              if (selquery.toString().equals(queries[1])){
                   String sn = JOptionPane.showInputDialog("Please enter board serial number...");
                   query = "select site,testStage,testName,testDate,testerName,slot,cardSerial,cardType,cardRev,result,failureInfo,failureCode,failureSubCode from testresult where cardSerial = '"+sn.trim()+"'";
              }else if (selquery.toString().equals(queries[0])){
                   query = "select * from testresult";
              }else if (selquery.toString().equals(queries[2])){
                   //query = "                                   ";
              }else{}
    statement = connection.createStatement();
    resultSet = statement.executeQuery( query );
    displayResultSet( resultSet );
    catch ( SQLException sqlex ) {
    sqlex.printStackTrace();
    private void displayResultSet( ResultSet rs )
    throws SQLException
    // position to first record
    boolean moreRecords = rs.next();
    // If there are no records, display a message
    if ( ! moreRecords ) {
    JOptionPane.showMessageDialog( this,
    "ResultSet contained no records" );
    setTitle( "No records to display" );
    return;
    Vector columnHeads = new Vector();
    Vector rows = new Vector();
    try {
    // get column heads
    ResultSetMetaData rsmd = rs.getMetaData();
    for ( int i = 1; i <= rsmd.getColumnCount(); ++i )
    columnHeads.addElement( rsmd.getColumnName( i ) );
    // get row data
    do {
    rows.addElement( getNextRow( rs, rsmd ) );
    } while ( rs.next() );
    // display table with ResultSet contents
    table = new JTable( rows, columnHeads );
    scroller = new JScrollPane( table );
    Container c = getContentPane();
    c.remove( 1 );
    c.add( scroller, BorderLayout.CENTER );
    c.validate();
    catch ( SQLException sqlex ) {
    sqlex.printStackTrace();
    private Vector getNextRow( ResultSet rs,
    ResultSetMetaData rsmd )
    throws SQLException
    Vector currentRow = new Vector();
    for ( int i = 1; i <=rsmd.getColumnCount(); ++i )
    switch( rsmd.getColumnType( i ) ) {
    case Types.VARCHAR:
    case Types.LONGVARCHAR:
    currentRow.addElement( rs.getString( i ) );
    break;
    case Types.INTEGER:
    currentRow.addElement(
    new Long( rs.getLong( i ) ) );
    break;
    default:
    System.out.println( "Type was: " +
    rsmd.getColumnTypeName( i ) );
    return currentRow;
    public void shutDown()
    try {
    connection.close();
    catch ( SQLException sqlex ) {
    System.err.println( "Unable to disconnect" );
    sqlex.printStackTrace();
    public static void main( String args[] )
    final DisplayQueryResults app =
    new DisplayQueryResults();
    app.addWindowListener(
    new WindowAdapter() {
    public void windowClosing( WindowEvent e )
    app.shutDown();
    System.exit( 0 );
    public JTable returnTable(){
         return table;
    public JScrollPane returnScrollPane(){
         return scroller;

    It's now fixed!!!

  • Validating JTextfield in an Applet

    I am doing a simple assignment for a Java class I am taking. The assignment consists of doing the Tower of Hanoi with just symbols showing the moves of the disks. I have been successful in writing the recursive statement and init() but I am having trouble validating the JTextfield in the applet. I want to validate the entry is only between 1 and 9. Nothing else and no letters. Here is my code at the present time. If anyone could help I would appreciate it.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class HWProblem6_37Hanoi extends JApplet implements ActionListener
    /** Initialization method that will be called after the applet is loaded
    into the browser.*/
    JLabel directions;
    JTextField userInput;
    //attach JTextArea to a JScrollPane so user can scroll results
    JTextArea outputArea = new JTextArea(10, 30);
    //Set up applet's GUI
    public void init()
    //obtain content pane and set its layout to FlowLayout
    Container container=getContentPane();
    container.setLayout( new FlowLayout() );
    JScrollPane scroller = new JScrollPane(outputArea);
    //create directions label and attach it to content pane
    directions = new JLabel("Enter a Integer Between 1 and 9: ");
    container.add( directions );
    //create numberField and attach it to content pane
    userInput = new JTextField(10);
    container.add( userInput );
    //register this applet as userInput ActionListener
    userInput.addActionListener( this );
    container.add (scroller);
    public void actionPerformed(ActionEvent event)
    //Initialize variables
    int number = 0;
    while (number == 0)
    number = Integer.parseInt(userInput.getText());
    if ((number<1) || (number >9))
    userInput.setText(" ");
    number =0;
    showStatus("Error: Invalid Input");
    else
    showStatus("Valid Input");
    tower(number,1,2,3);
    public void tower(int n, int needle1/*source*/, int needle2/*destination*/, int needle3/*free space*/)
    if (n >0)
    tower(n-1, needle1, needle3, needle2);
    outputArea.append(needle1 + " -> " + needle3 + "\n");
    tower(n-1, needle2, needle1, needle3);
    }

    How to Use Formatted Text Fields
    http://java.sun.com/docs/books/tutorial/uiswing/components/formattedtextfield.html

  • Could some guru lend me a hand on this one?

    Hi all, this is my first post so I hope I don't miss any bits out here, ok it's like this: I'm trying to write a little Java bulletin where you click a button and it gets the infor from a text file on the web and pastes it into a text area, simple so far. However thats far away at the mo, all I'm trying to master at the moment is getting it to copy a text file in the same directory but I get one flipping error that I cant solve and it looks so simple! Heres the code:
    package RobsJava;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    public class xenia extends JFrame implements ActionListener {
    public xenia() {
    setTitle("Welcome to Xenia");
    setBounds(100, 100, 420, 400);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Creates: Menu bar, Menu, Menu items
    JMenuBar menuBar = new JMenuBar();
    setJMenuBar(menuBar);
    JMenu menu = new JMenu("Menu");
    menuBar.add(menu);
    JMenuItem item = new JMenuItem("Item Label");
    menu.add(item);
    //Creates the Java pane
    JPanel pane = new JPanel();
    //Adds the label "text field"
    JLabel roblab1 = new JLabel("Text Field: ");
    pane.add(roblab1);
    //Adds text area with scroll bar
    JTextArea textA = new JTextArea("Text Area", 4, 25);
    JScrollPane scroll = new JScrollPane(
    textA,
    ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
    ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    pane.add(scroll);
    //Adds update button & Action listener
    JButton update = new JButton("Update");
    update.addActionListener(this);
    pane.add(update);
    setContentPane(pane);
    show();
    pack();
    setVisible(true);
    //The main program
    public static void main(String[] arguments) {
    xenia xx = new xenia();
    xx.setVisible(true);
    //The action listener
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    Object src = evt.getSource();
    if (src == update)
    copy();
    //The copy program
    private Object copy() {
         File inputFile = new File("C:/JavaFiles/sampledir/RobsJava/xenia.txt");
         File outputFile = new File("C:/JavaFiles/sampledir/RobsJava/xenout.txt");
    FileReader in = new FileReader(inputFile);
    FileWriter out = new FileWriter(outputFile);
    int c;
    while ((c = in.read()) != -1)
    out.write(c);
    in.close();
    out.close();
    // public Object getValue(String str) {
    // public void putValue(String str, Object obj) {
    Ok so you're supposed to push the button and it coppies xenia.txt and makes a xenout.txt.
    The problem is the if function that should calll the copy object thing. When I compile it it wont recognise the variable update.
    Anyone?
    Cheers
    Rob

    That's because you declare update to be a local variable in your constructor, but you're referencing it from a different method.
    In other words, it's "out of scope".
    IMHO, best solution is to use an anonymous inner class for that listener (the one that currently can't find the update variable). Another option is to make update a field in the object, rather than a local variable.

  • Need help with JTextArea and Scrolling

    import java.awt.*;
    import java.awt.event.*;
    import java.text.DecimalFormat;
    import javax.swing.*;
    public class MORT_RETRY extends JFrame implements ActionListener
    private JPanel keypad;
    private JPanel buttons;
    private JTextField lcdLoanAmt;
    private JTextField lcdInterestRate;
    private JTextField lcdTerm;
    private JTextField lcdMonthlyPmt;
    private JTextArea displayArea;
    private JButton CalculateBtn;
    private JButton ClrBtn;
    private JButton CloseBtn;
    private JButton Amortize;
    private JScrollPane scroll;
    private DecimalFormat calcPattern = new DecimalFormat("$###,###.00");
    private String[] rateTerm = {"", "7years @ 5.35%", "15years @ 5.5%", "30years @ 5.75%"};
    private JComboBox rateTermList;
    double interest[] = {5.35, 5.5, 5.75};
    int term[] = {7, 15, 30};
    double balance, interestAmt, monthlyInterest, monthlyPayment, monPmtInt, monPmtPrin;
    int termInMonths, month, termLoop, monthLoop;
    public MORT_RETRY()
    Container pane = getContentPane();
    lcdLoanAmt = new JTextField();
    lcdMonthlyPmt = new JTextField();
    displayArea = new JTextArea();//DEFINE COMBOBOX AND SCROLL
    rateTermList = new JComboBox(rateTerm);
    scroll = new JScrollPane(displayArea);
    scroll.setSize(600,170);
    scroll.setLocation(150,270);//DEFINE BUTTONS
    CalculateBtn = new JButton("Calculate");
    ClrBtn = new JButton("Clear Fields");
    CloseBtn = new JButton("Close");
    Amortize = new JButton("Amortize");//DEFINE PANEL(S)
    keypad = new JPanel();
    buttons = new JPanel();//DEFINE KEYPAD PANEL LAYOUT
    keypad.setLayout(new GridLayout( 4, 2, 5, 5));//SET CONTROLS ON KEYPAD PANEL
    keypad.add(new JLabel("Loan Amount$ : "));
    keypad.add(lcdLoanAmt);
    keypad.add(new JLabel("Term of loan and Interest Rate: "));
    keypad.add(rateTermList);
    keypad.add(new JLabel("Monthly Payment : "));
    keypad.add(lcdMonthlyPmt);
    lcdMonthlyPmt.setEditable(false);
    keypad.add(new JLabel("Amortize Table:"));
    keypad.add(displayArea);
    displayArea.setEditable(false);//DEFINE BUTTONS PANEL LAYOUT
    buttons.setLayout(new GridLayout( 1, 3, 5, 5));//SET CONTROLS ON BUTTONS PANEL
    buttons.add(CalculateBtn);
    buttons.add(Amortize);
    buttons.add(ClrBtn);
    buttons.add(CloseBtn);//ADD ACTION LISTENER
    CalculateBtn.addActionListener(this);
    ClrBtn.addActionListener(this);
    CloseBtn.addActionListener(this);
    Amortize.addActionListener(this);
    rateTermList.addActionListener(this);//ADD PANELS
    pane.add(keypad, BorderLayout.NORTH);
    pane.add(buttons, BorderLayout.SOUTH);
    pane.add(scroll, BorderLayout.CENTER);
    addWindowListener( new WindowAdapter()
    public void windowClosing(WindowEvent e)
    System.exit(0);
    public void actionPerformed(ActionEvent e)
    String arg = lcdLoanAmt.getText();
    int combined = Integer.parseInt(arg);
    if (e.getSource() == CalculateBtn)
    try
    JOptionPane.showMessageDialog(null, "Got try here", "Error", JOptionPane.ERROR_MESSAGE);
    catch(NumberFormatException ev)
    JOptionPane.showMessageDialog(null, "Got here", "Error", JOptionPane.ERROR_MESSAGE);
    if ((e.getSource() == CalculateBtn) && (arg != null))
    try{
    if ((e.getSource() == CalculateBtn) && (rateTermList.getSelectedIndex() == 1))
    monthlyInterest = interest[0] / (12 * 100);
    termInMonths = term[0] * 12;
    monthlyPayment = combined * (monthlyInterest / (1 - (Math.pow (1 + monthlyInterest,  -termInMonths))));
    lcdMonthlyPmt.setText(calcPattern.format(monthlyPayment));
    if ((e.getSource() == CalculateBtn) && (rateTermList.getSelectedIndex() == 2))
    monthlyInterest = interest[1] / (12 * 100);
    termInMonths = term[1] * 12;
    monthlyPayment = combined * (monthlyInterest / (1 - (Math.pow (1 + monthlyInterest,  -termInMonths))));
    lcdMonthlyPmt.setText(calcPattern.format(monthlyPayment));
    if ((e.getSource() == CalculateBtn) && (rateTermList.getSelectedIndex() == 3))
    monthlyInterest = interest[2] / (12 * 100);
    termInMonths = term[2] * 12;
    monthlyPayment = combined * (monthlyInterest / (1 - (Math.pow (1 + monthlyInterest,  -termInMonths))));
    lcdMonthlyPmt.setText(calcPattern.format(monthlyPayment));
    catch(NumberFormatException ev)
    JOptionPane.showMessageDialog(null, "Invalid Entry!\nPlease Try Again", "Error", JOptionPane.ERROR_MESSAGE);
    }                    //IF STATEMENTS FOR AMORTIZATION
    if ((e.getSource() == Amortize) && (rateTermList.getSelectedIndex() == 1))
    loopy(7, 5.35);
    if ((e.getSource() == Amortize) && (rateTermList.getSelectedIndex() == 2))
    loopy(15, 5.5);
    if ((e.getSource() == Amortize) && (rateTermList.getSelectedIndex() == 3))
    loopy(30, 5.75);
    if (e.getSource() == ClrBtn)
    rateTermList.setSelectedIndex(0);
    lcdLoanAmt.setText(null);
    lcdMonthlyPmt.setText(null);
    displayArea.setText(null);
    if (e.getSource() == CloseBtn)
    System.exit(0);
    private void loopy(int lTerm,double lInterest)
    double total, monthly, monthlyrate, monthint, monthprin, balance, lastint, paid;
    int amount, months, termloop, monthloop;
    String lcd2 = lcdLoanAmt.getText();
    amount = Integer.parseInt(lcd2);
    termloop = 1;
    paid = 0.00;
    monthlyrate = lInterest / (12 * 100);
    months = lTerm * 12;
    monthly = amount *(monthlyrate/(1-Math.pow(1+monthlyrate,-months)));
    total = months * monthly;
    balance = amount;
    while (termloop <= lTerm)
    displayArea.setCaretPosition(0);
    displayArea.append("\n");
    displayArea.append("Year " + termloop + " of " + lTerm + ": payments\n");
    displayArea.append("\n");
    displayArea.append("Month\tMonthly\tPrinciple\tInterest\tBalance\n");
    monthloop = 1;
    while (monthloop <= 12)
    monthint = balance * monthlyrate;
    monthprin = monthly - monthint;
    balance -= monthprin;
    paid += monthly;
    displayArea.setCaretPosition(0);
    displayArea.append(monthloop + "\t" + calcPattern.format(monthly) + "\t" + calcPattern.format(monthprin) + "\t");
    displayArea.append(calcPattern.format(monthint) + "\t" + calcPattern.format(balance) + "\n");
    monthloop ++;
    termloop ++;
    public static void main(String args[])
    MORT_RETRY f = new MORT_RETRY();
    f.setTitle("MORTGAGE PAYMENT CALCULATOR");
    f.setBounds(600, 600, 500, 500);
    f.setLocationRelativeTo(null);
    f.setVisible(true);
    }need help with displaying the textarea correctly and the scroll bar please.
    Message was edited by:
    new2this2020

    What's the problem you're having ???
    PS.

  • 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];

  • Having a JTextArea scroll when output is written to it

    I'm using a JTextArea (inside a JScrollPane) as a console, and I use the append() method to update the text area with various information. I'd like the JTextArea to automatically scroll down as more lines get added onto it, similar to a shell or command prompt.
    It seems "autoscroll" refers to something else, and the scrollpane horizontal/vertical policy refers to the display, not behavior, of the scrollpane. Can anyone point me in the right direction?
    Message was edited by:
    k1cheng

    i've done this in the past by adding
    textArea.setCaretPosition(
    textArea.getDocument().getLength());
    after the append. hope this helps!This works great. Thanks.
    camickr, you are right. Thanks.

  • Swing bug?: scrolling BLIT_SCROLL_MODE painting JTextArea components hangs

    java version "1.5.0_04"
    Hello,
    When drawing JComponent Text Areas and dynamically scrolling, Java gets confused, gets the shivers and freezes when the viewport cannot get its arms around the canvas. ;)
    Possible problem at JViewport.scrollRectToVisible().
    When painting non-text area components eg. graphics circles, it is ok.
    Have provided example code. This code is based on the ScrollDemo2 example provided in the Sun Java
    Tutorial
    thanks,
    Anil Philip
    juwo LLC
    Usage: run program and repeatedly click the left mouse button near right boundary to create a new JComponent node each time and to force scrolling area to increase in size to the right.
    When the first node crosses the left boundary, then the scroll pane gets confused, gets the shivers and hangs.
    The other scroll modes are a bit better - but very slow leaving the toolbar (in the oroginal application) unpainted sometimes.
    * to show possible bug when in the default BLIT_SCROLL_MODE and with JTextArea components.
    * author: Anil Philip. juwo LLC. http://juwo.com
    * Usage: run program and repeatedly click the left mouse button near right boundary to
    * create a new JComponent node each time and to force scrolling area to increase in size to the right.
    * When the first node crosses the left boundary, then the scroll pane gets confused, gets the shivers
    and hangs.
    * The other scroll modes are a bit better - but very slow leaving the toolbar (in the oroginal
    application)
    * unpainted sometimes.
    * This code is based on the ScrollDemo2 example provided in the Sun Java Tutorial (written by John
    Vella, a tutorial reader).
    import javax.swing.*;
    import javax.swing.border.EtchedBorder;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    /* ScrollDemo2WithBug.java is a 1.5 application that requires no other files. */
    public class ScrollDemo2WithBug extends JPanel {
    private Dimension area; //indicates area taken up by graphics
    private Vector circles; //coordinates used to draw graphics
    private Vector components;
    private JPanel drawingPane;
    public ScrollDemo2WithBug() {
    super(new BorderLayout());
    area = new Dimension(0, 0);
    circles = new Vector();
    components = new Vector();
    //Set up the instructions.
    JLabel instructionsLeft = new JLabel(
    "Click left mouse button to place a circle.");
    JLabel instructionsRight = new JLabel(
    "Click right mouse button to clear drawing area.");
    JPanel instructionPanel = new JPanel(new GridLayout(0, 1));
    instructionPanel.add(instructionsLeft);
    instructionPanel.add(instructionsRight);
    //Set up the drawing area.
    drawingPane = new DrawingPane();
    drawingPane.setBackground(Color.white);
    drawingPane.setPreferredSize(new Dimension(200, 200));
    //Put the drawing area in a scroll pane.
    JScrollPane scroller = new JScrollPane(drawingPane);
    // scroller.getViewport().setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
    if(scroller.getViewport().getScrollMode() == JViewport.BACKINGSTORE_SCROLL_MODE)
    System.out.println("BACKINGSTORE_SCROLL_MODE");
    if(scroller.getViewport().getScrollMode() == JViewport.BLIT_SCROLL_MODE)
    System.out.println("BLIT_SCROLL_MODE");
    if(scroller.getViewport().getScrollMode() == JViewport.SIMPLE_SCROLL_MODE)
    System.out.println("SIMPLE_SCROLL_MODE");
    //Lay out this demo.
    add(instructionPanel, BorderLayout.PAGE_START);
    add(scroller, BorderLayout.CENTER);
    /** The component inside the scroll pane. */
    public class DrawingPane extends JPanel implements MouseListener {
    private class VisualNode {
    int x = 0;
    int y = 0;
    int id = 0;
    public VisualNode(int id, int x, int y) {
    this.id = id;
    this.x = x;
    this.y = y;
    title.setLineWrap(true);
    title.setAlignmentY(Component.TOP_ALIGNMENT);
    titlePanel.add(new JButton("Hi!"));
    titlePanel.add(title);
    nodePanel.add(titlePanel);
    nodePanel.setBorder(BorderFactory
    .createEtchedBorder(EtchedBorder.RAISED));
    box.add(nodePanel);
    ScrollDemo2WithBug.this.drawingPane.add(box);
    Box box = Box.createVerticalBox();
    Box titlePanel = Box.createHorizontalBox();
    JTextArea title = new JTextArea(1, 10); // 1 rows x 10 cols
    Box nodePanel = Box.createVerticalBox();
    public void paintNode(Graphics g) {
    int ix = (int) x + ScrollDemo2WithBug.this.getInsets().left;
    int iy = (int) y + ScrollDemo2WithBug.this.getInsets().top;
    title.setText(id + " (" + ix + "," + iy + ") ");
    box.setBounds(ix, iy, box.getPreferredSize().width, box
    .getPreferredSize().height);
    int n = 0;
    DrawingPane() {
    this.setLayout(null);
    addMouseListener(this);
    protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.fill3DRect(10, 10, 25, 25, true);
    Point point;
    for (int i = 0; i < circles.size(); i++) {
    point = (Point) circles.elementAt(i);
    VisualNode node = (VisualNode) components.get(i);
    node.paintNode(g);
    //Handle mouse events.
    public void mouseReleased(MouseEvent e) {
    final int W = 100;
    final int H = 100;
    boolean changed = false;
    if (SwingUtilities.isRightMouseButton(e)) {
    //This will clear the graphic objects.
    circles.removeAllElements();
    area.width = 0;
    area.height = 0;
    changed = true;
    } else {
    int x = e.getX() - W / 2;
    int y = e.getY() - H / 2;
    if (x < 0)
    x = 0;
    if (y < 0)
    y = 0;
    Point point = new Point(x, y);
    VisualNode node = new VisualNode(circles.size(), point.x,
    point.y);
    // add(node);
    components.add(node);
    circles.addElement(point);
    drawingPane.scrollRectToVisible(new Rectangle(x, y, W, H));
    int this_width = (x + W + 2);
    if (this_width > area.width) {
    area.width = this_width;
    changed = true;
    int this_height = (y + H + 2);
    if (this_height > area.height) {
    area.height = this_height;
    changed = true;
    if (changed) {
    //Update client's preferred size because
    //the area taken up by the graphics has
    //gotten larger or smaller (if cleared).
    drawingPane.setPreferredSize(area);
    //Let the scroll pane know to update itself
    //and its scrollbars.
    drawingPane.revalidate();
    drawingPane.repaint();
    public void mouseClicked(MouseEvent e) {
    public void mouseEntered(MouseEvent e) {
    public void mouseExited(MouseEvent e) {
    public void mousePressed(MouseEvent e) {
    * Create the GUI and show it. For thread safety, this method should be
    * invoked from the event-dispatching thread.
    private static void createAndShowGUI() {
    //Make sure we have nice window decorations.
    JFrame.setDefaultLookAndFeelDecorated(true);
    //Create and set up the window.
    JFrame frame = new JFrame("ScrollDemo2");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create and set up the content pane.
    JComponent newContentPane = new ScrollDemo2WithBug();
    newContentPane.setOpaque(true); //content panes must be opaque
    frame.setContentPane(newContentPane);
    //Display the window.
    frame.setSize(800, 600);
    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();
    }

    I changed the name so you can run this as-is without name clashing. It works okay now.
    import javax.swing.*;
    import javax.swing.border.EtchedBorder;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    public class SD2 extends JPanel {
        public SD2() {
            super(new BorderLayout());
            //Set up the instructions.
            JLabel instructionsLeft = new JLabel(
                    "Click left mouse button to place a circle.");
            JLabel instructionsRight = new JLabel(
                    "Click right mouse button to clear drawing area.");
            JPanel instructionPanel = new JPanel(new GridLayout(0, 1));
            instructionPanel.add(instructionsLeft);
            instructionPanel.add(instructionsRight);
            //Set up the drawing area.
            DrawingPane drawingPane = new DrawingPane(this);
            drawingPane.setBackground(Color.white);
            drawingPane.setPreferredSize(new Dimension(200, 200));
            //Put the drawing area in a scroll pane.
            JScrollPane scroller = new JScrollPane(drawingPane);
            // scroller.getViewport().setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
            if(scroller.getViewport().getScrollMode() == JViewport.BACKINGSTORE_SCROLL_MODE)
                System.out.println("BACKINGSTORE_SCROLL_MODE");
            if(scroller.getViewport().getScrollMode() == JViewport.BLIT_SCROLL_MODE)
                System.out.println("BLIT_SCROLL_MODE");
            if(scroller.getViewport().getScrollMode() == JViewport.SIMPLE_SCROLL_MODE)
                System.out.println("SIMPLE_SCROLL_MODE");
            //Lay out this demo.
            add(instructionPanel, BorderLayout.PAGE_START);
            add(scroller, BorderLayout.CENTER);
         * Create the GUI and show it. For thread safety, this method should be
         * invoked from the event-dispatching thread.
        private static void createAndShowGUI() {
            //Make sure we have nice window decorations.
            JFrame.setDefaultLookAndFeelDecorated(true);
            //Create and set up the window.
            JFrame frame = new JFrame("ScrollDemo2");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            JComponent newContentPane = new SD2();
            newContentPane.setOpaque(true);      //content panes must be opaque
            frame.setContentPane(newContentPane);
            //Display the window.
            frame.setSize(800, 600);
            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();
    /** The component inside the scroll pane. */
    class DrawingPane extends JPanel implements MouseListener {
        SD2 sd2;
        private Dimension area;     //indicates area taken up by graphics
        private Vector circles;     //coordinates used to draw graphics
        private Vector components;
        int n = 0;
        final int
            W = 100,
            H = 100;
        DrawingPane(SD2 sd2) {
            this.sd2 = sd2;
            area = new Dimension(0, 0);
            circles = new Vector();
            components = new Vector();
            this.setLayout(null);
            addMouseListener(this);
         * The 'paint' method is a Container method and it passes its
         * Graphics context, g, to each of its Component children which
         * use it to draw themselves into the parent. JComponent overrides
         * this Container 'paint' method and in it calls this method in
         * addition to others - see api. So the children of DrawingPane will
         * each paint themselves. Here you can do custom painting/rendering.
         * But this is not the place to ask components to paint themselves.
         * That would get swing very confused...
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.fill3DRect(10, 10, 25, 25, true);
            g.setColor(Color.red);
            Point point;
            for (int i = 0; i < circles.size(); i++) {
                point = (Point) circles.elementAt(i);
                g.fillOval(point.x-2, point.y-2, 4, 4);
        //Handle mouse events.
        public void mousePressed(MouseEvent e) {
            if (SwingUtilities.isRightMouseButton(e)) {
                //This will clear the graphic objects.
                circles.removeAllElements();
                components.removeAllElements();
                removeAll();                    // to clear the components
                area.width = 0;
                area.height = 0;
                setPreferredSize(area);
                revalidate();
                repaint();
            } else {
                int x = e.getX() - W / 2;
                int y = e.getY() - H / 2;
                if (x < 0)
                    x = 0;
                if (y < 0)
                    y = 0;
                Point point = new Point(x, y);
                VisualNode node = new VisualNode(this, circles.size(), point.x, point.y);
                // add(node);
                components.add(node);       // not needed
                circles.addElement(point);
                checkBoundries(x, y, node);
        private void checkBoundries(int x, int y, VisualNode node) {
            boolean changed = false;
            // since we used the setPreferredSize property to set the size
            // of each box we'll have to use it again to let the JScrollPane
            // know what size we need to show all our child components
            int this_width = (x + node.box.getPreferredSize().width + 2);
            if (this_width > area.width) {
                area.width = this_width;
                changed = true;
            int this_height = (y + node.box.getPreferredSize().height + 2);
            if (this_height > area.height) {
                area.height = this_height;
                changed = true;
            if (changed) {
                //Update client's preferred size because
                //the area taken up by the graphics has
                //gotten larger or smaller (if cleared).
                setPreferredSize(area);
                scrollRectToVisible(new Rectangle(x, y, W, H));
                //Let the scroll pane know to update itself
                //and its scrollbars.
                revalidate();
            repaint();
        public void mouseReleased(MouseEvent e) { }
        public void mouseClicked(MouseEvent e)  { }
        public void mouseEntered(MouseEvent e)  { }
        public void mouseExited(MouseEvent e)   { }
    * We are adding components to DrawingPanel so there is no need to get
    * into the paint methods of DrawingPane. Components are designed to draw
    * themseleves when their parent container passes them a Graphics context
    * and asks them to paint themselves into the parent.
    class VisualNode {
        DrawingPane drawPane;
        int x;
        int y;
        int id;
        Box box;
        public VisualNode(DrawingPane dp, int id, int x, int y) {
            drawPane = dp;
            this.id = id;
            this.x = x;
            this.y = y;
            box = Box.createVerticalBox();
            Box titlePanel = Box.createHorizontalBox();
            JTextArea title = new JTextArea(1, 10);     // 1 rows x 10 cols
            Box nodePanel = Box.createVerticalBox();
            title.setLineWrap(true);
            title.setAlignmentY(Component.TOP_ALIGNMENT);
            titlePanel.add(new JButton("Hi!"));
            titlePanel.add(title);
            nodePanel.add(titlePanel);
            nodePanel.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
            box.add(nodePanel);
            // here we are adding a component to drawPane so there is really
            // no need to keep this VisualNode in a collection
            drawPane.add(box);
            int ix = (int) x + drawPane.getInsets().left;
            int iy = (int) y + drawPane.getInsets().top;
            title.setText(id + " (" + ix + "," + iy + ") ");
            // since we are using the preferredSize property to setBounds here
            // we'll need access to it (via box) for the scrollPane in DrawPane
            // so we expose box as a member variable
            box.setBounds(ix, iy, box.getPreferredSize().width,
                                  box.getPreferredSize().height);
    }

  • JTextArea refuses to scroll.

    Having just read through some old post and not getting any change i thought i would post.
    I have two JTextArea (They used to be JEditorPanes, but i grew tired of the slow down from the ever growing return of getText) and when they were JEditorPanes, they would scroll. But now they wont.
    Below is an code stub...
    else {
         outputText =  "Prepared to overwrite "     + destination_locale.getAbsolutePath() + "...";
         outputEditor.append(outputText);
         outputEditor.setCaretPosition(outputEditor.getDocument().getLength());
    }And yes the TextArea is inside a ScrollPane...
              // Initialize the outputEditor.
              outputEditor = new JTextArea();
              outputEditor.setEditable(false);
              outputEditor.setPreferredSize(new Dimension(500, 150));
              outputEditor.setMaximumSize(new Dimension(500, 150));
              // Attach the outputEditor to its scroll.
              scroll2 = new JScrollPane(outputEditor);
              scroll2.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

    1. Review http://java.sun.com/docs/books/tutorial/uiswing/components/textarea.html
    2. Post a small example program that compiles and exhibits the problem.
    3. Please post future Swing questions in the Swing forum.

Maybe you are looking for

  • 5002 error in itunes all of a sudden

    So my main itunes install is now acting up. I'm getting the 5002 error. It used to work fine. I purchased some songs on my iphone today and sync'd them to my mac mini itunes install where all my music is. I tried to go into my account and it asks for

  • Need A Code For CMD_EI_API

    Hi All, I used the class CMD_EI_API and method MAINTAIN_BAPI in my report to create a customer master data (data uploaded from the excelsheet which is  already has the customer number ) ,its not showing any messages and not even updating the table if

  • Mac crashed..can't sync..help!

    my macbook crashed and i lost everything and now i can't sync my phone.  I authorized the computer, and transfered the purchases.   All my apps show up on the screen now, however they're not highlighted..i can't move or select or sync anything from m

  • Use T.C. as plain NAS? Backup of T.C. to another drive?i

    I do not intend to use Time Machine at all, because all my valuable files are kept NOT on my local Macs, but on a Lacie NAS and an external Firewire drive. But, my lacie NAS is slow, and running out of space. I also only have a 100BT AirportExpress n

  • Charging all day can cause the bettery life shorter??

    hi.. i bought my bold 9780 yesterday. and i'm work using computer. so i think maybe i can connect my bold to my computer so the battery will always full when i go out. is that okay? i've saw someone post at another forum that i shouldn't connect my b