JScrollPane Question

Hi,
I am writing a simple java GUI application that feeds real-time data to surgeons during a brain surgery. I am using a JTextArea component inside a JScrollPane to display information. As the data get more than the window can display, the horizontal scrollbar appears to indicate that more information is appended to the window. The problem is that I want to display the latest information added to the JTextArea container without having to manually bring down the scrollbar to the bottom of the column. I think there must be a method in the JScrollPane class that automatically scrolls the bar to the bottom so that the latest information is always visible in the display area.
Thanks,
David

Well since the cat is out of the bag you should use:
textArea.setCaretPosition( textArea.getDocument().getLength() );
Its more efficient.

Similar Messages

  • JScrollPane questions

    Hi, I have two questions regarding JScrollPane:
    1) I have a JPanel inside a scrollpane, but setViewportView() doesn't seem to work too well. Could anyone give me a better idea how to set the viewport view, an example perhaps? The tutorial doesn't go into much detail. For instance, let's say I have an 800 * 600 JPanel with a spot on it at 500, 300. How would I make the JScrollPane move so that this spot is in the centre?
    2) Is there a method that essentially does the same thing as clicking on one of the scrollbar arrows, so I can have four buttons (Up Down Left Right) that scroll instead of scrollbars?
    Thanks.

    #1
    sp.getViewport().scrollRectToVisible(...)
    import javax.swing.*;
    import java.awt.*;
    class Testing extends JFrame
      public Testing()
        setLocation(400,300);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        JPanel panel = new JPanel(null);
        panel.setPreferredSize(new Dimension(800,600));
        JLabel label = new JLabel("Hello World");
        label.setBounds(500,300,80,20);
        panel.add(label);
        JScrollPane sp = new JScrollPane (panel);
        sp.setPreferredSize(new Dimension(200,200));
        getContentPane().add(sp);
        pack();
        sp.getViewport().scrollRectToVisible(new Rectangle(440,210,200,200));//<-----------------------
      public static void main(String[] args){new Testing().setVisible(true);}
    }#2
    you can get the scrollbar object/s from the scrollpane and use setValue()
    you can set the scrollbar's policy as NEVER - look up the various constructors
    for JScrollpane

  • About JTextArea and JScrollPane question

    I make a swing program to run a test,a JTextArea can display the test content ,and the content increased continuously,but the vertical scroll bar is always on the top .I want the vertical scroll bar at the bottom at all time so that we can read the newest content from JTextArea.
    How can I do?

    textArea.setCaretPosition( textArea.getDocument().getLength() );

  • Button events

    Hi
    Please can anyone help. I put a table button in a GUI and tried to open the table in a separate GUI. The data for this table is stored somewhere but when I click on the table button nothing happens. Some of the other buttons: next exercise, exit are not working either. What am I doing wrong?
    Any help will be most appreciated.
    Thanks
    Sofia
    ExerciseGUI - contains tableGUI button and other buttons
    TableGUI
    TableDBHandler
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import java.awt.Component;
    import javax.swing.text.*;
    import javax.swing.table.*;
    public class ExerciseGUI extends JFrame {
    JTable table = new JTable(5,3); JLabel tableLabel = new JLabel ("Customer Table");
    JTextField exerciseName = new JTextField(40); JLabel
    exerciseNameLabel = new JLabel("Exercise Name");
    JTextField questionNum = new JTextField(10); JLabel questionNumLabel = new JLabel("Question Number");
    Font font = new Font("times new roman", Font.BOLD, 30);
    JTextArea question = new JTextArea(5,36); JLabel questionLabel = new JLabel("Question");
    JTextField answer = new JTextField(36); JLabel answerLabel     = new JLabel("Student Answer");
    JButton accept          = new JButton();
    JButton copy = new JButton(); //JScrollBar scroll = new JScrollBar();
    JButton next = new JButton();
    JButton close = new JButton();
    JButton table = new JButton();
         JPanel questPanel     = new JPanel();
         JPanel answPanel     = new JPanel();
         JPanel mainPanel     = new JPanel();
    JScrollPane scrollPane = new JScrollPane(question);
    JLabel wordsLabel = new JLabel("Select words");
    JTextField wordList = new JTextField();
    TableGUI aTableGUI= new TableGUI();
    JLabel sortWordsLabel = new JLabel(" Sort these items to form the correct SQL query statement in answer.");
    public static final int DISPOSE_ON_CLOSE = 2;
         FlowLayout myLayout = new FlowLayout(FlowLayout.LEFT);
         public ExerciseGUI() {
         try {
    setDisplay();
    setSize(600,500);
    }catch(Exception e) {e.printStackTrace();}
         public static void setNativeLookAndFeel() {
    try {
         UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
         catch(Exception e) {
         System.out.println("Error setting native LAF: " + e);
         private void setQuestionPanel() {
              questPanel.setBorder(BorderFactory.createTitledBorder("QUESTION"));
              questPanel.setLayout(myLayout);
              questPanel.setMinimumSize(new Dimension(450,300));
              questPanel.setPreferredSize(new Dimension(450,300));
              questPanel.setMaximumSize(new Dimension(450,300));
    questPanel.add(exerciseNameLabel);
         questPanel.add(exerciseName);
    questPanel.add(questionNumLabel);
         questPanel.add(questionNum);
    questPanel.add(questionLabel);
    boolean aWrap = true;
    questPanel.add(question);
         questPanel.add(tableLabel);
    questPanel.add(table);
    JButton aButton = new JButton();
         questPanel.add(aButton, null);
    aButton.setText("Table");
    aButton.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
    aButton_mouseClicked(e);
    void aButton_mouseClicked(MouseEvent e) {
    tableGUI aTableGUI= new tableGUI();
         private void setAnswerPanel() {
              answPanel.setBorder(BorderFactory.createTitledBorder("ANSWER"));
              answPanel.setLayout(myLayout);
              answPanel.setMinimumSize(new Dimension(400,200));
              answPanel.setPreferredSize(new Dimension(400,200));
              answPanel.setMaximumSize(new Dimension(400,200));
         answPanel.add(sortWordsLabel);
    copy.setText("Select");
              copy.setSize(2,30);
    answPanel.add(copy);
    copy.addMouseListener(new MouseAdapter() {
              public void mouseClicked(MouseEvent e) {
         copy_mouseClicked(e);
    answPanel.add(answerLabel);
              answPanel.add(answer);
    accept.setText("Evaluate Answer");
              accept.setSize(2,30);
    accept.addMouseListener(new MouseAdapter() {
              public void mouseClicked(MouseEvent e) {
    accept_mouseClicked(e);
    next.setText("Next Exercise");
    next.setSize(2, 20);
    next.addMouseListener(new MouseAdapter() {
              public void mouseClicked(MouseEvent e) {
    next_mouseClicked(e);
    close.setText("Exit Tutorial");
    close.setSize(2, 20);
    close.addMouseListener(new MouseAdapter() {
              public void mouseClicked(MouseEvent e) {
    close_mouseClicked(e);
         answPanel.add(accept);
    answPanel.add(next, null);
    answPanel.add(close, null);
         private void setDisplay() throws Exception {
              setNativeLookAndFeel();
              Container content = getContentPane();
              //content.setMiniumSize(new Dimension(400,400));
              //content.setPreferredSize(new dimension(400,400));
              content.setLayout(new GridLayout(0,1));
              content.setFont(font);
              content.setBackground(Color.lightGray);
    this.setTitle("Display Exercise");
    setQuestionPanel();
              setAnswerPanel();
              content.add(questPanel);
              content.add(answPanel);
              setContentPane(content);
    /* exerciseGUI.setDefaultCloseOperation(
    WindowConstants.DISPOSE_ON_CLOSE);
    exerciseGUI.addWindowListener() {
    public void windowClosed(WindowEvent e){
    system.exit(20);
    String studentAnswer;
    void accept_mouseClicked(MouseEvent e) {
    String studentAnswer = answer.getText();
    DBHandler aDBHandler = new DBHandler(questionNum.getText(), studentAnswer);
    void copy_mouseClicked(MouseEvent e) {
    wordList.copy();
    answer.paste();
    answer.append("");
    void next_mouseClicked(MouseEvent e) {
    System.out.println("Starting Search_GUI...");
              ExerciseSelectorGUI aGUI = new ExerciseSelectorGUI();
    aGUI.show();
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import java.awt.Component;
    import javax.swing.text.*;
    import javax.swing.table.*;
    public class TableGUI extends JFrame {
    JTable table = new JTable(5,3); JLabel tableLabel = new JLabel("Customer Table");
         Font font          = new Font("times new roman", Font.BOLD, 30);
         JPanel tabPanel     = new JPanel();
         JPanel mainPanel     = new JPanel();
    TableDBHandler aTableDBHandler;
         FlowLayout myLayout = new FlowLayout(FlowLayout.LEFT);
         public TableGUI() {
         try {
    setDisplay();
    setSize(500,400);
    }catch(Exception e) {e.printStackTrace();}
         public static void setNativeLookAndFeel() {
    try {
         UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
         catch(Exception e) {
         System.out.println("Error setting native LAF: " + e);
         private void setTablePanel() {
              tabPanel.setBorder(BorderFactory.createTitledBorder("TABLE"));
              tabPanel.setLayout(myLayout);
              tabPanel.setMinimumSize(new Dimension(300,200));
              tabPanel.setPreferredSize(new Dimension(300,200));
              tabPanel.setMaximumSize(new Dimension(300,200));
    tabPanel.add(tableLabel);
    tabPanel.add(table);
    /*copy.setText("Select");
              copy.setSize(2,30);
         copy.addMouseListener(new MouseAdapter() {
              public void mouseClicked(MouseEvent e) {
    copy_mouseClicked(e);
         questPanel.add(copy);*/
         private void setDisplay() throws Exception {
              setNativeLookAndFeel();
              Container content = getContentPane();
              //content.setMiniumSize(new Dimension(400,400));
              //content.setPreferredSize(new dimension(400,400));
              content.setLayout(new GridLayout(0,1));
              content.setFont(font);
              content.setBackground(Color.lightGray);
    this.setTitle("Display Table");
    setTablePanel();
              content.add(tabPanel);
              setContentPane(content);
    import java.awt.*;
    import javax.swing.*;
    import java.sql.*;
    import java.lang.*;
    import javax.swing.table.*;
    public class TableDBHandler {
    TableGUI customTable = new TableGUI ();
    public TableDBHandler() {
    try {
    DriverManager.registerDriver(new sun.jdbc.odbc.JdbcOdbcDriver());
    Connection aConnection = DriverManager.getConnection("jdbc:odbc:SQLDatabase", "", "");
    Statement aStatement = aConnection.createStatement();
    ResultSet aSet = aStatement.executeQuery ("SELECT CustomerNo, Name, Address FROM CustTable"); {
    while (aSet.next());
    customTable.addItem(aSet.get(setText));
    //aGUI.customerNo.setText(k);
    //aGUI.name.setText(l);
    //set text one under another
    //aGUI.address.setText(m);
    customTable.show();
    aConnection.close();
    catch (SQLException e) { System.exit(8);}

    Hi,
    didn't read all of your code, but one problem is that you use the same name for the JTable and the JButton (both are named table. You should avoid this, personnally I often use the first letter(s) of a variable name to explain wich class it come from... for example, bNew (or JbNew) for a NEW JButton, tNames (or jtUsers) for a USERS JTable.
    Hope this helps,
    Regards.

  • JScrollPane viewport size question

    Hi all,
    I've a component that is very large (it has a dinamic height) but its width is always the same (fixed). I need to show this component in a JScrollPane container and only shows the vertical scrollbar. It works fine but when my applications runs, the component inside the JScrollPane (yes..my component) get a different width, which is larger than the original componet's width
    I'm using the following code:
            JScrollPane scroll = new JScrollPane(myComponent);
            scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);My question is, How I can do for set a fixed width to the JScrollPane (its viewport or its child component) in order to get the correct component width and only allows a dinamic height ?
    thanks in advance

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Random;
    public class Test3 extends JFrame {
      JPanel jp = new JPanel();
      JScrollPane jsp = new JScrollPane(jp);
      JLabel jl = new JLabel("", JLabel.CENTER);
      Random rand = new Random();
      public Test3(){
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container content = getContentPane();
        content.add(jl, BorderLayout.NORTH);
        jp.setBorder(BorderFactory.createLineBorder(Color.blue));
        jsp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        content.add(jsp, BorderLayout.CENTER);
        JButton jb = new JButton("Random Height");
        content.add(jb, BorderLayout.SOUTH);
        jb.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent ae) {
            int height = rand.nextInt(1000);
            jp.setPreferredSize(new Dimension(jsp.getViewport().getWidth(),height));
            jsp.getViewport().revalidate();
            jl.setText(""+height);
        setSize(300,300);
      public static void main(String[] args) {new Test3().setVisible(true); }
    }

  • 2 swing questions: JScrollPane and displaying pictures

    I'm building a GUI for a toy application I have written, I have two questions:
    1-The main window is inherited from JFrame, There is a JTabbedPane attached to it, and a JPanel as the first tab of the tabbed pane. There are so many jcomponents in this JPanel, this makes it too big for small resolution computers (below 1024 * 768), I would like to add this JPanel to a JScrollPane to make it behave like a text area, I've done it but it didn't work, obviously there is something I'm missing.
    2-My application calls another program to create some images at runtime which will be displayed in the other tabs, after calling the program and creating the image, I get the filename of the image. What is the best way to display this image?
    I have tried JLabel's but they don't update their pictures for some reason after it has been changed.
    Thanx in advance.

    Updated and tested code, hopefully this will help.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    public class ImagePanel extends JPanel {
      private String imageFilename = null;
      private Image image = null;
      private Toolkit toolkit = null;
      public ImagePanel() {
        super();
        toolkit = Toolkit.getDefaultToolkit();
      public void setImageFilename(String filename) {
        imageFilename = filename;
        try {
          image = toolkit.createImage(imageFilename);
          setPreferredSize(new Dimension(image.getWidth(this), image.getHeight(this)));
          repaint();
        } catch (Exception e) {
          e.printStackTrace();
          imageFilename = null;
          image = null;
      public Dimension getPreferredSize() {
           if (image == null) return new Dimension(0, 0);
           else return new Dimension(image.getWidth(this), image.getHeight(this));
      protected void paintComponent(Graphics g) {
           Insets insets = getInsets();
           g.setColor(Color.white);
           g.fillRect(0,0, insets.left + getWidth(), insets.top + getHeight());
        if (image != null) {
          g.drawImage(image, insets.top, insets.left, this);
      public void reloadImage() {
           if (imageFilename != null) {
          try {
            image = toolkit.createImage(imageFilename);
            repaint();
          } catch (Exception e) {
            imageFilename = null;
            image = null;
      public static void main(String args[]) {
           JFrame frame = new JFrame();
           frame.addWindowListener(
                new WindowAdapter() {
                     public void windowClosing(WindowEvent we) {
                          System.exit(0);     
           frame.setSize(600, 400);
           JPanel parentPanel = new JPanel();
           parentPanel.setLayout(new GridLayout(1,1));
           JTabbedPane tabPane = new JTabbedPane();
           ImagePanel imagePanel = new ImagePanel();
           JScrollPane scrollPane = new JScrollPane(imagePanel);
           imagePanel.setImageFilename("C:\\dell\\drivers\\R27748\\mrmfiles\\image015.jpg");
           parentPanel.add(scrollPane);
           tabPane.addTab("Tab 1", parentPanel);
           frame.getContentPane().add(tabPane);
           frame.show();
    }

  • Simple question I think, add JPanel to JScrollPane

    I would imagine that for anyone with experience with Java this will be a simple problem. Why can't I add a JPanel to a JScrollPane using myScrollPane.Add(myPanel); ?? it seems to get hidden...
    This works correctly:
         //Create a panel
         JPanel panel = new JPanel(new FlowLayout());
         //Make it pink
         panel.setBackground(Color.pink);
         //Make it 400,400
         panel.setPreferredSize(new Dimension(400,400));
         //Create a Scrollpane
         JScrollPane scrollPane = new JScrollPane(panel);
         //Make it 300,300
         scrollPane.setPreferredSize(new Dimension(300,300));
         //Create a JFrame
         JFrame frame = new JFrame("Test Scrollpane");
         frame.setLayout(new FlowLayout());
         //Set close operation
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         //Set its size
         frame.setSize(600,600);
         //Add Scrollpane to JFrame
         frame.add(scrollPane);
         //Show it
         frame.setVisible(true);
    This doesnt:
         //Create a panel
         JPanel panel = new JPanel(new FlowLayout());
         //Make it pink
         panel.setBackground(Color.pink);
         //Make it 400,400
         panel.setPreferredSize(new Dimension(400,400));
         //Create a Scrollpane
         JScrollPane scrollPane = new JScrollPane();
         scrollPane.add(panel);
         //Make it 300,300
         scrollPane.setPreferredSize(new Dimension(300,300));
         //Create a JFrame
         JFrame frame = new JFrame("Test Scrollpane");
         frame.setLayout(new FlowLayout());
         //Set close operation
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         //Set its size
         frame.setSize(600,600);
         //Add Scrollpane to JFrame
         frame.add(scrollPane);
         //Show it
         frame.setVisible(true);

    rcfearn wrote:
    I would appreciate it you could read the sample code, I am asking the question as to why I have to do this? For structural reasons I don't want to have to add the JPanel during instatiation of the JScrollPane...Please read the [jscrollpane api.|http://java.sun.com/javase/6/docs/api/javax/swing/JScrollPane.html] To display something in a scroll pane you need to add it not to the scroll pane but to its viewport. If you add the component in the scroll pane's constructor, then it will be automatically added to the viewport. if you don't and add the component later, then you must go out of your way to be sure that it is added to the viewport with:
    JScrollPane myScrollPane = new JScrollPane();
    myScrollPane.getViewport().add(myComponent);

  • Jlist / JScrollPane simple question

    Hi all.
    I have a question in general about JList, and in particular about this simple code. The code sets up a list in which the first entry is too long for the width I want the list to be. Is there any way at all to get it to wrap lines? Even if it made that one entry several lines? Would JList be able to handle that at all? Note: I can't make this a JApplet because I want to include this in some larger code that stops working if it's a JApplet. Don't know if that means anything.
    Any help at all is appreciated. If you need clarification, I am happy to try to provide it. I'm a total n00b so you go ahead and patronize me.
       import javax.swing.*;
       import java.awt.*;
       import java.awt.event.*;
       public class StreamsApplet extends java.applet.Applet implements ActionListener {
          private static final String CHARSET = "UTF-8";
          Button add;
          Button remove;
          JList list;
          private DefaultListModel listModel;
          public void init() {
            listModel = new DefaultListModel();
            listModel.addElement("Debbie Scott blablablablablablablablablabla");
            listModel.addElement("Scott Hommel");
            listModel.addElement("Sharon Zakhour");
            listModel.addElement("Debbie Scott");
            listModel.addElement("Scott Hommel");
            listModel.addElement("Sharon Zakhour");
            listModel.addElement("Debbie Scott");
            listModel.addElement("Scott Hommel");
            listModel.addElement("Sharon Zakhour");
            listModel.addElement("Debbie Scott");
            listModel.addElement("Scott Hommel");
            listModel.addElement("Sharon Zakhour");
            listModel.addElement("Debbie Scott");
            listModel.addElement("Scott Hommel");
            listModel.addElement("Sharon Zakhour");
            list = new JList(listModel);
            list.setSelectionMode(
              ListSelectionModel.SINGLE_SELECTION);
            JScrollPane pane = new JScrollPane(list);
            add(pane, BorderLayout.CENTER);
            add = new Button("To 10");
            remove = new Button("To 2");
            JPanel bottomPanel = new JPanel();
            bottomPanel.add(add);
            bottomPanel.add(remove);
            add(bottomPanel, BorderLayout.SOUTH);
            add.addActionListener(this);
            remove.addActionListener(this);
              public void actionPerformed(ActionEvent e) {
                   if (e.getSource() == add)
                     list.setSelectedIndex(10);
              list.ensureIndexIsVisible(10);
              if (e.getSource() == remove)
                   list.setSelectedIndex(2);
                   list.ensureIndexIsVisible(2);
    }

    Everything you need to know, you can find right here:
    http://java.sun.com/docs/books/tutorial/uiswing/components/list.html

  • Need help fast :a question about jcomponent and jscrollpane

    I draw a graphic on a jcomponent like this :
    class drawrecttree extends JComponent {
    public void paint( Graphics g) {
    and I add this to jscrollpane:
    drawrecttree www=new drawrecttree();
    www.k_choose=k_valuenow;
    www.node=currentNode;
    www.setAutoscrolls(true);
    jScrollPane2.setViewportView(www);
    but I hope the jscrollpane can autoscroll,that means jscrollpane's size is 400*400,if the Jcomponent's size is 200*300, just add jcomponent;if jcomponent is bigger than 400*400,the jscrollpane can autoscroll,how can I do that?
    Edited by: hcgerard on Jan 8, 2008 2:18 AM
    Edited by: hcgerard on Jan 8, 2008 2:22 AM
    Edited by: hcgerard on Jan 8, 2008 2:52 AM

    Below is a small non-compilable unit (you need to add a few things of course) - but at any rate, here is some code that, if you get it working, you will see that the scrollbars do the right thing.
    public class TestScrollPane  extends JFrame {
      private Container     container;
      private JPanel        panel;
      private JLabel        label;
      private JScrollPane   scroller;
      public TestScrollPane() {
        container = getContentPane();
        panel     = new JPanel();
        panel.setLayout(new BorderLayout());
        /* Get you images here ...                */
        /* I will call them imageOne and imageTwo */
        label     = new JLabel(new ImageIcon(imageOne));
        panel.add(label);
        scroller  = new JScrollPane(panel);
        scroller.setPreferredSize(new Dimension(100, 100));
        container.add(scroller);
        pack();
        /* Rest of JFrame stuff */
      public static void main(String[] argv)  throws InterruptedException {
        TestScrollPane tsp = new TestScrollPane();
        Thread.sleep(5000);
        tsp.label.setIcon(new ImageIcon(tsp.imageTwo));
        Thread.sleep(5000);
        tsp.label.setIcon(new ImageIcon(tsp.imageOne));
    }

  • Easy question about JScrollPane issue

    The problem is I do not understand why it is not possible, or what I am doing wrong to not be able to initialize a JScrollPane with a variable and call it later, real easy to see in the code below.
    NOTE! I CAN use scrollbars, but only without initializing first, am just trying to understand how to properly do this with initialization or if it is not possible.
    Thank you!!!!
    just look for the First 3 commented sections with stars ******
    import java.awt.Container;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    public class SquareIntegers extends JApplet {
         // set up GUI and calculate squares of integers from 1 to 10
         public void init() ///all variables below are LOCAL, because used only in "init()" if needed elsewhere make above in the CLASS
                             //OR SAVE VALUES between calls to the class's methods
                // get applet's content pane (GUI component display area)
              Container container = getContentPane();
              container.setLayout(new FlowLayout());
              //creaing a layout because I wanted to add a scroll pane
              //container.setLayout(new BorderLayout());
              // JTextArea to display results
              JTextArea outputArea = new JTextArea(8, 8);
              // JScrollPane myscrollbar = new JScrollPane( outputArea ); //********************this is line 27 why does this along with line 33 NOT work????????
              // attach outputArea to container
              container.add( outputArea);
              //container.add( myscrollbar); ******************************this is Line 33 why does this along with line 277 NOT work????????
              container.add(new JScrollPane( outputArea ));//***********this is Line 34, if I comment out 27/33, and just use this, scrollbars
                                                                     // work correctly, but I have heard/seems better to "initialize variables first"
              int result; // store result of call to method square
              String output = ""; // String containing results
              // loop 10 times
                   for ( int counter = 1; counter <= 10; counter++ ) {
                   // calculate square of counter and store in result
                   result = square( counter );           //***********************uses the CUSTOM method from line 44
                   // append result to String output
                   output += "The square of " + counter +
                   " is " + result + "\n";
                   } // end for structure
         outputArea.setText( output ); // place results in JTextArea
    } // end method init
         // square method definition...***** This is a CUSTOM method creation..... if "Math.sqrt" was used, we would not have to do this
         public int square( int y )
         return y * y;      // return square of y this is RETURNED to the statement in "init()" that originally invoked the
                             // "square()" method - in this case line 32, where RESULT invoked the METHOD, so "result" gets the value of RETURN
                             // if it were "public int square()" that means the method does NOT return a value
    The general format of a method definition is
    return-value-type method-name( parameter-list )
    declarations and statements
    including "return;" or "return EXPRESSION;"
         } // end method square ALL METHODS must always be created inside the CLASS definition, as this one is... notice the closing
              // CLASS bracket below
    } // end class SquareIntegers

    Thank you!!!
    I think I understand...... since the JScrollPane already assigned itself to the JTextArea....
    when "adding" to the parent container, the only necessary component to call was in fact the JScrollPane with the container.add( myscrollbar); I do not know if this is correct, but I thank you for your help, because this definitely confused me, back to studying :)
    I have it 100% operational, just posting this to say thank you that it worked, and it will help further my and possibly others understanding of this.

  • A question about JScrollPane

    Hello,
    I would like to create a Swing window that its size is (700,500) and it stores data that is recieved from user.
    The size of input from user is unknown, so I want that there'll be a scrollPane in axes X and Y.
    The problem: scrollPane doesn't fits to the data. How can I solve this?
    public void buildGUI(List<String> classList, Map<String, ClassData> classes)
         JFrame f = new JFrame("C");
         f.getContentPane().add(new JScrollPane(new GraphPanel(classList,classes)));
         f.setSize(700, 500);
         f.setLocationRelativeTo(null);
         f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         f.setVisible(true);
    class GraphPanel extends JPanel
    {     List<String> classList;
         Map<String, ClassData> classes;
         List<InfoRect> nodes;
         Map<InfoRect, String> edgesToBuild;
    public GraphPanel(List<String> classList, Map<String, ClassData> classes)
    { this.classList = classList;
         this.classes = classes;
         //     JLabel label = new JLabel("C");
    // label.setFont(new Font("Serif", Font.BOLD, 28));
    // label.setHorizontalAlignment(0);
         //add(label);
    //setPreferredSize(new Dimension(700,500));
         // super();
    setBackground(Color.WHITE);
    /* JLabel label = new JLabel("A label");
         label.setFont(new Font("Serif", Font.PLAIN, 14));
         label.setForeground(new Color(0xffffdd));
         add(label);*/
    public void paintComponent(Graphics g)
         setPreferredSize(new Dimension(700,500));
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;
         Font font = new Font("Serif", Font.BOLD, 28);
         FontMetrics metrics = g2.getFontMetrics(font);
         int hgt = metrics.getHeight();
    // get the advance of my text in this font and render context
    int adv = metrics.stringWidth("C");
         g2.setFont(font);
         g2.drawString("C", 70, 30);
         setBackground(Color.WHITE);
         printFile(g2);
    Edited by: shira on Dec 30, 2007 5:49 AM

    Your jscrollpane is being created anonymously, and there is no way to set the preferred size of this component. I suggest that you create a jscrollpane variable and that you set the preferred size on this variable. I also suggest that when posting code, you use code tags (by pressing the code button after highlighting your block of code), and I suggest that you paste compilable code. Something like so:
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import javax.swing.BorderFactory;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    class ScrollPaneDemo extends JPanel
        private JTextArea textArea = new JTextArea(20, 120);
        ScrollPaneDemo()
            setLayout(new BorderLayout());
            setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
            textArea.setWrapStyleWord(true);
            textArea.setLineWrap(true);
            fillWithText(textArea);
            JScrollPane myScrollPane = new JScrollPane(textArea);
            //**** this is the key step here ***
            myScrollPane.setPreferredSize(new Dimension(700, 500));
            add(myScrollPane, BorderLayout.CENTER);
        private void fillWithText(JTextArea textArea2)
            for (int i = 0; i < 10; i++)
                for (int j = 0; j < strings.length; j++)
                    textArea2.append(strings[j] + "\n\n");
                textArea2.append("\n");
        private static void createAndShowUI()
            JFrame frame = new JFrame("ScrollPaneDemo");
            frame.getContentPane().add(new ScrollPaneDemo());
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        public static void main(String[] args)
            java.awt.EventQueue.invokeLater(new Runnable()
                public void run()
                    createAndShowUI();
        private String[] strings =
          "Four score and seven years ago our fathers brought forth on this continent a new nation, " +
          "conceived in Liberty, and dedicated to the proposition that all men are created equal.",
          "Now we are engaged in a great civil war, testing whether that nation, or any nation, " +
          "so conceived and so dedicated, can long endure. We are met on a great battle-field of " +
          "that war. We have come to dedicate a portion of that field, as a final resting place for " +
          "those who here gave their lives that that nation might live. It is altogether fitting and " +
          "proper that we should do this.",
          "But, in a larger sense, we can not dedicate�we can not consecrate�we can not hallow�this " +
          "ground. The brave men, living and dead, who struggled here, have consecrated it, far " +
          "above our poor power to add or detract. The world will little note, nor long remember " +
          "what we say here, but it can never forget what they did here. It is for us the living, " +
          "rather, to be dedicated here to the unfinished work which they who fought here have thus " +
          "far so nobly advanced. It is rather for us to be here dedicated to the great task " +
          "remaining before us � that from these honored dead we take increased devotion to that " +
          "cause for which they gave the last full measure of devotion � that we here highly resolve " +
          "that these dead shall not have died in vain � that this nation, under God, shall have a " +
          "new birth of freedom � and that government of the people, by the people, for the people, " +
          "shall not perish from the earth."
    }Edited by: Encephalopathic on Dec 30, 2007 6:54 AM

  • A question regarding JScrollPane

    Here is my minimized code:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class MyTable extends JFrame {
         static JTable table = new JTable(5, 10);
         static JPanel panel = new JPanel(new GridBagLayout());
         static JScrollPane scrollPane = new JScrollPane(panel);
         public MyTable() {
              setCellSize(25);
              panel.add(table);
              add(scrollPane);
         private static void delay() {
              try { Thread.sleep(3000); }
              catch(InterruptedException ex) { }
         private static void setCellSize(int size) {
              table.setRowHeight(size);
              TableColumnModel columns = table.getColumnModel();
              int numberOfColumns = table.getColumnCount();
              for (int i = 0; i < numberOfColumns; i++)
                   columns.getColumn(i).setPreferredWidth(size);
         public static void main(String[] args) {
              MyTable frame = new MyTable();
              frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
              frame.pack();
              frame.setVisible(true);
              delay();
              setCellSize(50);
              // What should be here ?
    }The problem is:
    In the first time the table is shown, the frame is big enough to contain it all without the help of the scroll bar. But, if change the size of table's cells, the frame's size doesn't change dynamically. How can I tell the frame to change it's size dynamically after each change in size of cells, such that the scroll bar appears if and only if the table is big enough and there is no enough place in the frame to show the whole table ?

    Thanks camickr !
    I decided to do it in the following way, because I have a couple of tables in the panel:scrollPane.setPreferredSize(panel.getPreferredSize());
    frame.pack();but this is almost a perfect result. As you can see the last row and column partially covered by the scroll bars.
    1) How should I fix it so I will not see the scroll bars ?
    2) If I change the cell size to 150 instead of 50, frame's size becomes too large so the horizontal scroll bar disappears and only half of the vectical scroll bar seemed. What should I add to my program such that in this case the I'll see the whole two scroll bars (or maybe to maximize the frame) ?
    Thanks again !
    Here is my current version of code:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class MyTable extends JFrame {
         static JTable table = new JTable(5, 10);
         static JPanel panel = new JPanel(new GridBagLayout());
         static JScrollPane scrollPane = new JScrollPane(panel);
         public MyTable() {
              setCellSize(25);
              panel.add(table);
              add(scrollPane);
         private static void delay() {
              try { Thread.sleep(2000); }
              catch(InterruptedException ex) { }
         private static void setCellSize(int size) {
              table.setRowHeight(size);
              TableColumnModel columns = table.getColumnModel();
              int numberOfColumns = table.getColumnCount();
              for (int i = 0; i < numberOfColumns; i++)
                   columns.getColumn(i).setPreferredWidth(size);
         public static void main(String[] args) {
              MyTable frame = new MyTable();
              frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
              frame.pack();
              frame.setVisible(true);
              delay();
              setCellSize(50);
              scrollPane.setPreferredSize(panel.getPreferredSize());
              frame.pack();
    }

  • Question about JScrollPane

    Hi everybody,
    I'm using HSQLDB in my program and users can execute custom queries with a JTextArea. When an exception is thrown during the excecution of a big query, the message is pretty large, because it contains the query itself and the warnings/remarks about it.
    What I wanted to do was to use a JOptionPane and add the message to the JOptionPane inside a JScrollPane. I want the maximum size of the JScrollPane to be 320 x 160. This is what I'm doing now:
    Dimension size = new Dimension(320, 160);
    JLabel label = new JLabel(exception.getMessage());
    JScrollPane scrollPane = new JScrollPane();
    scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    scrollPane.getViewport().setLayout(new FlowLayout(0, 0, FlowLayout.LEFT));
    scrollPane.getViewport().add(label);
    scrollPane.getViewport().setMinimumSize(size);
    scrollPane.getViewport().setMaximumSize(size);
    scrollPane.getViewport().setPreferredSize(size);
    scrollPane.getViewport().setSize(size);
    scrollPane.getViewport().setBackground(Color.WHITE);
    JOptionPane.showMessageDialog(null, scrollPane, "Error", JOptionPane.ERROR_MESSAGE);I want no horizontal scrollbar, only a vertical. The problem with the code above is that the message stands on one line, instead to be spread on more then one line (thereby, you cannot see the message completely, because the horizontal scrollbar is disabled).
    The result I want is that the message is spread over more then one line, like in HTML when you've got a long text, the browser itself will spread the text over several lines that are available in the container where the text is in.
    Does somebody understand my problem? :-) I wish I could upload an image as an example, but FTP is blocked on the network where I'm connected to.
    Kind regards,
    Sweepee.
    Message was edited by:
    Sweepee

    see if this gets you close
    import java.awt.*;
    import javax.swing.*;
    class Testing
      public static void main(String[] args)
        JTextArea ta = new JTextArea();
        ta.setLineWrap(true);
        ta.setWrapStyleWord(true);
        ta.setText("I want no horizontal scrollbar, only a vertical. The problem with the"+
        " code above is that the message stands on one line, instead to be spread on more"+
        " then one line (thereby, you cannot see the message completely, because the"+
        " horizontal scrollbar is disabled).\n\nThe result I want is that the message is"+
        " spread over more then one line, like in HTML when you've got a long text, the"+
        " browser itself will spread the text over several lines that are available in the"+
        " container where the text is in.\n\nDoes somebody understand my problem? :-) I wish"+
        " I could upload an image as an example, but FTP is blocked on the network where I'm connected to.");
        JScrollPane scrollPane = new JScrollPane(ta);
        scrollPane.setPreferredSize(new Dimension(320, 160));
        JOptionPane.showMessageDialog(null, scrollPane, "Error", JOptionPane.ERROR_MESSAGE);
        System.exit(0);
    }

  • Simple question about JScrollPane

    Here is my source code(A combination of trial and error from previous topic threads). It works, but I would like it to work by being able to call a new object by itself, ie the main method would be public static void main (String[]args){new O();}. The reason why I am asking this is because I have no idea how to add buttons, panels, etc to this!
    Anyone?
    class O extends JPanel
    O()
    super();
    super.setPreferredSize( new Dimension (5000,5000) );;;
    super.setBackground( new Color(20,10,156) );
    public static void main(String[] args)
              O instance = new O();
    JFrame frame = new JFrame();
    frame.getContentPane().setLayout(new BorderLayout());
    JScrollPane pane = new JScrollPane(instance);
    frame.getContentPane().add(pane, BorderLayout.CENTER);
              frame.setSize(1024,768);
    frame.setVisible(true);
         public void paint(Graphics g)
    super.paint(g);
    g.drawLine(0,0,5000,5000);
    g.drawLine(5000,5000,0,0);

    Take a lot at the Swing tutorial on "How to Use Scroll
    Panes":
    http://java.sun.com/docs/books/tutorial/uiswing/compone
    ts/scrollpane.html
    There is a section in the tutorial for every Swing
    components. Take the time to read the entire tutorial.

  • Newbie question - Applying SpringLayout to a JScrollPane

    I have created a JTree and its associated nodes. I want to add my Jtree to a JFrame and manage the position of the tree using a SpringLayout. I added the JTree to a JScrollPane and tried to use SpringLayout to manage the layout of the JScrollPane. However, my JScrollPane always gets stuck in the top right-hand corner of the frame. My code is below. Any suggestions?
    public SimpleTree(JFrame frame, SpringLayout layout)
    DefaultMutableTreeNode top =
    new DefaultMutableTreeNode("The World");
    Container contentPane = frame.getContentPane();
    contentPane.setLayout(layout);
    CreateNodes(top);
    JTree tree = new JTree(top);
    tree.getSelectionModel().setSelectionMode
    (TreeSelectionModel.SINGLE_TREE_SELECTION);
    JScrollPane treeView = new JScrollPane(tree);
    treeView.setHorizontalScrollBarPolicy(
    ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    treeView.setVerticalScrollBarPolicy(
    ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
    //JPanel treePanel = new JPanel();
    //treePanel.add(treeView);
    contentPane.add(treeView);
    contentPane.setBounds(100,100,50,50);
    //tree.setSize(100,100);
    //treePanel.setSize(treeView.getSize());
    Spring s = Spring.constant(100,300,800);
    layout.putConstraint(SpringLayout.EAST, contentPane, s, SpringLayout.EAST, treeView);
    layout.putConstraint(SpringLayout.WEST, contentPane, s, SpringLayout.WEST, treeView);
    //layout.putConstraint(SpringLayout.NORTH, contentPane, s, SpringLayout.NORTH, treePanel);
    //layout.putConstraint(SpringLayout.SOUTH, contentPane, s, SpringLayout.SOUTH, treePanel);
    frame.pack();
    frame.setVisible(true);
    }

    bsampieri, thank you very much for your response.
    So layout managers only work in panels? Not frames? For example, I have a JTree that I put inside a JScrollPane. I also have some other components that I want to share the same frame (window). So in order to do this, I should place all my components inside a panel and assign a layout manager, such as SpringLayout to my panel. Then place the panel inside of my frame.
    Rather than adding my components inside a JFrame and assigning a layout manager to manage the component positions inside the JFrame.
    Does this sound correct?

Maybe you are looking for

  • Why does Firefox not open my windows and tabs from last time until I have tried starting 3 or 4 times?

    I have this problem with opening Firefox: My Startup options are set to "When Firefox starts: Show my windows and tabs from last time" However, each time I start Firefox, by clicking the icon in the Taskbar, it opens with a single blank tab. I repeat

  • Cost of Good Sold (COGS) in Project

    Dear All What is concept of COGS calculate in Project? How it calculate for Material & Services? When the order is complete, the Material stock is transfer to the customer site at this point no COGS should be recognized. When the installation is comp

  • OCI compliance with SSP4

    I need to know if SSP4 is OCI compliant (Open Catalog Interface) because I will need to connect to a Central Catalog from a distant entity. And, in order to connect through a direct line (leased line or Private Network), I have been told that my ePro

  • In IC_Auto business role Toolbar buttons not visible

    Hi,    In my project for IC_Auto role the buttons in the toolbar is not visible. we have not modified any thing to standard. Any notes to be updated ? With regards, selvam

  • 7.3.1 Issues

    I installed Firmware 7.3.1 on my Time Capsule and Airport Extreme this afternoon and now I am experiencing "lag" when browsing web sites. This is the case on wired and wireless machines using Safari or Firefox. If I go to a website the page will load