ScrollPane

What would be the Action Script for a ScrollPane in Flash 8
or CS3.
I know I keep bothering but I am lost. I'm going to try and
explain as best as possible, and in short. This is what I did.
1. I watched your how to create a "photo gallery and
thumbnails" tutorial and "make a web textbox and save for html"
tutorial.
2. I created a flash file with web textboxes (dimensions
6x5in) I created in photoshop that was saved as a jpegs, 15 in
total. I just dupilicated the actual one once in flash. Inside of
the textbox I placed scrolling text and set it to dynamic text and
multiline.
3. There are 15 thumbnails(tabs, with dimensions 1.25x.5)
that I need for for those 15 textboxes. On the side of the textbox
I placed a ScrollPane box (dimensions 1.25x4).
5. The ScrollPane works, the web textbox is there. But when I
click on the thumbnail it doesnt go to the next movie (web
textbox). Do I need to add a a movie script to the ScrollPane or a
movie to the actual textbox I created inside of the web
textbox.

Why?
Does the ScrollPane appears only if the contentPane layout is BorderLayout??
I d like to have the JList component inside the orderBillPanel with the latter including a JScrollPane.
I ve changed it as you suggested but I do not see the JScrollPane.
I am getting more confused now.
I have done it many times in the past. Why does not work??
Any advice?
private void jbInit() throws Exception {
border1 = BorderFactory.createEtchedBorder(Color.white,new Color(165, 163, 151));
//setIconImage(Toolkit.getDefaultToolkit().createImage(Frame1.class.getResource("[Your Icon]")));
contentPane = (JPanel) this.getContentPane();
contentPane.setLayout(new BorderLayout());
contentPane.add(orderBillPanel, BorderLayout.CENTER);
this.setTitle("PointOfSaleX");
this.setSize(new Dimension(1100, 800));
orderBillPanel.setLayout(null);
listModel = new DefaultListModel();
//Create the list and put it in a scroll pane.
list = new JList(listModel);
list.setBounds(new Rectangle(0, 0, 412, 456));
list.setBackground(Color.yellow);
list.setFont(new java.awt.Font("Dialog", 0, 14));
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setSelectedIndex(0);
orderBillPanel.add(list);
list.setVisibleRowCount(5);
JScrollPane scr = new JScrollPane(list);
scr.setBounds(new Rectangle(0, 0, 425, 230));
orderBillPanel.add(scr);
}

Similar Messages

  • Custom graphics in java.awt.ScrollPane

    Hi all,
    I have to draw a custom created image in a scroll pane. As the image is very large I want to display it in a scroll pane. As parts of the image may change within seconds, and drawing the whole image is very time consuming (several seconds) I want to draw only the part of the image that is currently visible to the user.
    My idea: creating a new class that extends from java.awt.ScrollPane, overwrite the paint(Graphics) method and do the drawings inside. Unfortunately, it does not work. The background of the scoll pane is blue, but it does not show the red box (the current viewport is not shown in red).
    Below please find the source code that I am using:
    package graphics;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.ScrollPane;
    import java.awt.event.AdjustmentEvent;
    public class CMyComponent extends ScrollPane {
         /** <p>Listener to force a component to repaint when a scroll bar changes its
          * position.</p>
         private final class ScrollBarAdjustmentListener implements java.awt.event.AdjustmentListener {
              /** <p>The component to force to repaint.</p> */
              private final Component m_Target;
              /** <p>Default constructor.</p>
               * @param Target The component to force to repaint.
              private ScrollBarAdjustmentListener(Component Target) { m_Target = Target; }
              /** <p>Forces to component to repaint upon adjustment of the scroll bar.</p>
               *  @see java.awt.event.AdjustmentListener#adjustmentValueChanged(java.awt.event.AdjustmentEvent)
              public void adjustmentValueChanged(AdjustmentEvent e) { m_Target.paint(m_Target.getGraphics()); }
         public CMyComponent() {
              // Ensure that the component repaints upon changing of the scroll bars
              ScrollBarAdjustmentListener sbal = new ScrollBarAdjustmentListener(this);
              getHAdjustable().addAdjustmentListener(sbal);
              getVAdjustable().addAdjustmentListener(sbal);
         public void paint(Graphics g) {
              setBackground(Color.BLUE);
              g.setColor(Color.RED);
              g.fillRect(getScrollPosition().x, getScrollPosition().y, getViewportSize().width, getViewportSize().height);
         public final static void main(String[] args) {
              java.awt.Frame f = new java.awt.Frame();
              f.add(new CMyComponent());
              f.pack();
              f.setVisible(true);
    }

    Dear all,
    I used the last days and tried several things. I think now I have a quite good working solution (just one bug remains) and it is very performant. To give others a chance to see what I have done I post the source code of the main class (a canvas drawing and implementing scrolling) here. As soon as the sourceforge project is accepted, I will publish the whole sources at there. Enjoy. And if you have some idea for my last bug in getElementAtPixel(Point), then please tell me.
    package internetrail.graphics.hexgrid;
    import java.awt.Canvas;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Image;
    import java.awt.Point;
    import java.awt.Polygon;
    import java.awt.event.ComponentEvent;
    import java.awt.event.ComponentListener;
    import java.awt.geom.Area;
    import java.awt.image.BufferedImage;
    import java.util.WeakHashMap;
    import java.util.Map;
    /** <p>Hex grid view.</p>
    * <p>Visualizes a {@link IHexGridModel}.</p>
    * @version 0.1, 03.06.2006
    * @author Bjoern Wuest, Germany
    public final class CHexGridView extends Canvas implements ComponentListener, IHexGridElementListener {
         /** <p>Serial version unique identifier.</p> */
         private static final long serialVersionUID = -965902826101261530L;
         /** <p>Instance-constant parameter for the width of a hex grid element.</p> */
         public final int CONST_Width;
         /** <p>Instance-constant parameter for 1/4 of the width of a hex grid element.</p> */
         public final int CONST_Width1fourth;
         /** <p>Instance-constant parameter for 3/4 of the width of a hex grid element.</p> */
         public final int CONST_Width3fourth;
         /** <p>Instance-constant parameter for 1.5 times of the width of a hex grid element.</p> */
         public final int CONST_Width1dot5;
         /** <p>Instance-constant parameter for 4 times of the width of a hex grid element.</p> */
         public final int CONST_Widthquad;
         /** <p>Instance-constant parameter for the height of a hex grid element.</p> */
         public final int CONST_Height;
         /** <p>Instance-constant parameter for 1/2 of the height of a hex grid element.</p> */
         public final int CONST_Heighthalf;
         /** <p>Instance-constant parameter for the double height of a hex grid element.</p> */
         public final int CONST_Heightdouble;
         /** <p>The steepness of a side of the hex grid element (calculated for the upper left arc).</p> */
         public final double CONST_Steepness;
         /** <p>The model of this hex grid </p> */
         private final IHexGridModel m_Model;
         /** <p>A cache for already created images of the hex map.</p> */
         private final Map<Point, Image> m_Cache = new WeakHashMap<Point, Image>();
         /** <p>The graphical area to draw the selection ring around a hex element.</p> */
         private final Area m_SelectionRing;
         /** <p>The image of the selection ring around a hex element.</p> */
         private final BufferedImage m_SelectionRingImage;
         /** <p>The current position of the hex grid in pixels (top left visible corner).</p> */
         private Point m_ScrollPosition = new Point(0, 0);
         /** <p>Flag to define if a grid is shown ({@code true}) or not ({@code false}).</p> */
         private boolean m_ShowGrid = true;
         /** <p>Flag to define if the selected hex grid element should be highlighted ({@code true}) or not ({@code false}).</p> */
         private boolean m_ShowSelected = true;
         /** <p>The offset of hex grid elements shown on the screen, measured in hex grid elements.</p> */
         private Point m_CurrentOffset = new Point(0, 0);
         /** <p>The offset of the image shown on the screen, measured in pixels.</p> */
         private Point m_PixelOffset = new Point(0, 0);
         /** <p>The index of the currently selected hex grid element.</p> */
         private Point m_CurrentSelected = new Point(0, 0);
         /** <p>The width of a buffered pre-calculated image in pixel.</p> */
         private int m_ImageWidth;
         /** <p>The height of a buffered pre-calculated image in pixel.</p> */
         private int m_ImageHeight;
         /** <p>The maximum number of columns of hex grid elements to be shown at once on the screen.</p> */
         private int m_MaxColumn;
         /** <p>The maximum number of rows of hex grid elements to be shown at once on the screen.</p> */
         private int m_MaxRow;
         /** <p>Create a new hex grid view.</p>
          * <p>The hex grid view is bound to a {@link IHexGridModel} and registers at
          * that model to listen for {@link IHexGridElement} updates.</p>
          * @param Model The model backing this view.
         public CHexGridView(IHexGridModel Model) {
              // Set the model
              m_Model = Model;
              CONST_Width = m_Model.getElementsWidth();
              CONST_Height = m_Model.getElementsHeight();
              CONST_Width1fourth = CONST_Width/4;
              CONST_Width3fourth = CONST_Width*3/4;
              CONST_Width1dot5 = CONST_Width*3/2;
              CONST_Heighthalf = CONST_Height/2;
              CONST_Widthquad = CONST_Width*4;
              CONST_Heightdouble = CONST_Height*2;
              CONST_Steepness = (double)CONST_Heighthalf / CONST_Width1fourth;
              m_ImageWidth = getSize().width+CONST_Widthquad;
              m_ImageHeight = getSize().height+CONST_Heightdouble;
              m_MaxColumn = m_ImageWidth / CONST_Width3fourth;
              m_MaxRow = m_ImageHeight / CONST_Height;
              // Register this canvas for various notifications
              m_Model.addElementListener(this);
              addComponentListener(this);
              // Create the selection ring to highlight hex grid elements
              m_SelectionRing = new Area(new Polygon(new int[]{-1, CONST_Width1fourth-1, CONST_Width3fourth+1, CONST_Width+1, CONST_Width3fourth+1, CONST_Width1fourth-1}, new int[]{CONST_Heighthalf, -1, -1, CONST_Heighthalf, CONST_Height+1, CONST_Height+1}, 6));
              m_SelectionRing.subtract(new Area(new Polygon(new int[]{2, CONST_Width1fourth+2, CONST_Width3fourth-2, CONST_Width-2, CONST_Width3fourth-2, CONST_Width1fourth+2}, new int[]{CONST_Heighthalf, 2, 2, CONST_Heighthalf, CONST_Height-2, CONST_Height-2}, 6)));
              m_SelectionRingImage = new BufferedImage(CONST_Width, CONST_Height, BufferedImage.TYPE_INT_ARGB);
              Graphics2D g = m_SelectionRingImage.createGraphics();
              g.setColor(Color.WHITE);
              g.fill(m_SelectionRing);
         @Override public synchronized void paint(Graphics g2) {
              // Caculate the offset of indexes to show
              int offsetX = 2 * (m_ScrollPosition.x / CONST_Width1dot5) - 2;
              int offsetY = (int)(Math.ceil(m_ScrollPosition.y / CONST_Height) - 1);
              m_CurrentOffset = new Point(offsetX, offsetY);
              // Check if the image is in the cache
              Image drawing = m_Cache.get(m_CurrentOffset);
              if (drawing == null) {
                   // The image is not cached, so draw it
                   drawing = new BufferedImage(m_ImageWidth, m_ImageHeight, BufferedImage.TYPE_INT_ARGB);
                   Graphics2D g = ((BufferedImage)drawing).createGraphics();
                   // Draw background
                   g.setColor(Color.BLACK);
                   g.fillRect(0, 0, m_ImageWidth, m_ImageHeight);
                   // Draw the hex grid
                   for (int column = 0; column <= m_MaxColumn; column += 2) {
                        for (int row = 0; row <= m_MaxRow; row++) {
                             // Draw even column
                             IHexGridElement element = m_Model.getElementAt(offsetX + column, offsetY + row);
                             if (element != null) { g.drawImage(element.getImage(m_ShowGrid), (int)(column*(CONST_Width3fourth-0.5)), CONST_Height*row, null); }
                             // Draw odd column
                             element = m_Model.getElementAt(offsetX + column+1, offsetY + row);
                             if (element!= null) { g.drawImage(element.getImage(m_ShowGrid), (int)(column*(CONST_Width3fourth-0.5)+CONST_Width3fourth), CONST_Heighthalf*(row*2+1), null); }
                   // Put the image into the cache
                   m_Cache.put(m_CurrentOffset, drawing);
              // Calculate the position of the image to show
              offsetX = CONST_Width1dot5 + (m_ScrollPosition.x % CONST_Width1dot5);
              offsetY = CONST_Height + (m_ScrollPosition.y % CONST_Height);
              m_PixelOffset = new Point(offsetX, offsetY);
              g2.drawImage(drawing, -offsetX, -offsetY, null);
              // If the selected element should he highlighted, then do so
              if (m_ShowSelected) {
                   // Check if the selected element is on screen
                   if (isElementOnScreen(m_CurrentSelected)) {
                        // Correct vertical offset for odd columns
                        if ((m_CurrentSelected.x % 2 == 1)) { offsetY -= CONST_Heighthalf; }
                        // Draw the selection circle
                        g2.drawImage(m_SelectionRingImage, (m_CurrentSelected.x - m_CurrentOffset.x) * CONST_Width3fourth - offsetX - ((m_CurrentSelected.x + 1) / 2), (m_CurrentSelected.y - m_CurrentOffset.y) * CONST_Height - offsetY, null);
         @Override public synchronized void update(Graphics g) { paint(g); }
         public synchronized void componentResized(ComponentEvent e) {
              // Upon resizing of the component, adjust several pre-calculated values
              m_ImageWidth = getSize().width+CONST_Widthquad;
              m_ImageHeight = getSize().height+CONST_Heightdouble;
              m_MaxColumn = m_ImageWidth / CONST_Width3fourth;
              m_MaxRow = m_ImageHeight / CONST_Height;
              // And flush the cache
              m_Cache.clear();
         public void componentMoved(ComponentEvent e) { /* do nothing */ }
         public void componentShown(ComponentEvent e) { /* do nothing */ }
         public void componentHidden(ComponentEvent e) { /* do nothing */ }
         public synchronized void elementUpdated(IHexGridElement Element) {
              // Clear cache where the element may be contained at
              for (Point p : m_Cache.keySet()) { if (isElementInScope(Element.getIndex(), p, new Point(p.x + m_MaxColumn, p.y + m_MaxRow))) { m_Cache.remove(p); } }
              // Update the currently shown image if the update element is shown, too
              if (isElementOnScreen(Element.getIndex())) { repaint(); }
         /** <p>Returns the model visualized by this grid view.</p>
          * @return The model visualized by this grid view.
         public IHexGridModel getModel() { return m_Model; }
         /** <p>Returns the current selected hex grid element.</p>
          * @return The current selected hex grid element.
         public IHexGridElement getSelected() { return m_Model.getElementAt(m_CurrentSelected.x, m_CurrentSelected.y); }
         /** <p>Sets the current selected hex grid element by its index.</p>
          * <p>If the selected hex grid element should be highlighted and is currently
          * shown on the screen, then this method will {@link #repaint() redraw} this
          * component automatically.</p>
          * @param Index The index of the hex grid element to become the selected one.
          * @throws IllegalArgumentException If the index refers to a non-existing hex
          * grid element.
         public synchronized void setSelected(Point Index) throws IllegalArgumentException {
              // Check that the index is valid
              if ((Index.x < 0) || (Index.y < 0) || (Index.x > m_Model.getXElements()) || (Index.y > m_Model.getYElements())) { throw new IllegalArgumentException("There is no hex grid element with such index."); }
              m_CurrentSelected = Index;
              // If the element is on screen and should be highlighted, then repaint
              if (m_ShowSelected && isElementOnScreen(m_CurrentSelected)) { repaint(); }
         /** <p>Moves the visible elements to the left by the number of pixels.</p>
          * <p>To move the visible elements to the left by one hex grid element, pass
          * {@link #CONST_Width3fourth} as the parameter. The component will
          * automatically {@link #repaint()}.</p>
          * @param Pixels The number of pixels to move to the left.
          * @return The number of pixels moved to the left. This is always between 0
          * and {@code abs(Pixels)}.
         public synchronized int moveLeft(int Pixels) {
              int delta = m_ScrollPosition.x - Math.max(0, m_ScrollPosition.x - Math.max(0, Pixels));
              if (delta != 0) {
                   m_ScrollPosition.x -= delta;
                   repaint();
              return delta;
         /** <p>Moves the visible elements up by the number of pixels.</p>
          * <p>To move the visible elements up by one hex grid element, pass {@link
          * #CONST_Height} as the parameter. The component will automatically {@link
          * #repaint()}.</p>
          * @param Pixels The number of pixels to move up.
          * @return The number of pixels moved up. This is always between 0 and {@code
          * abs(Pixels)}.
         public synchronized int moveUp(int Pixels) {
              int delta = m_ScrollPosition.y - Math.max(0, m_ScrollPosition.y - Math.max(0, Pixels));
              if (delta != 0) {
                   m_ScrollPosition.y -= delta;
                   repaint();
              return delta;
         /** <p>Moves the visible elements to the right by the number of pixels.</p>
          * <p>To move the visible elements to the right by one hex grid element, pass
          * {@link #CONST_Width3fourth} as the parameter. The component will
          * automatically {@link #repaint()}.</p>
          * @param Pixels The number of pixels to move to the right.
          * @return The number of pixels moved to the right. This is always between 0
          * and {@code abs(Pixels)}.
         public synchronized int moveRight(int Pixels) {
              int delta = Math.min(m_Model.getXElements() * CONST_Width3fourth + CONST_Width1fourth - getSize().width, m_ScrollPosition.x + Math.max(0, Pixels)) - m_ScrollPosition.x;
              if (delta != 0) {
                   m_ScrollPosition.x += delta;
                   repaint();
              return delta;
         /** <p>Moves the visible elements down by the number of pixels.</p>
          * <p>To move the visible elements down by one hex grid element, pass {@link
          * #CONST_Height} as the parameter. The component will automatically {@link
          * #repaint()}.</p>
          * @param Pixels The number of pixels to move down.
          * @return The number of pixels moved down. This is always between 0 and
          * {@code abs(Pixels)}.
         public synchronized int moveDown(int Pixels) {
              int delta = Math.min(m_Model.getYElements() * CONST_Height + CONST_Heighthalf - getSize().height, m_ScrollPosition.y + Math.max(0, Pixels)) - m_ScrollPosition.y;
              if (delta != 0) {
                   m_ScrollPosition.y += delta;
                   repaint();
              return delta;
         /** <p>Checks if the hex grid element of the given index is currently
          * displayed on the screen (even just one pixel).</p>
          * <p>The intention of this method is to check if a {@link #repaint()} is
          * necessary or not.</p>
          * @param ElementIndex The index of the element to check.
          * @return {@code true} if the hex grid element of the given index is
          * displayed on the screen, {@code false} if not.
         public synchronized boolean isElementOnScreen(Point ElementIndex) { return isElementInScope(ElementIndex, m_CurrentOffset, new Point(m_CurrentOffset.x + m_MaxColumn, m_CurrentOffset.y + m_MaxRow)); }
         /** <p>Checks if the hex grid element of the given index is within the given
          * indexes.</p>
          * <p>The intention of this method is to check if a {@link #repaint()} is
          * necessary or not.</p>
          * @param ElementIndex The index of the element to check.
          * @param ReferenceIndexLeftTop The left top index of the area to check.
          * @param ReferenceIndexRightBottom The right bottom index of the area to check.
          * @return {@code true} if the hex grid element of the given index is within
          * the given area, {@code false} if not.
         public synchronized boolean isElementInScope(Point ElementIndex, Point ReferenceIndexLeftTop, Point ReferenceIndexRightBottom) { if ((ElementIndex.x >= ReferenceIndexLeftTop.x) && (ElementIndex.x <= ReferenceIndexRightBottom.x) && (ElementIndex.y >= ReferenceIndexLeftTop.y) && (ElementIndex.y <= (ReferenceIndexRightBottom.y))) { return true; } else { return false; } }
         /** <p>Return the {@link IHexGridElement hex grid element} shown at the given
          * pixel on the screen.</p>
          * <p><b>Remark: There seems to be a bug in retrieving the proper element,
          * propably caused by rounding errors and unprecise pixel calculations.</p>
          * @param P The pixel on the screen.
          * @return The {@link IHexGridElement hex grid element} shown at the pixel.
         public synchronized IHexGridElement getElementAtPixel(Point P) {
              // @FIXME Here seems to be some bugs remaining
              int dummy = 0; // Variable for warning to indicate that there is something to do :)
              // Calculate the pixel on the image, not on the screen
              int px = P.x + m_PixelOffset.x;
              int py = P.y + m_PixelOffset.y;
              // Determine the x-index of the column (is maybe decreased by one)
              int x = px / CONST_Width3fourth + m_CurrentOffset.x;
              // If the column is odd, then shift the y-pixel by half element height
              if ((x % 2) == 1) { py -= CONST_Heighthalf; }
              // Determine the y-index of the row (is maybe decreased by one)
              int y = py / CONST_Height + m_CurrentOffset.y;
              // Normative coordinates to a single element
              px -= (x - m_CurrentOffset.x) * CONST_Width3fourth;
              py -= (y - m_CurrentOffset.y) * CONST_Height;
              // Check if the normative pixel is in the first quarter of a column
              if (px < CONST_Width1fourth) {
                   // Adjustments to the index may be necessary
                   if (py < CONST_Heighthalf) {
                        // We are in the upper half of a hex-element
                        double ty = CONST_Heighthalf - CONST_Steepness * px;
                        if (py < ty) { x--; }
                   } else {
                        // We are in the lower half of a hex-element
                        double ty = CONST_Heighthalf + CONST_Steepness * px;
                        if (py > ty) {
                             x--;
                             y++;
              return m_Model.getElementAt(x, y);
    }Ah, just to give you some idea: I use this component to visualize a hex grid map with more than 1 million grid elements. And it works, really fast, and requires less than 10 MByte of memory.

  • Design problem(split pane scrollpane Insets)

    hi,
    doing a exam simulator prgm
    design is like,
    Question (text area with scrollpane)
    Answers (checkbox inside panel with scrollpane)
    used split pane between qst and ans but big thick bar comes how to reduce size and it is not
    moving.
    used GridLayout for container and panel.
    PROBLEM is how to leave space qst textarea appears from very left edge of screen how to leave some space
    same prblm for checkbox they to appear extreme left on screen.

    Put those components in a JPanel overwriting the getInsets() method like this:
    JPanel cPane=new JPanel(){
        private final Insets _insets=new Insets(10,10,10,10);
        public Insets getInsets(){
            return _insets;
    };...should do the trick, take a look at the Insets class if you need information on how defining it...

  • Problem with ScrollPane and JFrame Size

    Hi,
    The code is workin but after change the size of frame it works CORRECTLY.Please help me why this frame is small an scrollpane doesn't show at the beginning.
    Here is the code:
    import java.awt.*;
    public class canvasExp extends Canvas
         private static final long serialVersionUID = 1L;
         ImageLoader map=new ImageLoader();
        Image img = map.GetImg();
        int h, w;               // the height and width of this canvas
         public void update(Graphics g)
            paint(g);
        public void paint(Graphics g)
                if(img != null)
                     h = getSize().height;
                     System.out.println("h:"+h);
                      w = getSize().width;
                      System.out.println("w:"+w);
                      g.drawRect(0,0, w-1, h-1);     // Draw border
                  //  System.out.println("Size= "+this.getSize());
                     g.drawImage(img, 0,0,this.getWidth(),this.getHeight(), this);
                    int width = img.getWidth(this);
                    //System.out.println("W: "+width);
                    int height = img.getHeight(this);
                    //System.out.println("H: "+height);
                    if(width != -1 && width != getWidth())
                        setSize(width, getHeight());
                    if(height != -1 && height != getHeight())
                        setSize(getWidth(), height);
    }I create frame here...
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.JFrame;
    public class frame extends JFrame implements MouseMotionListener,MouseListener
         private static final long serialVersionUID = 1L;
        private ScrollPane scrollPane;
        private int dragStartX;
        private int dragStartY;
        private int lastX;
        private int lastY;
        int cordX;
        int cordY;
        canvasExp canvas;
        public frame()
            super("test");
            canvas = new canvasExp();
            canvas.addMouseListener(this);
            canvas.addMouseMotionListener(this);
            scrollPane = new ScrollPane();
            scrollPane.setEnabled(true);
            scrollPane.add(canvas);
            add(scrollPane);
            setSize(300,300);
            pack();
            setVisible(true);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        public void mousePressed(MouseEvent e)
            dragStartX = e.getX();
            dragStartY = e.getY();
            lastX = getX();
            lastY = getY();
        public void mouseReleased(MouseEvent mouseevent)
        public void mouseClicked(MouseEvent e)
            cordX = e.getX();
            cordY = e.getY();
            System.out.println((new StringBuilder()).append(cordX).append(",").append(cordY).toString());
        public void mouseEntered(MouseEvent mouseevent)
        public void mouseExited(MouseEvent mouseevent)
        public void mouseMoved(MouseEvent mouseevent)
        public void mouseDragged(MouseEvent e)
            if(e.getX() != lastX || e.getY() != lastY)
                Point p = scrollPane.getScrollPosition();
                p.translate(dragStartX - e.getX(), dragStartY - e.getY());
                scrollPane.setScrollPosition(p);
    }...and call here
    public class main {
         public main(){}
         public static void main (String args[])
             frame f = new frame();
    }There is something I couldn't see here.By the way ImageLoader is workin I get the image.
    Thank you for your help,please answer me....

    I'm not going to even attempt to resolve the problem posted. There are other problems with your code that should take priority.
    -- class names by convention start with a capital letter.
    -- don't use the name of a common class from the standard API for your custom class, not even with a difference of case. It'll come back to bite you.
    -- don't mix awt and Swing components in the same GUI. Change your class that extends Canvas to extend JPanel instead, and override paintComponent(...) instead of paint(...).
    -- launch your GUI on the EDT by wrapping it in a SwingUtilities.invokeLater or EventQueue.invokeLater.
    -- calling setSize(...) followed by pack() is meaningless. Use one or the other.
    -- That's not the correct way to display a component in a scroll pane.
    Ah, well, and the problem is that when you call pack(), it retrieves the preferredSize of the components in the JFrame, and you haven't set a preferredSize for the scroll pane.
    Please, for your own good, take a break from whatever it is you're working on and go through The Java&#8482; Tutorials: [Creating a GUI with JFC/Swing|http://java.sun.com/docs/books/tutorial/uiswing/TOC.html]
    db

  • Problem with drawing in a scrollpane using clipbounds

    Hello
    Setup is a JFrame containing a splitpane with on the left just some config buttons and on the right a scrollpane.
    Inside the scrollpane I want to draw big waveforms.
    This is represented by a long array of 1's and 0's for the Y coordinates.
    On drawing in paintComponents method I allways reconstruct a GeneralPath, based on the Clipbouns returned by the Graphics variable.
    I have to reconstruct the GeneralPath polygon because my data can be millions long. And therefor I have to limit the points that are drawn.
    When I allways reconstruct this GeneralPath, upon scrolling the polygon is shown scrappy, as in the line connecting the points will only be half shown or almost not.
    Resizing the window or just minimize maximize and it is shown ok.
    I do not have this problem when the GeneralPath I construct is only once made upfront and never remade in the paintComponent method.
    But as I need the clipbounds to know which part to construct I need to rebuild this polygon over and over again.
    I have tried to draw it with Line2D.Double but I get almost the same effect, parts of the lines not being drawn ok.
    Below is the code of the Panel inside the ScrollPane responsible for this drawing.
    public class Usr_Test_L extends JPanel
      final static Color bg   = Color.black;
      final static Color fg   = Color.white;
      final static Color wave = Color.red;
      final static Color txt  = Color.green;
      final static Color grid = Color.lightGray;
      private static final BasicStroke SOLID = new BasicStroke(1.0f);
      private static final BasicStroke BOLD  = new BasicStroke(3.0f);
      private double maxX = 0.0;
      private double maxY = 0.0;
      private double gridWidth;
      private double gridHeight;
      private int panelWidth;
      private int panelHeight;
      boolean firstTime = true;
      private double[] xPoints = null;
      private double[] yPoints = null;
      GeneralPath polygon;
      boolean polyOk = false;
      private double waveHeight = 0;
      private boolean gridOn = true;
      private Usr_Test_R scrollPane = null;
      Usr_Test_L(Usr_Test_R scrollPane)
        super(true);
        this.scrollPane = scrollPane;
        buildGui();
      void buildGui()
        setBackground(bg);
        setForeground(fg);
        //Let the user scroll by dragging to outside the window.
        setAutoscrolls(true); //enable synthetic drag events
    //    addMouseMotionListener(this); //handle mouse drags
        repaint();
      private void generateWave(int cycles, double height)
        waveHeight = height;
        xPoints = new double[cycles];
        yPoints = new double[cycles];
        Random r = new Random();
        for ( int i = 0; i < cycles; i++ )
          xPoints[i] = i;
          yPoints[i] = (int)( Math.pow(-1.0,i) ) * ( r.nextInt(2) );
    //      if ( ( i % 10 ) == 0 ) yPoints[i] = height;
    //      else                   yPoints[i] = height + gridHeight;
    //      System.err.println("P"+i+"("+xPoints[i]+","+yPoints[i]+")");
      private void generateSineWave(int cycles, double height)
        waveHeight = height;
        xPoints = new double[cycles];
        yPoints = new double[cycles];
        double j, xval, yval;
        j = 0;
        int i = 0;
        while (i < cycles)
          xval = j;
          yval = Math.sin(j) * 10.0 + 20;
          xPoints[i] = xval;
          yPoints[i] = yval;
          i++;
          j += 0.01;
      public Dimension getPreferredSize()  // <== used because of revalidate, parent scrollpane asks preferredsize ..., so we overruled the method
        return new Dimension(panelWidth, panelHeight);
      public void drawLine(int cycles, int height)
        generateWave(cycles,(int)(gridHeight*height));
        maxX = gridWidth  * cycles;
        maxY = gridHeight * cycles;
        while ( maxX > panelWidth  ) panelWidth  *= 2;
        while ( maxY > panelHeight ) panelHeight *= 2;
    //    polyOk = buildPolygon();
        revalidate();
        repaint();
      public void drawSine(int cycles, int height)
        generateSineWave(cycles,(int)(gridHeight*height));
        maxX = gridWidth  * cycles;
        maxY = gridHeight * cycles;
        while ( maxX > panelWidth  ) panelWidth  *= 2;
        while ( maxY > panelHeight ) panelHeight *= 2;
    //    polyOk = buildPolygon();
        revalidate();
        repaint();
      public void zoomIn()
        gridWidth  *= 2;
        gridHeight *= 2;
        repaint();
      public void zoomOut()
        gridWidth  /= 2;
        gridHeight /= 2;
        repaint();
      private void initPanel()
        Dimension d = getSize();
        panelWidth = d.width;
        panelHeight = d.height;
        maxX = panelWidth;
        maxY = panelHeight;
        gridWidth  = panelWidth / 8;
        gridHeight = panelHeight / 8;
        scrollPane.getHorBar().setUnitIncrement((int)(gridWidth*3));           // times 2 otherwise no clipbounds are allways too small
        scrollPane.getHorBar().setBlockIncrement((int)(gridWidth*3));
        scrollPane.getVerBar().setUnitIncrement((int)(gridHeight*3));
        scrollPane.getVerBar().setBlockIncrement((int)(gridHeight*3));
      public void grid()
        if ( gridOn ) gridOn = false;
        else          gridOn = true;
      private void drawGrid(Graphics2D g2, Rectangle clip)
        if ( ! gridOn ) return;
        // draw grid
        g2.setPaint(grid);
        // new good grid
        double startX = clip.getX() + ( gridWidth - ( clip.getX() % gridWidth ) );
        double endX   = clip.getX() + clip.getWidth();
        double startY = clip.getY() + ( gridHeight - ( clip.getY() % gridHeight ) );
        double endY   = clip.getY() + clip.getHeight();
        double y = startY;
        while ( startX < endX )
          while ( y < endY )
            g2.draw(new Rectangle2D.Double( startX - 0.5, y - 0.5, 1.0, 1.0 ));
            y += gridHeight;
          y = startY;
          startX += gridWidth;
      private boolean buildPolygon(Rectangle clip)
        if ( xPoints != null && yPoints != null )
          polygon = new GeneralPath(GeneralPath.WIND_NON_ZERO,xPoints.length);
        else
          return false;
        double x = xPoints[0] * gridWidth;
        double y = waveHeight;
        polygon.moveTo((float)xPoints[0], (float)yPoints[0]);
        for ( int index = 0; index < xPoints.length; index++ )
          x = xPoints[index] * gridWidth;
          y = waveHeight + ( yPoints[index] * gridHeight );
          if ( x > ( clip.getX() + clip.getWidth() ) ) break;
          if ( y < clip.getY() || y > ( clip.getY() + clip.getHeight() ) ) continue;
          if ( x < clip.getX() || x > ( clip.getX() + clip.getWidth()  ) ) continue;
          polygon.lineTo((float)x, (float)y);
        return true;
      private boolean drawLines(Graphics2D g2, Rectangle clip)
        if ( xPoints == null || yPoints == null ) return false;
        double x1 = xPoints[0] * gridWidth;
        double y1 = waveHeight;
        double x2, y2;
        boolean cont = false;
        for ( int index = 0; index < xPoints.length; index++ )
          x2 = xPoints[index] * gridWidth;
          y2 = waveHeight + ( yPoints[index] * gridHeight );
          if ( x1 > ( clip.getX() + clip.getWidth() ) )
            break;
          if ( x2 > ( clip.getX() + clip.getWidth() ) )
            break;
          if ( y2 < clip.getY() || y2 > ( clip.getY() + clip.getHeight() ) )
            cont = true;
          if ( x2 < clip.getX() || x2 > ( clip.getX() + clip.getWidth()  ) )
            cont = true;
          if ( ! cont ) g2.draw(new Line2D.Double(x1,y1,x2,y2));
          x1 = x2;
          y1 = y2;
          cont = false;
        return true;
      public void paintComponent(Graphics g)
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        if ( firstTime )
          initPanel();
          firstTime = false;
        // get clip bounds
        Rectangle clip = new Rectangle();
        clip = g2.getClipBounds(clip);
        // draw grid
        drawGrid(g2,clip);
        // draw waveform
        g2.setPaint(wave);
        g2.setStroke(SOLID);
        if ( buildPolygon(clip) ) g2.draw(polygon);
    //    if ( polyOk ) g2.draw(polygon);
    //    drawLines(g2,clip);
      }

    I have added a standalone testcase for ease.
    import java.awt.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import java.util.*;
    public class Scrolling {
        public static void main(String[] args) {
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new JScrollPane(new DrawPanel()));
            f.setSize(400,300);
            f.setLocationRelativeTo(null);
            f.setVisible(true);
    class DrawPanel extends JPanel {
        private GeneralPath polygon = new GeneralPath(GeneralPath.WIND_NON_ZERO,1000);
        private int[] coords;
        public DrawPanel() {
            setBackground(Color.white);
            buildPolygon();
        private void buildPolygon() {
         coords = new int[2000];
            Random r = new Random();
            int height = 80;
            int gridHeight = 10;
            int gridWidth = 10;
         int j = 0;       
            for (int i=0, dir=-1; i<1000; i++, dir=-dir) {
                coords[j++] = i * gridWidth;
                coords[j++] = height + dir*gridHeight*r.nextInt(2);
        private void drawPolygonClipped(Rectangle clip)
    polygon = new GeneralPath(GeneralPath.WIND_NON_ZERO,1000);
           polygon.moveTo(0,80);
           for ( int i = 0; i < 2000; i++ )
          if ( coords[i] > ( clip.getX() + clip.getWidth() ) ) break;
          if ( coords[i+1] < clip.getY() || coords[i+1] > ( clip.getY() + clip.getHeight() ) ) continue;
          if ( coords[i] < clip.getX() || coords[i] > ( clip.getX() + clip.getWidth()  ) ) continue;
                polygon.lineTo(coords[i++],coords);
    private void drawPolygon(Rectangle clip)
    polygon = new GeneralPath(GeneralPath.WIND_NON_ZERO,1000);
         polygon.moveTo(0,80);
         for ( int i = 0; i < 2000; i++ )
              polygon.lineTo(coords[i++],coords[i]);
    protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D)g;
         Rectangle clip = new Rectangle();
         g.getClipBounds(clip);
         drawPolygonClipped(clip);
         //drawPolygon(clip);
    g2.draw(polygon);
    public Dimension getPreferredSize() {
    return new Dimension(1500,500);

  • JScrollpane does not work properly when I interlinked to another Scrollpane

    Hi,
    I am trying to develop a small Editor using java Swing. I hav to display Line numbers also. for that i used another textarea and set the scrollbar model of that to the scrollbar model of text area where i type the programs. the module works perfectly in the first appearance.. scrolls same time..but the problem arises when i insert a new line into or delete a new line from the text area. when i am inserting or deleting the scrollbar of the prgram text area scrolls down immdtly after the insertion or deletion...
    I tried a lot to solve the problem. Please help me...

    I hav to display Line numbers ...Whatever component you use to display the line number you should add the component directly to the scroll pane that contains your main text area. You do this by using the scrollPane.setRowHeaderView(). I've posted several example of this if you search the forums.

  • How can i make my scrollpane in a way that at the opening of a frame it doe

    How can i make my scrollpane in a way that at the opening of a frame it does not scroll down automatically?
    code is below
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.net.*;
    import javax.swing.JOptionPane.*;
    import java.io.*;
    import javax.swing.colorchooser.*;
    import javax.swing.filechooser.*;
    import javax.accessibility.*;
    import javax.swing.border.*;
    import java.sql.*;
    public class Signup extends JFrame
         JLabel p1,p2,p3,p4,p5,p6,uid,upass,cpass,fname,sname,hint,sl,ed,age,adr,cit,zip;
         JTextField uname,fnamet,snamet,hintt,adrt,adrt1,city,zipcode;
         JPasswordField upassw,cpassw;     
         JComboBox sex,education,agegr;
         Signup()
         Container c=getContentPane();
         c.setLayout(null);
         c.setBackground(Color.white);
         /** JPanel c = new JPanel();
         c.setBackground(Color.white);
         int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;
         int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
         JScrollPane jsp = new JScrollPane(c, v, h); ***/
    p1=new JLabel("Create Your Icafe!ID",10);
         p2=new JLabel("Personal Information");
         p3=new JLabel("User Address");
         p4=new JLabel("Tell Us About Your Hobbiess (Optional) ");
         p5=new JLabel("Tell us something about what you like. This will help us choose the kind of content to display on           your pages.");
         p6=new JLabel("--------------------------------------------------------------------------------");
    uid=new JLabel("User Id");
         upass=new JLabel("Password");
         cpass=new JLabel("Confirmation Password");
         fname=new JLabel("UserName");
         sname=new JLabel("SurName");
         hint=new JLabel("Hint Question");
    sl=new JLabel("Sex");
         ed=new JLabel("Education");     
         age=new JLabel("Age Group");     
         adr=new JLabel("Address");
    cit=new JLabel("City");
    zip=new JLabel("ZipCode");
         uname=new JTextField(10);
         uname.requestFocus();     
         uname.setToolTipText("UserName");
    upassw=new JPasswordField(10);
         upassw.setToolTipText("Password");
         upassw.setEchoChar('*');
         cpassw=new JPasswordField(10);
         cpassw.setToolTipText("Confirmation Password");
         cpassw.setEchoChar('*');
         fnamet=new JTextField(10);
         fnamet.setToolTipText("FullName");
         snamet=new JTextField(10);
         snamet.setToolTipText("SurName");
         hintt=new JTextField(10);
         hintt.setToolTipText("Hint Question");     
    String[] gender={"[Select one]","Male","Female"};
         sex = new JComboBox(gender);          
    String[] edu={"[Select one]","S.S.C","Inter","Graduate","Post Graduate"};
         education= new JComboBox(edu);     
    String[] ageg={"[Select one]","0 - 15","16 - 35","36 - 70","70 - 100"};
         agegr= new JComboBox(ageg);     
    adrt=new JTextField(15);
         adrt.setToolTipText("Address");
         adrt1=new JTextField(15);
         adrt1.setToolTipText("Address");
         city=new JTextField(15);
         city.setToolTipText("City");
    zipcode=new JTextField(15);
         zipcode.setToolTipText("ZipCode");
         p1.setBounds(200,70,160,30);
         uid.setBounds(350,100,160,30);
         uname.setBounds(400,100,160,30);
         upass.setBounds(335,140,160,30);
         upassw.setBounds(400,140,160,30);
         cpass.setBounds(260,180,160,30);
         cpassw.setBounds(400,180,160,30);
         p2.setBounds(200,220,160,30);
         fname.setBounds(330,260,160,30);
         fnamet.setBounds(400,260,160,30);
         sname.setBounds(335,300,160,30);
         snamet.setBounds(400,300,160,30);
    hint.setBounds(315,340,160,30);     
    hintt.setBounds(400,340,160,30);
         sl.setBounds(370,380,160,30);     
         sex.setBounds(400,380,160,30);
         ed.setBounds(335,420,160,30);     
         education.setBounds(400,420,160,30);
    age.setBounds(330,460,160,30);
    agegr.setBounds(400,460,160,30);
    p3.setBounds(200,500,160,30);
         adr.setBounds(340,540,160,30);
         adrt.setBounds(400,540,160,30);
         adrt1.setBounds(400,580,160,30);
         cit.setBounds(370,620,160,30);
         city.setBounds(400,620,160,30);
    zip.setBounds(590,620,160,30);
    zipcode.setBounds(640,620,160,30);
         Font font = new Font("SansSerif",Font.BOLD, 12);
         setFont(font);
         c.add(p1);
    c.add(uid);
         c.add(uname);     
         c.add(upass);
         c.add(upassw);
    c.add(cpass);
         c.add(cpassw);
    c.add(p2);
    c.add(fname);     
         c.add(fnamet);
    c.add(sname);
    c.add(snamet);
         c.add(hint);
    c.add(hintt);     
    c.add(sl);
    c.add(sex);
    c.add(ed);
         c.add(education);
    c.add(age);
         c.add(agegr);
    c.add(p3);
    c.add(adr);
         c.add(adrt);
         c.add(adrt1);
    c.add(cit);
    c.add(city);
    c.add(zip);
    c.add(zipcode);
         setResizable(false);
         //int a=DO_NOTHING_ON_CLOSE;
         //setDefaultCloseOperation(a);
         show();
         setSize(800,500);
    // Border raisedBorder = new BevelBorder(BevelBorder.RAISED);     
         setContentPane(c);     
    public static void main (String arg[])
         try{
         UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
         }catch(Exception s)
         Signup swu=new Signup();

    just try the following:
    jsp.getVerticalScrollbar().setValue(0);after inserting and adding all your components. this will set the vertical scrollbar up to the very first line.
    regards

  • How do I create an infinite drawing canvas in a ScrollPane?

    I wanted to figure this out on my own, but it is time to ask for help. I've tried too many different things. The closest I've come to the behaviour I want is with this code:
    final BorderPane root = new BorderPane();
    final Pane canvasWrapper = new Pane();
    canvasWrapper.setPrefSize(800, 500);
    canvasWrapper.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
    canvasWrapper.setStyle("-fx-background-color: lightgray; -fx-border-color: green; -fx-border-width: 2px;");
    final Group canvas = new Group();
    canvasWrapper.getChildren().add(canvas);
    final ScrollPane scroll = new ScrollPane();
    scroll.setContent(canvasWrapper);
    root.setCenter(scroll);
    // event code for adding circles and lines to the canvas
    I want the ScrollPane to be filled with the Pane, so it can catch events for drawing. When the stage is resized, the ScrollPane is resized too. This the result of the BorderPane. What I want is to expand the window and have canvasWrapper expand to fill the entire ScrollPane viewport. When the stage is made smaller the ScrollPane shrinks, but I want the canvasWrapper to retain its size. The idea is the drawing canvas can only grow. When it gets too large for the current stage/ScrollPane size, the scrollpane can be used to navigate around the canvas.
    I tried using
    scroll.setFitToHeight(true);
    scroll.setFitToWidth(true);
    but this causes the Pane to be made smaller when the viewport is made smaller.

    I figured it out!
    Use
    scroll.setFitToHeight(true);
    scroll.setFitToWidth(true);
    to resize the Pane as the view port changes.
    Save the canvas' size as the Pane's size.
    canvas.layoutBoundsProperty().addListener(new ChangeListener<Bounds>() {
                @Override
                public void changed(ObservableValue<? extends Bounds> ov, Bounds t, Bounds t1) {
                    canvasWrapper.setMinSize(t1.getMaxX(), t1.getMaxY());
    This forces the Pane to always be as large as the group is.
    Missed a piece of code - jrguenther

  • How to print the components in scrollpane

    hi there,
    can anyone tell me how to print the scrollpane components, i mean the headers & the main view of the component. i've a scrollpane with the following code and i want to print the components:
    JScrollPane pane = new JScrollPane(aTextPane);
    pane.setRowHeaderView(aLineNumberComponent);my requirement is i've a editor & lineno component as textpanes and added to scrollpane & when asked to print it should print the lineno component which resides in scrollpane's row header & the editor textpane which is the main view in the scrollpane. how can i achieve this?
    i'd would appreciate any suggestions & codes given.
    thanx in advance.

    After adding/removing components to/from a panel try:
    panel.revalidate();
    panel.repaint() // sometimes this is also needed, I'm
    not sure whyI'm not certain, but I think that panel.revalidate() implicitly calls repaint() only if something actually changed in the layout. If nothing changed, it sees no reason to repaint; hence, if something changed in appearance but not in layout, you have to repaint it yourself.
    Or something like that. I'm no expert. ;)

  • Is it possible to load .swfs on top of scrollpane

    I have a scrollpane that links to a movie clip in my library
    that holds about 40 buttons. I'm using the scrollpane since the
    layout doesn't have enough room to show them all at once. This way
    the user can scroll down to see all the names. These buttons have
    the names of various articles on them. Upon clicking on an article
    a flashpaper .swf file of that article is loaded. Right now the
    article is loading into my scrollpane and seems to be kicking out
    the movie clip that contains the buttons. Upon closing out the
    flashpaper article the buttons return and work fine. The only issue
    I have with this is that if the user scrolls down, clicks on an
    article and then closes it out, the buttons reappear, but they are
    back at the top. The user would then need to scroll back down to
    where they were if there were wanting to click on the next article
    in line. Not a big deal, but it gets kina annoying after a while.
    I'd like to figure out a way for the flashpaper articles to load on
    top of the scroll pane so that when the user closes the flashpaper
    article the links below are where they left off. So far no matter
    what I try the flashpapers keep loading inside the scroll pane.
    Here is the code I'm using as applied to one of the 40 buttons:
    on (release) {
    _parent.loadMovie("MM/flashpaper/art2_120106_prev_injuries_unint.swf",
    1);
    art2_120106_prev_injuries_unint.swf is the name of the
    flashpaper article being loaded.
    -I've tried changing the level number and that doesn't work
    -I've tried creating an empty movie clip in a layer above the
    buttons and that doesn't work:
    on (release) {
    _parent.loadMovie("MM/flashpaper/art2_120106_prev_injuries_unint.swf",
    "artMC");
    ("artMC" is the empty movie clip)
    -I've tride creating an empty movie clip in the main timeline
    above the scrollpane and that doesn't work either
    any thoughts on how I should handle this?
    thanks

    import mx.managers.DepthManager;
    movieclipyouwantontop.setDepthAbove(movieclipyouwantonbottom);
    use the creatEmptyMovieClip method you tried before then
    place it into what i gave

  • Problem adding a table to scrollpane

    Hi:
    I have created a JTable that I want to be in a scrollpane. When I tried to add this JTable to a scrollpane I get a null pointer error at execution time. But when I add this table directly to the frame I get no error at execution time.
    Here is my code:
    import java.awt.*;
    import java.awt.event .*;
    import javax.swing.*;
    import java.util.*;
    import javax.swing.event.*;
    import java.io.*;
    import javax.swing.table.*;
    import javax.swing.BorderFactory;
    import javax.swing.border.Border;
    import java.net.*;
    import java.util.regex.*;
    // METHODS
    // =======
    // private String returnSelectedString( int col ))
    public class DialogFrame extends JFrame
    {     //===================
    //MEMBER VARIABLES
    //===================
    public JLabel topClassifiedLabel, bottomClassifiedLabel,printerCountLabel,defaultPrinterLabel ;
    public JPanel panelForLabel,topClassificationPanel , bottomClassificationPanel, SecBotPanel, ClassificationPanel,Classification_botPanel,firstTopPanel, titlePanel,titlePanel2,displayPanel,labelPanel,buttonPanel;
    public DefaultListModel listModel;
    public final String screenTitle = "Printer Configuration "
    + " CSS - 105";
    public JLabel localDisplay = new JLabel("Local: Printer directly connected to this computer");
    public JLabel remoteDisplay = new JLabel("Remote: Printer connected to another computer");
    public JLabel networkDisplay = new JLabel("Network: Printer connected to the LAN");
    public char hotKeys[] = { 'A', 'D', 'Q','T','R','I','Q','H' };
    public JPanel ConnectTypePanel = null, printCountPanel;
    public JScrollPane tabScrollPane;
    public JLabel l1,l2,l3,l4,l5,l6,l7,l8,l9,l10,l11,l12,TitleLabel;
    public JButton addPrinterButton,setDefaultButton,restartPrintSystemButton, deletePrinterButton, displayQueueButton,
    ToggleBannerButton, RestartPrintSystemButton, InstallOpenPrintButton, QuitButton, continueButton,CancelButton,HelpButton;
    public Vector columnNames;
    public String line2 = "";
    public addPrinterDialog aPDialog;
    public printQueueDialog dQDialog;
    public String nextElement,name,Type,Interface,Description,Status,Queue,BannerPage;
    public JRadioButton networkButton, localButton, remoteButton;
    public JLabel nameLabel, descriptionLabel, modelLabel,ClassificationLabel,ClassificationLabel_bot,setL,defaultL;
    public JTextField nameTextField, descriptionTextField, modelTextField;
    private int printerCount = 0;
    static DefaultTableModel model;
    public JTable table;
    //=======================//
    //**Constructor
    //=========================//
    public DialogFrame()
    createTable();
    public void createTable()
    defaultPrinterLabel = new JLabel();
    printerCountLabel = new JLabel();
    //COLUMN FOR TABLE
    columnNames = new Vector();
    columnNames.add("Name");
    columnNames.add("Type");
    columnNames.add("Interface");
    columnNames.add("Description");
    columnNames.add("Status");
    columnNames.add("Queue");
    columnNames.add("BannerPage");
    Vector tableRow = new Vector();
    //tableRow = executeScript("perl garb.pl");
    // tableRow = executeScript("perl c:\\textx.pl");
    model = new DefaultTableModel( tableRow, columnNames ){
    public boolean isCellEditable(int row,int col) {
    return false;
    public Dimension getPreferredScrollableViewportSize() {
    return getPreferredSize();
    table = new JTable(model);
    JTableHeader header = table.getTableHeader();
    TableColumnModel colmod = table.getColumnModel();
    for (int i=0; i < table.getColumnCount(); i++)
    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
    renderer.setHorizontalAlignment(SwingConstants.CENTER);
    colmod.getColumn(i).setCellRenderer(renderer);
    table.setPreferredScrollableViewportSize(new Dimension(500, 70));
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    table.setShowGrid( false );
    table.getTableHeader().setReorderingAllowed( false );
    table.setIntercellSpacing(new Dimension(0,0) );
    table.addMouseListener( new MouseAdapter () {
    public void mouseClicked( MouseEvent e) {
    if ((e.getModifiers() & InputEvent.BUTTON1_MASK) !=0)
    printSelectCell(table);
    this.setSize(900,900);
    //========================================//
    // Technique for centering a frame on the screen
    //===========================================//
    Dimension frameSize = this.getSize();
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    this.setLocation((screenSize.width - frameSize.width)/2,
    (screenSize.height - frameSize.height)/2);
    setResizable(false);
    // CREATE A FEW PANELS
    firstTopPanel = new JPanel();
    BoxLayout box = new BoxLayout(firstTopPanel, BoxLayout.Y_AXIS);
    firstTopPanel.setLayout(box);
    topClassificationPanel = new JPanel();
    topClassificationPanel.setBackground(new Color(45,145,71));
    bottomClassificationPanel = new JPanel();
    bottomClassificationPanel.setBackground(new Color(45,145,71));
    SecBotPanel = new JPanel();
    SecBotPanel.setLayout(new BorderLayout());
    buttonPanel = new JPanel();
    buttonPanel.setLayout(new GridLayout(1,8));
    buttonPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 0));
    buttonPanel.setBackground(new Color(170,187,119));
    panelForLabel = new JPanel();
    // panelForLabel.setBackground( Color.white );
    //Border etchedBorder = BorderFactory.createEtchedBorder();
    printerCountLabel.setHorizontalAlignment(SwingConstants.LEFT);
    printerCountLabel.setPreferredSize(new Dimension(700, 20));
    //printerCountLabel.setBorder(etchedBorder);
    printerCountLabel.setForeground(Color.black);
    defaultPrinterLabel.setHorizontalAlignment(SwingConstants.RIGHT);
    defaultPrinterLabel.setText("Default Printer: " + name);
    defaultPrinterLabel.setForeground(Color.black);
    panelForLabel.add(printerCountLabel);
    panelForLabel.add(defaultPrinterLabel);
    titlePanel = new JPanel( );
    titlePanel.setBackground( Color.white );
    ConnectTypePanel = new JPanel();
    ConnectTypePanel.setBackground(new Color(219,223,224));
    ConnectTypePanel.setLayout( new GridLayout(3,1) );
    //CREATE A FEW LABELS
    topClassifiedLabel = new JLabel("UNCLASSIFIED", SwingConstants.CENTER );
    topClassifiedLabel.setForeground(Color.white);
    bottomClassifiedLabel = new JLabel("UNCLASSIFIED", SwingConstants.CENTER );
    bottomClassifiedLabel.setForeground(Color.white);
    TitleLabel = new JLabel( screenTitle, SwingConstants.CENTER );
    //ADD LABELS TO PANELS
    topClassificationPanel.add( topClassifiedLabel );
    bottomClassificationPanel.add( bottomClassifiedLabel );
    titlePanel.add( TitleLabel, BorderLayout.CENTER );
    ConnectTypePanel.add(localDisplay );
    ConnectTypePanel.add(remoteDisplay );
    ConnectTypePanel.add(networkDisplay );
    //Create the scrollpane and add the table to it.
    tabScrollPane = new JScrollPane(table);
    JPanel ps = new JPanel();
    ps.add(tabScrollPane);
    getContentPane().setLayout(
    new BoxLayout( getContentPane(), BoxLayout.Y_AXIS ) );
    getContentPane().add(firstTopPanel);
    getContentPane().add(panelForLabel);
    getContentPane().add(header);
    getContentPane().add(ps);//contain table
    getContentPane().add(SecBotPanel);
    WindowListener w = new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    DialogFrame.this.dispose();
    System.exit(0);
    this.addWindowListener(w);
    //==================================//
    // AddPrinterButton
    //==================================//
    addPrinterButton = new JButton();
    addPrinterButton.setLayout(new GridLayout(2, 1));
    l1 = new JLabel("Add", JLabel.CENTER);
    l1.setForeground(Color.black);
    l2 = new JLabel("Printer", JLabel.CENTER);
    l2.setForeground(Color.black);
    addPrinterButton.add(l1);
    addPrinterButton.add(l2);
    addPrinterButton.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent event)
    //(aPDialog == null) // first time
    aPDialog = new addPrinterDialog(DialogFrame.this);
    aPDialog.setLocationRelativeTo(null);
    aPDialog.pack();
    aPDialog.show(); // pop up dialog
    //======================================
    // DeletePrinterButton
    //=====================================
    deletePrinterButton = new JButton();
    deletePrinterButton.setLayout(new GridLayout(2, 1));
    l1 = new JLabel("Delete", JLabel.CENTER);
    l1.setForeground(Color.black);
    l2 = new JLabel("Printer", JLabel.CENTER);
    l2.setForeground(Color.black);
    deletePrinterButton.add(l1);
    deletePrinterButton.add(l2);
    deletePrinterButton.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent event)
    int sr = table.getSelectedRow();
    if (sr == -1)
    JOptionPane.showMessageDialog(null, "You have not selected a printer for this operation","NOSELECT",JOptionPane.INFORMATION_MESSAGE);
    else
    name = returnSelectedString(0);
    int ans = JOptionPane.showConfirmDialog(null,"Are you sure you want to delete printer " + name + "?","Delete",JOptionPane.YES_NO_OPTION);
    switch(ans) {
    case JOptionPane.NO_OPTION:
    return;
    case JOptionPane.YES_OPTION:
    // String machineName = returnSelectedString(0);
    int rowNumber = table.getSelectedRow();
    model.removeRow(rowNumber);
    //TiCutil.exe("/usr/lib/lpadmin -x " + machineName);
    decreasePrinterCount();
    JOptionPane.showMessageDialog(null, "Printer " + name + " have been successfully deleted","SUCCEED",JOptionPane.INFORMATION_MESSAGE);
    return;
    //==============================//
    //DisplayQueuePrinter //
    //================================//
    displayQueueButton = new JButton();
    displayQueueButton.setLayout(new GridLayout(2, 1));
    l5 = new JLabel("Display", JLabel.CENTER);
    l5.setForeground(Color.black);
    l6 = new JLabel("Queue", JLabel.CENTER);
    l6.setForeground(Color.black);
    displayQueueButton.add(l5);
    displayQueueButton.add(l6);
    displayQueueButton.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent event)
    Vector tab = new Vector();
    int sr = table.getSelectedRow();
    if (sr == -1)
    JOptionPane.showMessageDialog(null, "You have not selected a printer for this" +
    "operation","NOSELECT",JOptionPane.INFORMATION_MESSAGE);
    else
    name = returnSelectedString(0);
    //PASS TABLE HERE
    /*tab = executeScript("lpstat -o " + name + " | sed \'s/ on$//\'");
    System.out.println("lpstat -o " + name + " | sed \'s/ on$//\'");
    dQDialog = new printQueueDialog(DialogFrame.this, name, tab);
    dQDialog.setLocationRelativeTo(null);
    dQDialog.pack();
    dQDialog.show(); // pop up dialog */
    //===================================
    // SetDefaultButton
    //================================//
    setDefaultButton = new JButton();
    setDefaultButton.setLayout(new GridLayout(2, 1));
    setL = new JLabel("Set", JLabel.CENTER);
    setL.setForeground(Color.black);
    defaultL = new JLabel("Default", JLabel.CENTER);
    defaultL.setForeground(Color.black);
    setDefaultButton.add(setL);
    setDefaultButton.add(defaultL);
    setDefaultButton.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent event)
    int sr = table.getSelectedRow();
    if (sr == -1)
    JOptionPane.showMessageDialog(null, "You have not selected a printer for this operation","NOSELECT",JOptionPane.INFORMATION_MESSAGE);
    else
    name = returnSelectedString(0);
    JOptionPane.showMessageDialog(null, "printer " + name + " is now the default.","Succeed",JOptionPane.INFORMATION_MESSAGE);
    defaultPrinterLabel.setText("Default Printer: " + name);
    //==============================//
    // ToggleBannerButton
    //==============================//
    ToggleBannerButton = new JButton();
    ToggleBannerButton.setLayout(new GridLayout(2, 1));
    l7 = new JLabel("Toggle", JLabel.CENTER);
    l7.setForeground(Color.black);
    l8 = new JLabel("Banner", JLabel.CENTER);
    l8.setForeground(Color.black);
    ToggleBannerButton.add(l7);
    ToggleBannerButton.add(l8);
    ToggleBannerButton.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent event)
    int sr = table.getSelectedRow();
    System.out.println("sr :" + sr);
    if (sr == -1)
    JOptionPane.showMessageDialog(null, "You have not selected a printer for this operation","NOSELECT",JOptionPane.INFORMATION_MESSAGE);
    else
    String banner = returnSelectedString(6);
    name = returnSelectedString(0);
    String machineName = returnSelectedString(0);
    Type = returnSelectedString(1);
    if ( !(Type.equals("Remote")) )
    if( banner.equals("Yes") )
    JOptionPane.showMessageDialog(null,"Banner page will NOT be printed for printer "+ name ,"Succeed",JOptionPane.INFORMATION_MESSAGE);
    //TiCutil.exe("sed -e 's/^BANNER=\"yes\"/BANNER=\"\"/' /etc/lp/interfaces/" + machineName + " > /tmp/delete.txt" );
    //TiCutil.exe("mv /tmp/delete.txt /etc/lp/interfaces/" + machineName);
    table.setValueAt("No",sr,6);
    DefaultTableModel model = (DefaultTableModel)table.getModel();
    model.fireTableCellUpdated(sr,6);
    table.requestFocus();
    else
    JOptionPane.showMessageDialog(null,"Banner page WILL be printed for printer "+ name ,"Succeed",JOptionPane.INFORMATION_MESSAGE);
    //TiCutil.exe("sed -e 's/^BANNER=\"\"/BANNER=\"yes\"/' /etc/lp/interfaces/" + machineName + " > /tmp/delete.txt");
    //TiCutil.exe("mv /tmp/delete.txt /etc/lp/interfaces/" + machineName);
    table.setValueAt("Yes",sr,6);
    DefaultTableModel model = (DefaultTableModel)table.getModel();
    model.fireTableCellUpdated(sr,6);
    table.requestFocus();
    else
    JOptionPane.showMessageDialog(null,"Operation failed system respond \n" + "was:\n" + "cannot toggle the banner page for a\n" + "REMOTE printer." ,"OPFAIL",JOptionPane.INFORMATION_MESSAGE);
    //==================================//
    // RestartPrintSystemButton
    //==================================//
    restartPrintSystemButton = new JButton();
    restartPrintSystemButton.setLayout(new GridLayout(2, 1));
    l3 = new JLabel("Restart Print", JLabel.CENTER);
    l3.setForeground(Color.black);
    l4 = new JLabel("System", JLabel.CENTER);
    l4.setForeground(Color.black);
    restartPrintSystemButton.add(l3);
    restartPrintSystemButton.add(l4);
    restartPrintSystemButton.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent event)
    //==============================
    // InstallOpenPrint
    //================================
    InstallOpenPrintButton = new JButton();
    InstallOpenPrintButton.setLayout(new GridLayout(2, 1));
    l11 = new JLabel("Install Open", JLabel.CENTER);
    l11.setForeground(Color.black);
    l12 = new JLabel("Print", JLabel.CENTER);
    l12.setForeground(Color.black);
    InstallOpenPrintButton.add(l11);
    InstallOpenPrintButton.add(l12);
    InstallOpenPrintButton.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent event)
    int ans = JOptionPane.showConfirmDialog(null,"Are you sure you want to install OPENPrint?","Delete",JOptionPane.YES_NO_OPTION);
    switch(ans) {
    case JOptionPane.NO_OPTION:
    return;
    case JOptionPane.YES_OPTION:
    int cd,opinstall,banner_var,pwd;
    opinstall = runIt("open_print.ksh");
    banner_var = runIt("banner_var.ksh");
    System.out.println("opinstall: " + opinstall );
    System.out.println("banner_var: " + banner_var);
    if ( opinstall == 0 && banner_var == 0)
    JOptionPane.showMessageDialog(null, "OPENprint successfully added"
    ,"SUCCEED",JOptionPane.INFORMATION_MESSAGE);
    return;
    //==========================
    //QuitButton
    //============================
    QuitButton = new JButton("Quit");
    QuitButton.addActionListener (new ActionListener ()
    { public void actionPerformed (ActionEvent e){
    System.exit (0); }
    HelpButton = new JButton("Help");
    //ADD BUTTONS TO PANEL
    buttonPanel.add( addPrinterButton );
    buttonPanel.add( deletePrinterButton );
    buttonPanel.add( displayQueueButton );
    buttonPanel.add( setDefaultButton);
    buttonPanel.add( ToggleBannerButton );
    buttonPanel.add( restartPrintSystemButton );
    buttonPanel.add( InstallOpenPrintButton );
    buttonPanel.add( QuitButton );
    //buttonPanel.add( HelpButton );
    //END OF BUTTONS CREATION
    //ADD PANEL ON TO PANEL
    SecBotPanel.add(ConnectTypePanel, BorderLayout.CENTER);
    SecBotPanel.add(bottomClassificationPanel, BorderLayout.SOUTH);
    firstTopPanel.add(topClassificationPanel);
    firstTopPanel.add(titlePanel);
    firstTopPanel.add(buttonPanel);
    //===========================================================
    // METHODS
    //==========================================================
    public int runIt(String targetCode)
    int result = -1;
    try{
    Runtime rt = Runtime.getRuntime();
    Process p = rt.exec( targetCode );
    // Thread.sleep(20000);
    p.waitFor();
    result = p.exitValue();
    catch( IOException ioe )
    ioe.printStackTrace();
    catch( InterruptedException ie )
    ie.printStackTrace();
    return result;
    //====================================================
    public void increasePrinterCount()
    printerCount++;
    printerCountLabel.setText("Printer: " + printerCount);
    //===========================================================
    public void decreasePrinterCount()
    printerCount--;
    printerCountLabel.setText("Printer: " + printerCount);
    private String returnSelectedString( int col )
    int row = table.getSelectedRow();
    String word;
    //javax.swing.table.TableModel model = table.getModel();
    word =(String)model.getValueAt(row, col);
    return word; //return string
    //==============================================================================
    private Vector executeScript(String str)
    Vector tableOfVectors = new Vector();
    try{          
    String line;
    Process ls_proc = Runtime.getRuntime().exec(str);
    //get its output (your input) stream
    BufferedReader in = new BufferedReader( new InputStreamReader( ls_proc.getInputStream() ));
    //readLine reads in one line of text
    int k = 1, i = 0;
    //LOOK FOR THE "|"
    Pattern p = Pattern.compile(" ");
    while (( line = in.readLine()) != null)
    Vector data = new Vector();
    Matcher m = p.matcher(line);
    if(m.find() == true)//find " "
    line = line.replaceAll(" {2,}?", "|");
    //creates a new vector for each new line read in
    StringTokenizer t = new StringTokenizer(line,"|");
    while ( t.hasMoreTokens() )
    try
    nextElement = t.nextToken().trim();
    //add a string to a vector
    data.add(nextElement.trim());
    catch(java.util.NoSuchElementException nsx)
    System.out.println(nsx);
    tableOfVectors.add(data);
    //COUNT THE NUMBER OF PRINTER
    printerCount = k;
    printerCountLabel.setText("Printer: " + printerCount);
    k++;
    }//END OF WHILE
    in.close();
    }//END OF TRY
    catch (IOException e1) {
    System.err.println(e1);
    System.exit(1);
    return tableOfVectors;
    //==========================================================================================================
    private String getDefaultPrinter(String str)
    String groupStr = null;
    try{          
    String lin;
    Process ls_proc = Runtime.getRuntime().exec(str);
    BufferedReader in = new BufferedReader( new InputStreamReader( ls_proc.getInputStream() ));
    Pattern p2 = Pattern.compile("system default destination: (\\S+)");
    while (( lin = in.readLine()) != null)
    Matcher m2 = p2.matcher(lin);
    m2.reset(lin);
    if (m2.find() == true )
    groupStr = m2.group(1);
    in.close();
    catch (IOException e1) {
    System.err.println(e1);
    System.exit(1);
    return groupStr;
    //================================================================================
    public synchronized void clearTable()
    int numrows = model.getRowCount();
    for ( int i = numrows -1 ; i >= 0 ; i--)
    model.removeRow(i);
    //=======================================================================================================
    private void printSelectCell(JTable table )
    int numCols = table.getColumnCount();
    int row = table.getSelectedRow();
    System.out.println(row);
    javax.swing.table.TableModel model = table.getModel();
    for(int j=0;j < numCols; j++)
    System.out.println(" " + model.getValueAt(row,j));
    System.out.println();
    System.out.println("-----------------------------------------------");
    //CREATE ADD PRINTER DIALOG
    class addPrinterDialog extends JDialog
    public addPrinterDialog(JFrame owner)
    super(owner, "ap1", true);
    final ButtonGroup rbg = new ButtonGroup();
    JPane

    Ok  I have the table  on the page  I created a css with a background image called .search  How to I link that to the table so It shows the image
    I am only used to doing certain css items   Never didi this before
    THXS STeve

  • How to restrict the maximum size of a java.awt.ScrollPane

    Dear all,
    I would like to implement a scroll pane which is resizable, but not to a size exceeding the maximum size of the java.awt.Canvas that it contains.
    I've sort of managed to do this by writing a subclass of java.awt.ScrollPane which implements java.awt.event.ComponentListener and has a componentResized method that checks whether the ScrollPane's viewport width (height) exceeds the content's preferred size, and if so, resizes the pane appropriately (see code below).
    It seems to me, however, that there ought to be a simpler way to achieve this.
    One slightly weird thing is that when the downsizing of the pane happens, the content can once be moved to the left by sliding the horizontal scrollbar, but not by clicking on the arrows. This causes one column of gray pixels to disappear and the rightmost column of the content to appear; subsequent actions on the scrollbar does not have any further effect. Likewise, the vertical scrollbar can also be moved up once.
    Also, I would like a java.awt.Frame containing such a restrictedly resizable scrollpane, such that the Frame cannot be resized by the user such that its inside is larger than the maximum size of the scrollpane. The difficulty I encountered with that is that setSize on a Frame appears to set the size of the window including the decorations provided by the window manager (fvwm2, if that matters), and I haven't been able to find anything similar to getViewportSize, which would let me find out the size of the area inside the Frame which is available for the scrollpane which the frame contains.
    Thanks in advance for hints and advice.
    Here's the code of the componentResized method:
      public void componentResized(java.awt.event.ComponentEvent e)
        java.awt.Dimension contentSize = this.content.getPreferredSize();
        this.content.setSize(contentSize);
        java.awt.Dimension viewportSize = getViewportSize();
        System.err.println("MaxSizeScrollPane: contentSize = " + contentSize);
        System.err.println("MaxSizeScrollPane: viewportSize = " + viewportSize);
        int dx = Math.max(0, (int) (viewportSize.getWidth() - contentSize.getWidth()));
        int dy = Math.max(0, (int) (viewportSize.getHeight() - contentSize.getHeight()));
        System.err.println("MaxSizeScrollPane: dx = " + dx + ", dy = " + dy);
        if ((dx > 0) || (dy > 0))
          java.awt.Dimension currentSize = getSize();
          System.err.println("MaxSizeScrollPane: currentSize = " + currentSize);
          setSize(new java.awt.Dimension(((int) currentSize.getWidth()) - dx, ((int) currentSize.getHeight()) - dy));
        System.err.println();
      }Best regards, Jan

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    public class ScrollPaneTest
        GraphicCanvas canvas;
        CustomScrollPane scrollPane;
        private Panel getScrollPanel()
            canvas = new GraphicCanvas();
            scrollPane = new CustomScrollPane();
            scrollPane.add(canvas);
            // GridBagLayout allows scrollPane to remain at
            // its preferred size during resizing activity
            Panel panel = new Panel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            panel.add(scrollPane, gbc);
            return panel;
        private WindowListener closer = new WindowAdapter()
            public void windowClosing(WindowEvent e)
                System.exit(0);
        private Panel getUIPanel()
            int w = canvas.width;
            int h = canvas.height;
            int visible = 100;
            int minimum = 200;
            int maximum = 500;
            final Scrollbar
                width  = new Scrollbar(Scrollbar.HORIZONTAL, w,
                                       visible, minimum, maximum),
                height = new Scrollbar(Scrollbar.HORIZONTAL, h,
                                       visible, minimum, maximum);
            AdjustmentListener l = new AdjustmentListener()
                public void adjustmentValueChanged(AdjustmentEvent e)
                    Scrollbar scrollbar = (Scrollbar)e.getSource();
                    int value = scrollbar.getValue();
                    if(scrollbar == width)
                        canvas.setWidth(value);
                    if(scrollbar == height)
                        canvas.setHeight(value);
                    canvas.invalidate();
                    scrollPane.validate();
            width.addAdjustmentListener(l);
            height.addAdjustmentListener(l);
            Panel panel = new Panel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(2,2,2,2);
            gbc.weightx = 1.0;
            addComponents(new Label("width"),  width,  panel, gbc);
            addComponents(new Label("height"), height, panel, gbc);
            gbc.anchor = GridBagConstraints.CENTER;
            return panel;
        private void addComponents(Component c1, Component c2, Container c,
                                   GridBagConstraints gbc)
            gbc.anchor = GridBagConstraints.EAST;
            c.add(c1, gbc);
            gbc.anchor = GridBagConstraints.WEST;
            c.add(c2, gbc);
        public static void main(String[] args)
            ScrollPaneTest test = new ScrollPaneTest();
            Frame f = new Frame();
            f.addWindowListener(test.closer);
            f.add(test.getScrollPanel());
            f.add(test.getUIPanel(), "South");
            f.pack();
            f.setLocation(200,200);
            f.setVisible(true);
            f.addComponentListener(new FrameSizer(f));
    class GraphicCanvas extends Canvas
        int width, height;
        public GraphicCanvas()
            width = 300;
            height = 300;
        public void paint(Graphics g)
            super.paint(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            int dia = Math.min(width, height)*7/8;
            g2.setPaint(Color.blue);
            g2.draw(new Rectangle2D.Double(width/16, height/16, width*7/8, height*7/8));
            g2.setPaint(Color.green.darker());
            g2.draw(new Ellipse2D.Double(width/2 - dia/2, height/2 - dia/2, dia-1, dia-1));
            g2.setPaint(Color.red);
            g2.draw(new Line2D.Double(width/16, height*15/16-1, width*15/16-1, height/16));
        public Dimension getPreferredSize()
            return new Dimension(width, height);
        public Dimension getMaximumSize()
            return getPreferredSize();
        public void setWidth(int w)
            width = w;
            repaint();
        public void setHeight(int h)
            height = h;
            repaint();
    class CustomScrollPane extends ScrollPane
        Dimension minimumSize;
        public Dimension getPreferredSize()
            Component child = getComponent(0);
            if(child != null)
                Dimension d = child.getPreferredSize();
                if(minimumSize == null)
                    minimumSize = (Dimension)d.clone();
                Insets insets = getInsets();
                d.width  += insets.left + insets.right;
                d.height += insets.top + insets.bottom;
                return d;
            return null;
        public Dimension getMinimumSize()
            return minimumSize;
        public Dimension getMaximumSize()
            Component child = getComponent(0);
            if(child != null)
                return child.getMaximumSize();
            return null;
    class FrameSizer extends ComponentAdapter
        Frame f;
        public FrameSizer(Frame f)
            this.f = f;
        public void componentResized(ComponentEvent e)
            Dimension needed = getSizeForViewport();
            Dimension size = f.getSize();
            if(size.width > needed.width || size.height > needed.height)
                f.setSize(needed);
                f.pack();
         * returns the minimum required frame size that will allow
         * the scrollPane to be displayed at its preferred size
        private Dimension getSizeForViewport()
            ScrollPane scrollPane = getScrollPane(f);
            Insets insets = f.getInsets();
            int w = scrollPane.getWidth() + insets.left + insets.right;
            int h = getHeightOfChildren() + insets.top + insets.bottom;
            return new Dimension(w, h);
        private ScrollPane getScrollPane(Container cont)
            Component[] c = cont.getComponents();
            for(int j = 0; j < c.length; j++)
                if(c[j] instanceof ScrollPane)
                    return (ScrollPane)c[j];
                if(((Container)c[j]).getComponentCount() > 0)
                    return getScrollPane((Container)c[j]);
            return null;
        private int getHeightOfChildren()
            Component[] c = f.getComponents();
            int extraHeight = 0;
            for(int j = 0; j < c.length; j++)
                int height;
                if(((Container)c[j]).getComponent(0) instanceof ScrollPane)
                    height = ((Container)c[j]).getComponent(0).getHeight();
                else
                    height = c[j].getHeight();
                extraHeight += height;
            return extraHeight;
    }

  • Event handling in scrollpane and graphics programming concept

    I am still unclear about what to do to refresh a canvas inside a scrollpane?
    what should i do with "repaint()" method of scrollpane??
    clearly i have to update the drawing on the graphics g of the canvas, according to the viewport of the scrollpane so that a min. area is painted only.
    will the "repaint()" method of canvas automatically get called when scrollbar is scrolled?? i tested but seems not.
    do i have to consume adjustmentevent?? seems it's not a low level event
    i saw in the console that the "update()" of the canvas sometimes get called twice when i scroll the scrollbar.
    the problem i am having is : i got different effect when i clicked on different part of the scrollbar
    clicked on the "bubble" will scroll the canvas, but once stopped the canvas that becomes visible(blank be4) is not updated
    only clicking on the area next to the "bubble" will lead to a "great leap" and the screen get updated
    i dont know how to override the adjustmentvaluechanged() actually

    i clearrect() and drawline(), filloval() in the update() of canvas and call update() inside the paint() of the canvas, i dont know if i should make it this way
    should i call repaint() of the scrollpane or repaint() of the canvas inside the adjustmentvaluechanged() of the scrollpane??

  • ScrollPane Problem breaking my heart...

    HI .I Want to read in a number from a textfield.This number will decide how many textfileds will appear on a panel. I want to then add this panel to a ScrollPane.I have this working but when the panel is in the scrollPane it doesnt scroll down the full length of the panel
    heres my code structure
    Create Scrollpane
    Read integer
    Create panel with textFields
    Add Panel to Scrollpane
    Add ScrollPane
    Is this the wrong way.....
    Any help really appreciated

    The client area of a ScrollPane is sized according to the components preferred size. The return value of the panels getPreferredSize is interesting. Does it have the value you expect?
    public Dimension getPreferredSize()
         Dimension dim;
         dim=super.getPreferredSize();
         System.out.println(�Preferre size:�+dim.width+�, �+dim.height);
         Return dim;
    }The other possible problem is the validation. When is the layout performed?
    public void doLayout()
         System.out.println(�doLayout() called�);
    }Try to add the above two methods to your panel class.
    Ragnvald.

  • I can't get ScrollPane.invalidate() to work.  Need help on this one.

    I have a dynamically created scrollpane who's content comes
    from a movieclip in the library.
    When I add this content from the library, I can't for the
    life of me get the scrollpane to correctly render the scrollbars.
    This is the code that I have. The movieclip in the library is
    linked as mc1 (width 100 height 46)
    import fl.containers.ScrollPane;
    import fl.controls.ScrollPolicy;
    import fl.controls.DataGrid;
    import fl.data.DataProvider;
    var aSp:ScrollPane = new ScrollPane();
    aSp.verticalScrollPolicy = "on";
    aSp.horizontalScrollPolicy = "on";
    var aBox:MovieClip = new MovieClip();
    drawBox(aBox);
    aSp.setSize(300, 300);
    aSp.source = aBox;
    addChild(aSp);
    function drawBox(box:MovieClip):void {
    var myMc1:mc1 = new mc1();
    myMc1.y = 50;
    myMc1.x = 50;
    box.addChild(myMc1);
    var mymc2:mc1 = new mc1();
    mymc2.x = 200;
    mymc2.y = 50;
    box.addChild(mymc2);
    }

    I figured it out. Nevermind.

  • Please Help me place the arrows of my ScrollPane scroll bar together on one end of the scroll track!!

    I have a scrollpane component with a movie clip of some
    thumbnail images.
    I just want to have its scrollbar arrows together on one end
    of the track (or together ANYwhere) instead of having them at
    opposite ends of the scroll track.
    I have been able to customize the appearance of the
    scrollpane and its scrollbar using the HaloTheme library, but that
    approach has so far been of no use in getting the arrows together.
    I cannot tell you how deeply any help will be appreciated. I
    will probably sob and mewl with gratitude, the way I imagine
    someone lost in a vast rain forest for many weeks mewls when
    rescued. I am desperate. I am going insane. Please, please help me.

    Cherrylanenc are you on a managed network?  If not then I would recommend reviewing the steps listed in Sign in, activation, or connection errors | CC, CS6, CS5.5 - http://helpx.adobe.com/x-productkb/policy-pricing/activation-network-issues.html.

Maybe you are looking for

  • SSO to SAP R3 thru ITS 6.20 with Logon tickets

    Hi All, I am trying to configure SSO to R3 thru ITS with the Logon Tickets. I have configured R3 to accept the tickets using STRUSTSSO2. Downloaded the verify.der file from Portal and imported to R3 And tried to test the System connection. If I use <

  • How to check the file size before loading it to the context

    Hello, I have an application to upload a file and write it to the server using the FileUpload UI and IWDResource Interface. I would like to limit the size of the file the user is uploading to, say, 2MB. The problem is that the current API doesn't all

  • How can you use the Keyboard for a JComboBox within a JTable without F2

    I am brand new to Java and I can't seem to figure this out. I have a JTable with 4 columns. The first column is a jCheckBox which is working fine. The other three are JComboBoxes. They work fine when you click them and select from the list, but our e

  • Trying to finish up my network

    I've got Airport Extreme up. My PowerMac G5 is connected through ethernet. My Dell Laptop is connected wirelessly. My Xbox 360 is connected through ethernet. I have moved my music to a USB Harddrive thats plugged into the Airport Extreme. My laptop i

  • Setting an app level item based on :APP_USER

    I am trying to set an application level item right after I log in and I want the value to be based on the setting of :APP_USER. I created an application level process at the "On New Session: After Authentication" point containing the following code: