ComponentListener

I've developed docking functionality for JFrames in my application. When application executed on different machines with the same JRE1.3.1_02, it behaves differently.
The problem is in the componentMoved(ComponentEvent e) method. On some machines the method invokes when you start drag the Jframe ( wrong behavior ) opposed to be invoked when you are done with dragging and release the mouse.
Any one have any suggestions?

Are they both the same OS?

Similar Messages

  • ComponentListener works in Java 1.5, not in Java 1.6

    Hi there,
    I'm having an odd problem. I have a GUI application that has a JFrame with a JDesktopPane as its content pane, with several sub-windows (JInternalFrames).
    The master JFrame listens for when a JInternalFrame closes and performs an action. Each JInternalFrame executes:
    addComponentListener(parent);The JFrame (parent) implements ComponentListener and includes:
        public void componentHidden(ComponentEvent e) {
             System.out.println(e.getComponent().getClass().getName());
             dostuff();
        }This works fine with Java 1.5. But if I compile a .jar and run it on Java 1.6, componentHidden is never called.
    Any suggestions?
    Many thanks,
    Peter.

    Hello there!
    I've been experiencing similar problem. As the author of the original post I have JFrame and JDesktopPane on it. I have several JInternalFrames. Internal frame has BorderLayout. I have two JPanels, that I want to add to Internal frame (one at a time). Other JPanel is removed and made invisible by calling setVisible(false). When I am adding JPanel to internal frame and calling method setVisible(true), componnetShown method is called as it should be. When I call method setVisible(false) and remove JPanel, method componentHidden is not called. I did workaround by calling active_panel.getComponentListeners()[0].componentHidden(null) at the time when setVisible(false) is called, but I do not like that. I'd like to know if I am misunderstanding something or if it is a bug.

  • Lazy (blind ?) componentListener

    I am using the componentListener interface to force the size of a JFrame to be greater than 400 * 200. This is the code :
    public void componentResized(ComponentEvent e) {
         int fen_wi = getWidth(), fen_he = getHeight() ;
         if(fen_wi < 400)
         fen_wi = 400 ;
         if(fen_he < 200)
         fen_he = 200 ;
         setBounds(getX(), getY(), fen_wi, fen_he) ;     
         int borne = 24, dim_x = getContentPane().getWidth(), dim_y = getContentPane().getHeight() ;
         scrollPane.setBounds(borne, borne, dim_x - 2 * borne, dim_y - 4 * borne ) ;
         ba.setBounds(borne, dim_y - 2 * borne, (dim_x - 4 * borne) / 3, borne) ;
         bm.setBounds(2 * borne + (dim_x - 4 * borne) / 3, dim_y - 2 * borne, (dim_x - 4 * borne) / 3, borne) ;
         br.setBounds(3 * borne + 2 * (dim_x - 4 * borne) / 3, dim_y - 2 * borne, (dim_x - 4 * borne) / 3, borne) ;
    The problem is that it only works half of the time ! When I try to resize the frame lower than 400 * 200, either it resize it correctly to 400 * 200, o it leaves it 150 * 50, telling me that the size is 400*200 ! Where does it comes from ? How can the getWidht et getHeight methods can return a size of 400 * 200 when the real dimensions are 120 * 50 ?

    Hi Peter
    I have the exact same problem - and probably have to switch back to my old 6300 - as I too miss too many appointments...
    I've just created a topic - and hope there is a solution...
    otherwise it's just iPhone I reckon  

  • Problem with ComponentListener

    Hi,
    I have a component listener for a dialog(JDialog) and when the JDialog is closed by a call to dispose() method, ComponentHidden event is not triggered. But if I use hide() method to close the dialog, then ComponentHidden event is fired properly. Is this a bug or is this the way it was designed?

    I think you should be using a WindowListener

  • 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.

  • Making certain parts of an image transparent laying it on top of another

    I am currently doing an MSc project, where I am simulating the behaviour of ants in Java, however I have hit a stumbling block. Currently, I have an AntTerrain class that contains a paintComponent method. Every time this is called it draws a BufferedImage of the terrain which consists of all the obstacles and food, over which the ants are drawn by iterating through a 2D array. I have been trying to implement pheromones into the simulation, and although I am able to do it I want to have the functionality to be able view or not view them. Initially I had two Buffered images, one containing all the terrain information and the pheromones, and one not containing the pheromones. This became rather costly as the simulation progressed and more pheromones were laid, so recently I have been trying to create a buffered image of just the pheromones which I can overlay onto the terrain as and when the user wants to.
    This has been causing me immense problems. I have had limited success with using the alpha channels of the terrain image, by making it almost completely transparent, then drawing it on top of the terrain image, by setting the compositing to SRC_OVER, however, this muddys the terrain image below.
    I have been looking up various books and documentation on line to try and work out how to do it in a more elegant fashion without success. Peter has come up with the idea of using either Regions of Interest, Bitmasking or a combination of both. Neither of these techniques have been particularly well explained in the documentation I have found and I am more confused than when I started. Any help you could give me in this matter would be greatly appreciated.

    If the pheromones can be drawn independent of the array of ants then I would use a single BufferedImage and make a new one for each user change of pheromone visibility. If this is to unwieldy of if the pheromones require the ant array then I would try an OverlayLayout with the BufferedImage of obstacles/food/etc on the bottom and the pheromones on top. The ants could go on either one; maybe they would look better drawn above the pheromones on the top layer (guessing...). If you want to draw the pheromones with an AlphaComposite and they would look okay drawn above the ants you could draw the ants below and the pheromones above. This would be easy and fast.
    Here's an example of the OverlayLayout option:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.BufferedImage;
    import javax.swing.*;
    public class ToggleTest
        public static void main(String[] args)
            JPanel panel = new JPanel();
            OverlayLayout overlay = new OverlayLayout(panel);
            panel.setLayout(overlay);
            panel.add(new Top());
            panel.add(new Bottom());
            JFrame f = new JFrame("click me");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setContentPane(panel);
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
    class Top extends JPanel
        boolean showPheromones;
        public Top()
            showPheromones = false;
            setOpaque(false);
            addMouseListener(toggler);
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            if(showPheromones)
                int w = getWidth();
                int h = getHeight();
                AlphaComposite ac =
                    AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.25f);
                g2.setComposite(ac);
                g2.setPaint(Color.red);
                g2.fill(new Ellipse2D.Double(w*2/5, h/3, w/3, h/3));
        private MouseListener toggler = new MouseAdapter()
            public void mousePressed(MouseEvent e)
                showPheromones = !showPheromones;
                repaint();
    class Bottom extends JPanel
        BufferedImage image;
        public Bottom()
            addComponentListener(resizer);
        protected void paintComponent(Graphics g)
            if(image == null)
                makeImage();
            g.drawImage(image, 0, 0, this);
        private BufferedImage makeImage()
            int w = getWidth();
            int h = getHeight();
            image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2 = image.createGraphics();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setBackground(UIManager.getColor("Panel.background"));
            g2.clearRect(0, 0, w, h);
            g2.setPaint(Color.red);
            g2.draw(new Ellipse2D.Double(w/2, h/5, w/9, h/3));
            g2.setPaint(Color.green.darker());
            g2.draw(new Ellipse2D.Double(25, 16, w/6, h/2));
            g2.setPaint(Color.blue);
            g2.draw(new Ellipse2D.Double(w/4, h*5/6, 125, 25));
            g2.setPaint(Color.blue);
            g2.draw(new Ellipse2D.Double(w*5/9, h/2, 55, 60));
            g2.dispose();
            return image;
        private ComponentListener resizer = new ComponentAdapter()
            public void componentResized(ComponentEvent e)
                image = null;
                repaint();
    }

  • Problem with painting/threads/ProgressMonitor

    Hello,
    I'll try to be clear, ask me anything if it isn't. I have two threads, one that downloads some selected webpages, and the other that reads them. In the thread that reads, there is a ProgressMonitor object, which indicate how many webpages have been read.
    I created a JUnit test which works as expected. One thread downloads, the other reads and a nice little progress monitor appears and everything works.
    I transfered the code (the part of the code starting the thread that reads, which starts the thread that downloads) into the main application. The threads are working and the ProgressMonitor appears, but it does not draw the components (there is no label, progress bar, button etc...). I can't seem to find the problem. I think it is caused by the threads or synchronized methods, I am not sure as I am no expert with threads. Once the threads have finished running, the components of the ProgressMonitor appears. So I guess that the threads are blocking the (re)painting of the application, but I can't figure why. Im using Thread.yield() quite often. Priorities problem ? Here some parts of the code :
    JUnit Test code :
         public synchronized void testHarvest() {
              JFrame frame = new JFrame("Super");
              frame.setVisible(true);
              Harvester harvester = new Harvester(
                        frame,
                        new Rule());
              Thread harvest = new Thread(harvester);
              harvest.start();
              try {
                   harvest.join();
              } catch (InterruptedException ie) {}
    ...Main application :
    Code:
    public class Gui extends JFrame implements ComponentListener {
       private static JFrame mMotherFrame = null;
        public Gui() {
            mMotherFrame = this;
        private class GuiActionRealize {
              public synchronized void getFromWeb() {
                   Harvester harvester = new Harvester(
                             mMotherFrame,
                             new Rule());
                   Thread harvest = new Thread(harvester);
                   harvest.start();               
                   try {                    
                        harvest.join();
                   } catch (InterruptedException ie) {}
    }Harvester :
    Code:
    public class Harvester implements Runnable {
      private JFrame mMotherFrame;
      private ProgressMonitor mMonitor;
    public Harvester(JFrame owner, IRule subjectRule) {
       mMotherFrame = owner;
        public void find() {
        mMonitor = new ProgressMonitor(mMotherFrame, "Downloading from the Internet.", "", 1, mAcceptedURLs.size());
         mMonitor.setMillisToDecideToPopup(0);
         mMonitor.setMillisToPopup(0);
    public void run() {
      find();
      mHarvested = harvest();
      mFinished = true;
      Thread.yield();
    public List harvest() {
      download = new DownloadThread(this, mAcceptedURLs);
      Thread downthread = new Thread(download);
      downthread.start(); int i = 0;
      while (!mMonitor.isCanceled()) {
          while (download.getDownloadedDocuments().isEmpty()) {
               try {
                       Thread.yield();
                       Thread.sleep(300);
                } catch (InterruptedException ie) {}
           mMonitor.setNote("Downloading decision " + i);
           mMonitor.setProgress(mMonitor.getMinimum()+ ++i);
           } // end while(!cancel)
           download.kill();
           return mHarvested;
    }I'm very puzzled by the fact that it worked in the JUnit Case and not in the application.
    I can see that the thread that is responsible for drawing components is not doing his job, since that the mother frame (Gui class) is not being repainted while the harvest/download threads are working. That's not the case in the JUnit case, where the frame is being repainted and everything is fine. This is the only place in the application that I'm using threads/runnable objects.
    I also tried making the Gui class a thread by implementing the Runnable interface, and creating the run method with only a repaint() statement.
    And I tried setting the priority of the harvest thread to the minimum. No luck.
    If you need more info/code, let me know, Ill try to give as much info as I can.
    Thank you

    Why are you painting the values yourself? Why don't you just add the selected values to a JList, or create a container with a GridLayout and add a JLabel with the new text to the container.
    Every time you call the paintComponent() method the painting gets done from scratch so you would need to keep a List of selected items and repaint each item every time. Maybe this [url http://forum.java.sun.com/thread.jsp?forum=57&thread=304939]example will give you ideas.

  • I need help with TransparentBackgrounds for a school project

    So i had found the transparentBackground class
    * @(#)TransparentBackground.java
    * @author
    * @version 1.00 2010/2/26
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.text.NumberFormat;
    public class TransparentBackground extends JComponent implements ComponentListener, WindowFocusListener, Runnable{
        private JFrame frame;
        private Image background;
         private long _lastUpdate = 0;
         private boolean _refreshRequested = true;
         public Robot rbt;
         public Toolkit tk;
         public Dimension dim;
         public Point pos;
         public Point offset;
         long total;
         long used;
    public TransparentBackground(JFrame frame) {
        this.frame = frame;
        updateBackground();
        frame.addComponentListener(this);
         frame.addWindowFocusListener(this);
        new Thread(this).start();
    public void updateBackground( ) {
        try {
             total = Runtime.getRuntime().totalMemory();
             used  = (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())/1024;
             System.out.println("updateBackground() Run: Memory Usage: " + used +" MB");
            rbt = new Robot();
            tk = Toolkit.getDefaultToolkit( );
            dim = tk.getScreenSize( );
            background = rbt.createScreenCapture(
            new Rectangle(0,0,(int)dim.getWidth( ),
                              (int)dim.getHeight( )));
        } catch (Exception ex) {
    public void paintComponent(Graphics g) {
         System.out.println("paintComponent() Run");
        pos = this.getLocationOnScreen();
        offset = new Point(-pos.x,-pos.y);
        g.drawImage(background,offset.x,offset.y,null);
    protected void refresh() {
              if (frame.isVisible() && this.isVisible()) {
                   repaint();
                   _refreshRequested = true;
                   _lastUpdate = System.currentTimeMillis();
              System.out.println("refresh() Run");
    // ComponentListener -------------------------------------------------------
         public void componentHidden(ComponentEvent e) {
         public void componentMoved(ComponentEvent e) {
              repaint();
         public void componentResized(ComponentEvent e) {
              repaint();
         public void componentShown(ComponentEvent e) {
              repaint();
         // WindowFocusListener -----------------------------------------------------
         public void windowGainedFocus(WindowEvent e) {
              refresh();
         public void windowLostFocus(WindowEvent e) {
              refresh();
    public void run() {
              try {
                   while (true) {
                        Thread.sleep(10);
                        long now = System.currentTimeMillis();
                        if (_refreshRequested && ((now - _lastUpdate) > 100)) {
                             if (frame.isVisible()) {
                                  Point location = frame.getLocation();
                                  frame.setLocation(-frame.getWidth(), -frame.getHeight());
                                  updateBackground();
                                  frame.setLocation(location);
                                  refresh();
                             _lastUpdate = now;
                             _refreshRequested = false;
                             System.out.println("run() END------------");
              } catch (InterruptedException e) {
                   e.printStackTrace();
    }In have like 8 - 12 of these "panels" in my program. They are not running simultaneously but each one is created everytime I press a button.
    I have A button ing main class (x) and another class (y)
    Class y
    public JFrame Frame;
    public TransparentBackground Panel;
    class y()
    public void makeMe()
    Frame = new JFrame(" ");
         Panel= new TransparentBackground(Frame);
      ///   ....all the combining
       // and then
       frame.setVisible(true);
    public void hideMe()
         frame.setVisible(false);
    }When press A which has only one instanciation of class y:
    it calls
    y.makeMe()
    and then it when I press it again
    it calls
    y.hideMe()
    and then this same process goes on for like 8 times before it starts to show this
    updateBackground() Run: Memory Usage: 248606 MB
    Exception in thread "Thread-25" java.lang.OutOfMemoryError: Java heap space
        at sun.awt.windows.WRobotPeer.getRGBPixels(WRobotPeer.java:46)
        at java.awt.Robot.createScreenCapture(Robot.java:329)
        at TransparentBackground.updateBackground(TransparentBackground.java:45)
        at TransparentBackground.run(TransparentBackground.java:104)
        at java.lang.Thread.run(Thread.java:619)
    paintComponent() Run
    refresh() Run
    paintComponent() RunBTW: the x and y class are just skeletal classes, but the actual ones I use in the programs are filled with Images and all that good stuff..
    So my ulimate question is..
    Why dose it make that error?
    and i also tried to increase the heap space, but it still showed the same error.
    I am just a newbie, so i would appreciate if the explainations are easier to understand for beginners
    thank you for reading and taking interest

    I don't understand you GUI approach at all: you are making a very basic board game. You need not even do an animation loop as a continuously running process. While I have not gone over your code extensively, what your errors and glimpsing at your code says to me is that you don't have your objects being disposed of because they are running--your "while(true)" loop is not being canceled/stopped.
    You need to make a very basic animation loop and look at making your events happen accordingly. You can easily paint your cards/messages over portions of the playing screen and have them age off with a timer or other triggered events--this removes the need of your while(true) loops and runnable objects.
    On the other hand, you do not need to implement runnable nor have a running animation loop with a basic GUI. When you have your "cards" pop up, they need not be objects that implement runnable either, but just basic GUI components.
    Anyways, I'm just at a loss as to your need to have everything implement runnable.

  • Problems with 'background' JFrame focus when adding a modal JDialog

    Hi all,
    I'm trying to add a modal JDialog to my JFrame (to be used for data entry), although I'm having issues with the JFrame 'focus'. Basically, at the moment my program launches the JFrame and JDialog (on program load) fine. But then - if I switch to another program (say, my browser) and then I try switching back to my program, it only shows the JDialog and the main JFrame is nowhere to be seen.
    In many ways the functionality I'm looking for is that of Notepad: when you open the Find/Replace box (albeit it isn't modal), you can switch to another program, and then when you switch back to Notepad both the main frame and 'JDialog'-esque box is still showing.
    I've been trying to get this to work for a couple of hours but can't seem to. The closest I have got is to add a WindowFocusListener to my JDialog and I hide it via setVisible(false) once windowLostFocus() is fired (then my plan was to implement a similar functionality in my JFrame class - albeit with windowGainedFocus - to show the JDialog again, i.e. once the user switches back to the program). Unfortunately this doesn't seem to work; I can't seem to get any window or window focus listeners to actually fire any methods, in fact?
    I hope that kind of makes sense lol. In short I'm looking for Notepad CTRL+R esque functionality, albeit with a modal box. As for a 'short' code listing:
    Main.java
    // Not all of these required for the code excerpt of course.
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.GraphicsEnvironment;
    import java.awt.Rectangle;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.ComponentAdapter;
    import java.awt.event.ComponentEvent;
    import java.awt.event.FocusEvent;
    import java.awt.event.FocusListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowFocusListener;
    import java.awt.event.WindowListener;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JSplitPane;
    import javax.swing.UIManager;
    import javax.swing.plaf.basic.BasicSplitPaneDivider;
    import javax.swing.plaf.basic.BasicSplitPaneUI;
    public class Main extends JFrame implements ActionListener, WindowFocusListener, WindowListener, FocusListener {
         static JFrame frame;
         private static int programWidth;
         private static int programHeight;
         private static int minimumProgramWidth = 700;
         private static int minimumProgramHeight = 550;
         public static SetupProject setupProjectDialog;
         public Main() {
              // Setup the overall GUI of the program
         private static void createSetupProjectDialog() {
              // Now open the 'Setup Your Project' dialog box
              // !!! Naturally this wouldn't auto-open on load if the user has already created a project
              setupProjectDialog = new SetupProject( frame, "Create Your Website Project", true );
              // Okay, for this we want it to be (say) 70% of the progamWidth/height, OR *slightly* (-25px) smaller than the minimum size of 700/550
              // Change (base on programWidth/Height) then setLocation
              int currProgramWidth = getProgramWidth();
              int currProgramHeight = getProgramHeight();
              int possibleWidth = (int) (currProgramWidth * 0.7);
              int possibleHeight = (int) (currProgramHeight * 0.7);
              // Set the size and location of the JDialog as needed
              if( (possibleWidth > (minimumProgramWidth-25)) && (possibleHeight > (minimumProgramHeight-25)) ) {
                   setupProjectDialog.setPreferredSize( new Dimension(possibleWidth,possibleHeight) );
                   setupProjectDialog.setLocation( ((currProgramWidth/2)-(possibleWidth/2)), ((currProgramHeight/2)-(possibleHeight/2)) );
               else {
                   setupProjectDialog.setPreferredSize( new Dimension( (minimumProgramWidth-25), (minimumProgramHeight-25)) );
                   setupProjectDialog.setLocation( ((currProgramWidth/2)-((minimumProgramWidth-25)/2)), ((currProgramHeight/2)-((minimumProgramHeight-25)/2)) );
              setupProjectDialog.setResizable(false);
              setupProjectDialog.toFront();
              setupProjectDialog.pack();
              setupProjectDialog.setVisible(true);
         public static void main ( String[] args ) {
              Main frame = new Main();
              frame.pack();
              frame.setVisible(true);
              createSetupProjectDialog();
            // None of these get fired when the Jframe is switched to. I also tried a ComponentListener, but had no joy there either.
         public void windowGainedFocus(WindowEvent e) {
              System.out.println("Gained");
              setupProjectDialog.setVisible(true);
         public void windowLostFocus(WindowEvent e) {
              System.out.println("GainedLost");
         public void windowOpened(WindowEvent e) {
              System.out.println("YAY1!");
         public void windowClosing(WindowEvent e) {
              System.out.println("YAY2!");
         public void windowClosed(WindowEvent e) {
              System.out.println("YAY3!");
         public void windowIconified(WindowEvent e) {
              System.out.println("YAY4!");
         public void windowDeiconified(WindowEvent e) {
              System.out.println("YAY5!");
         public void windowActivated(WindowEvent e) {
              System.out.println("YAY6!");
         public void windowDeactivated(WindowEvent e) {
              System.out.println("YAY7!");
         public void focusGained(FocusEvent e) {
              System.out.println("YAY8!");
         public void focusLost(FocusEvent e) {
              System.out.println("YAY9!");
    SetupProject.java
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowEvent;
    import java.awt.event.WindowFocusListener;
    import java.awt.event.WindowListener;
    import java.io.IOException;
    import java.net.URL;
    import javax.imageio.ImageIO;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    public class SetupProject extends JDialog implements ActionListener {
         public SetupProject( final JFrame frame, String title, boolean modal ) {
              // Setup the JDialog
              super( frame, title, modal );
              setDefaultCloseOperation( JDialog.DISPOSE_ON_CLOSE );
              // Bad code. Is only temporary
              add( new JLabel("This is a test.") );
              // !!! TESTING
              addWindowFocusListener( new WindowFocusListener() {
                   public void windowGainedFocus(WindowEvent e) {
                        // Naturally this now doesn't get called after the setVisible(false) call below
                   public void windowLostFocus(WindowEvent e) {
                        System.out.println("Lost");
                        setVisible(false); // Doing this sort of thing since frame.someMethod() always fires a null pointer exception?!
    }Any help would be very much greatly appreciated.
    Thanks!
    Tristan

    Hi,
    Many thanks for the reply. Isn't that what I'm doing with the super() call though?
    As in, in Main.java I'm doing:
    setupProjectDialog = new SetupProject( frame, "Create Your Website Project", true );Then the constructor in SetupProject is:
    public SetupProject( final JFrame frame, String title, boolean modal ) {
              // Setup the JDialog
              super( frame, title, modal );
              And isn't the super call (since the class extends JDialog) essentially like doing new JDialog(frame,title,modal)?
    If not, that would make sense due to the null pointer exception errors I've been getting. Although I did think I'd done it right hence am confused as to the right way to handle this,if so.
    Thanks,
    Tristan
    Edited by: 802573 on 20-Oct-2010 08:27

  • Trying to make a WrappingComboBox

    Inspired by a fairly straightforward WrappingList, I thought I'd try to make a Wrapping JScrollPane. The goal is a ScrollPane that automatically wraps the text inside it. I've just about got it, but I have one thing that's not working. If I just put the JTextArea{s} in as the Editor, then you lose the any text that doesn't fit inside whatever the initial size was. Instead, I put the JTextAreas inside a JScrollPane which works fine, except that I still have to determine the size of the JScrollPane in advance. I would like to make each Editor/JScrollPane start out with just a single line of text and expand until it reaches a certain small number of lines.
    Here is my attempt at a WrappingComboBox
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.Insets;
    import java.awt.LayoutManager;
    import java.awt.Rectangle;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.ComponentEvent;
    import java.awt.event.ComponentListener;
    import java.awt.event.InputMethodEvent;
    import java.awt.event.InputMethodListener;
    import java.util.Vector;
    import javax.swing.BoxLayout;
    import javax.swing.ComboBoxEditor;
    import javax.swing.JComboBox;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JList;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JViewport;
    import javax.swing.ListCellRenderer;
    import javax.swing.ScrollPaneConstants;
    import javax.swing.SwingUtilities;
    import javax.swing.event.EventListenerList;
    import javax.swing.plaf.basic.BasicComboBoxUI;
    import javax.swing.plaf.basic.BasicComboPopup;
    import javax.swing.plaf.basic.ComboPopup;
    import javax.swing.text.View;
    import debibdup.ScrollablePanel.ScrollableSizeHint;
    * @author jfolson
    public class WrappingComboBox extends JComboBox {
         WrappingComboBox() {
              super();
              this.setUI(new WrappingComboBoxUI());
         WrappingComboBox(Vector<?> items) {
              super(items);
              this.setUI(new WrappingComboBoxUI());
         public static class WrappingComboBoxUI extends BasicComboBoxUI {
              WrappingHelper wrappingHelper;
              public WrappingComboBoxUI() {
                   super();
              public WrappingHelper getWrappingHelper() {
                   if (wrappingHelper == null)
                        wrappingHelper = new WrappingHelper();
                   return wrappingHelper;
              /* Since my Editor, Renderer and Popup are not UIResources, I have to overload these methods
               * or else installUI would call BasicComboBoxUI.createXXX anyway and replace mine
              @Override
              protected ComboBoxEditor createEditor() {
                   return new WrappingComboBoxEditor();
              /* See note for createEditor()
              @Override
              protected ListCellRenderer createRenderer() {
                   return new WrappingList.WrappingListCellRenderer();
              /* See note for createEditor()
              @Override
              protected ComboPopup createPopup() {
                   return new BasicComboPopup(comboBox) {
                        @Override
                        protected JList createList() {
                             // use the WrappingList for the popup to make it update its
                             // sizes
                             return new WrappingList(comboBox.getModel());
                             // BasicComboPopup overrides default, apparently fixes some
                             // bug but I can't use it because BasicGraphicsUtils
                             // functions are private
                             /*return new JList(comboBox.getModel()) {
                                  @Override
                                  public void processMouseEvent(MouseEvent e) {
                                       if (BasicGraphicsUtils.isMenuShortcutKeyDown(e)) {
                                            // Fix for 4234053. Filter out the Control Key
                                            // from the list.
                                            // ie., don't allow CTRL key deselection.
                                            Toolkit toolkit = Toolkit.getDefaultToolkit();
                                            e = new MouseEvent((Component) e.getSource(), e
                                                      .getID(), e.getWhen(), e.getModifiers()
                                                      ^ toolkit.getMenuShortcutKeyMask(), e
                                                      .getX(), e.getY(), e.getXOnScreen(), e
                                                      .getYOnScreen(), e.getClickCount(), e
                                                      .isPopupTrigger(), MouseEvent.NOBUTTON);
                                       super.processMouseEvent(e);
              /*Have to overrige getMinimumSize, rectangleForCurrentValue and layoutContainer in the Helper class
               * to make a smaller (reasonable) sized popup button, otherwise, for multi-line combobox you get
               *  ridiculously large buttons.
              @Override
              public Dimension getMinimumSize(JComponent c) {
                   if (!isMinimumSizeDirty) {
                        return new Dimension(cachedMinimumSize);
                   Dimension size = getDisplaySize();
                   Insets insets = getInsets();
                   // calculate the width and height of the button
                   int buttonHeight = size.height;
                   if (buttonHeight > arrowButton.getPreferredSize().width)
                        buttonHeight = arrowButton.getPreferredSize().width;
                   int buttonWidth = arrowButton.getPreferredSize().width;
                   // adjust the size based on the button width
                   size.height += insets.top + insets.bottom;
                   size.width += insets.left + insets.right + buttonWidth;
                   cachedMinimumSize.setSize(size.width, size.height);
                   isMinimumSizeDirty = false;
                   return new Dimension(size);
               * Returns the area that is reserved for drawing the currently selected
               * item.
              @Override
              protected Rectangle rectangleForCurrentValue() {
                   int width = comboBox.getWidth();
                   int height = comboBox.getHeight();
                   Insets insets = getInsets();
                   int buttonSize = height - (insets.top + insets.bottom);
                   if (arrowButton != null) {
                        buttonSize = arrowButton.getWidth();
                   if (true) {// BasicGraphicsUtils.isLeftToRight(comboBox)) { // this
                        // method is not visible
                        return new Rectangle(insets.left, insets.top, width
                                  - (insets.left + insets.right + buttonSize), height
                                  - (insets.top + insets.bottom));
                   } else { // if I could tell, put the box on the other side for right
                        // to left checkboxes
                        return new Rectangle(insets.left + buttonSize, insets.top,
                                  width - (insets.left + insets.right + buttonSize),
                                  height - (insets.top + insets.bottom));
              @Override
              protected LayoutManager createLayoutManager() {
                   return getWrappingHelper();
              private class WrappingHelper implements LayoutManager {
                   // LayoutManager
                   /* Need to override layoutContainer to put in a smaller popup button
                   public void addLayoutComponent(String name, Component comp) {} // Can't
                   // do
                   // this
                   public void removeLayoutComponent(Component comp) {}
                   public Dimension preferredLayoutSize(Container parent) {
                        return parent.getPreferredSize();
                   public Dimension minimumLayoutSize(Container parent) {
                        return parent.getMinimumSize();
                   public void layoutContainer(Container parent) {
                        JComboBox cb = (JComboBox) parent;
                        int width = cb.getWidth();
                        int height = cb.getHeight();
                        Insets insets = getInsets();
                        int buttonHeight = height - (insets.top + insets.bottom);
                        int buttonWidth = buttonHeight;
                        if (arrowButton != null) {
                             if (buttonHeight > arrowButton.getPreferredSize().width)
                                  buttonHeight = arrowButton.getPreferredSize().width;
                             Insets arrowInsets = arrowButton.getInsets();
                             buttonWidth = arrowButton.getPreferredSize().width
                                       + arrowInsets.left + arrowInsets.right;
                        Rectangle cvb;
                        if (arrowButton != null) {
                             if (true) {// BasicGraphicsUtils.isLeftToRight(cb)) { //
                                  // this method is not visible
                                  arrowButton.setBounds(width
                                            - (insets.right + buttonWidth), insets.top,
                                            buttonWidth, buttonHeight);
                             } else { // if I could tell, put the box on the other side
                                  // for right to left checkboxes
                                  arrowButton.setBounds(insets.left, insets.top,
                                            buttonWidth, buttonHeight);
                        if (editor != null) {
                             cvb = rectangleForCurrentValue();
                             editor.setBounds(cvb);
         public static class WrappingComboBoxEditor extends JScrollPane implements
                   ComboBoxEditor, ComponentListener {
              EventListenerList listenerList = new EventListenerList();
              LineAwareTextArea text;
              public WrappingComboBoxEditor() {
                   super();
                   this.text = new LineAwareTextArea();
                   this.setViewportView(text);
                   setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
                   setPreferredSize(new Dimension(100, 30));
                   this.setItem("");
                   text.setLineWrap(true);
                   text.setWrapStyleWord(false);
                   text.setEditable(true);
                   text.addInputMethodListener(new InputMethodListener() {
                        @Override
                        public void caretPositionChanged(InputMethodEvent arg0) {}
                        @Override
                        public void inputMethodTextChanged(InputMethodEvent arg0) {
                             Object[] listeners = WrappingComboBoxEditor.this.listenerList
                                       .getListenerList();
                             // Process the listeners last to first, notifying
                             // those that are interested in this event
                             ActionEvent actionEvent = null;
                             for (int i = listeners.length - 2; i >= 0; i -= 2) {
                                  if (listeners[i] == ActionListener.class) {
                                       if (actionEvent == null)
                                            actionEvent = new ActionEvent(this,
                                                      ActionEvent.ACTION_PERFORMED, null);
                                       ((ActionListener) listeners[i + 1])
                                                 .actionPerformed(actionEvent);
                   text.addComponentListener(this);
              @Override
              public void addActionListener(ActionListener l) {
                   listenerList.add(ActionListener.class, l);
              @Override
              public Component getEditorComponent() {
                   return this;
              @Override
              public Object getItem() {
                   return text.getText();
              @Override
              public void removeActionListener(ActionListener l) {
                   listenerList.remove(ActionListener.class, l);
              @Override
              public void setItem(Object anObject) {
                   if (anObject == null)
                        text.setText("");
                   else
                        text.setText(String.valueOf(anObject));
              @Override
              public void selectAll() {
                   text.selectAll();
              public void componentHidden(ComponentEvent arg0) {}
              public void componentMoved(ComponentEvent arg0) {}
              @Override
              public void componentResized(ComponentEvent arg0) {
                   JViewport view = this.getViewport();
                   Dimension viewDim = view.getExtentSize();
                   Insets insets = view.getInsets();
                   System.out.println("actual view height: " + viewDim.height);
                   Dimension wantDim = text.getPreferredScrollableViewportSize();
                   if (wantDim.height > viewDim.height) {
                        viewDim.height = wantDim.height + insets.top + insets.bottom;
                        view.setPreferredSize(viewDim);
                        view.revalidate();
                        ((JComponent) this.getParent()).revalidate();
                        //SwingUtilities.windowForComponent(this).pack(); //even this doesn't work
              @Override
              public void componentShown(ComponentEvent arg0) {}
          * Only really need to expose rowHeight but might as well determine the
          * correct size it wants its viewport
          * @author jfolson
         public static class LineAwareTextArea extends JTextArea {
              private int maxVisibleRows = 3;
              public LineAwareTextArea() {
                   super();
              public LineAwareTextArea(String text) {
                   this();
                   setText(text);
              @Override
              public Dimension getPreferredScrollableViewportSize() {
                   Dimension d = this.getPreferredSize();
                   float hspan = getWidth();
                   View view = (getUI()).getRootView(this);
                   view.setSize(hspan, Float.MAX_VALUE);
                   float vspan = view.getPreferredSpan(View.Y_AXIS);
                   Insets insets = getInsets();
                   int rows = (d.height / this.getRowHeight());
                   if (rows > maxVisibleRows)
                        rows = maxVisibleRows;
                   d.height = rows * getRowHeight() + insets.top + insets.bottom;
                   System.out.println("prefer view height: " + d.height + " (" + rows
                             + " line(s))");  // this is here just so I can see that it's getting the right number of desired lines.
                   return d;
              public void setMaxVisibleRows(int rows) {
                   this.maxVisibleRows = rows;
              public int getMaxVisibleRows() {
                   return this.maxVisibleRows;
         public static class ComboTest extends JFrame {
              public ComboTest() {
                   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   init();
                   pack();
                   show();
              private void init() {
                   ScrollablePanel mainPanel = new ScrollablePanel();
                   mainPanel.setScrollableWidth(ScrollableSizeHint.FIT);
                   mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
                   ScrollablePanel fieldPanel = new ScrollablePanel();
                   fieldPanel.setLayout(new BoxLayout(fieldPanel, BoxLayout.X_AXIS));
                   fieldPanel.setScrollableWidth(ScrollableSizeHint.FIT);
                   Vector<String> items = new Vector<String>();
                   items.add("Item One");
                   JComboBox list = new WrappingComboBox(items);
                   list.setEditable(true);
                   JLabel fieldLabel = new JLabel("Label: ");
                   fieldLabel.setAlignmentY(TOP_ALIGNMENT);
                   list.setAlignmentY(TOP_ALIGNMENT);
                   fieldPanel.add(fieldLabel);
                   fieldPanel.add(list);
                   mainPanel.add(fieldPanel);
                   fieldPanel = new ScrollablePanel();
                   fieldPanel.setLayout(new BoxLayout(fieldPanel, BoxLayout.X_AXIS));
                   fieldPanel.setScrollableWidth(ScrollableSizeHint.FIT);
                   items
                             .add("Item Two content content content content Item Two content content content content Item Two content content content content Item Two content content content content");
                   list = new WrappingComboBox(items);
                   list.setEditable(true);
                   fieldLabel = new JLabel("Label: ");
                   fieldLabel.setAlignmentY(TOP_ALIGNMENT);
                   list.setAlignmentY(TOP_ALIGNMENT);
                   fieldPanel.add(fieldLabel);
                   fieldPanel.add(list);
                   mainPanel.add(fieldPanel);
                   JScrollPane mainScrolls = new JScrollPane(mainPanel,
                             JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                             JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
                   mainScrolls.setPreferredSize(new Dimension(200, 200));
                   setContentPane(mainScrolls);
         public static void main(String[] args) {
              new ComboTest();
    }And here is the WrappingList that it references
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.Insets;
    import javax.swing.JFrame;
    import javax.swing.JList;
    import javax.swing.JScrollPane;
    import javax.swing.JTextPane;
    import javax.swing.ListCellRenderer;
    import javax.swing.ListModel;
    import javax.swing.border.EmptyBorder;
    import javax.swing.plaf.basic.BasicListUI;
    import javax.swing.text.View;
    * List that wraps its text! Whenever the list's layout (e.g. size) changes the
    * list's UI is instructed to update its layout too.
    public class WrappingList extends JList {
         public WrappingList() {
              setUI(new WrappingListUI());
              setCellRenderer(new WrappingListCellRenderer());
         public WrappingList(ListModel model) {
              super(model);
              setUI(new WrappingListUI());
              setCellRenderer(new WrappingListCellRenderer());
         @Override
         public void doLayout() {
              ((WrappingListUI) getUI()).updateLayoutState();
              super.doLayout();
         @Override
         public boolean getScrollableTracksViewportWidth() {
              return true;
          * ListUI implementation that exposes the method for updating its layout
         private static class WrappingListUI extends BasicListUI {
              @Override
              public void updateLayoutState() {
                   super.updateLayoutState();
          * List cell renderer that uses the list's width to alter its preferred size
          * TODO - override bound properties in the same way as
          * DefaultListCellRenderer
         public static class WrappingListCellRenderer extends JTextPane implements
                   ListCellRenderer {
              public WrappingListCellRenderer() {
                   setBorder(new EmptyBorder(1, 1, 1, 1));
              public Component getListCellRendererComponent(JList list, Object value,
                        int index, boolean selected, boolean hasFocus) {
                   setBackground(selected ? list.getSelectionBackground() : list
                             .getBackground());
                   setForeground(selected ? list.getSelectionForeground() : list
                             .getForeground());
                   // TODO - border, font etc.
                   setText(String.valueOf(value));
                   float hspan = list.getWidth();
                   View view = (getUI()).getRootView(this);
                   view.setSize(hspan, Float.MAX_VALUE);
                   float vspan = view.getPreferredSpan(View.Y_AXIS);
                   Insets insets = getInsets();
                   setPreferredSize(new Dimension(insets.left + insets.right
                             + (int) hspan, insets.top + insets.bottom + (int) vspan));
                   return this;
         public static void main(String[] args) {
              new Test();
         public static class Test extends JFrame {
              public Test() {
                   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   init();
                   pack();
                   show();
              private void init() {
                   JList list = new WrappingList();
                   list
                             .setListData(new Object[] {
                                       "Item One",
                                       "Item Two content content content content Item Two content content content content Item Two content content content content Item Two content content content content" });
                   setContentPane(new JScrollPane(list,
                             JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                             JScrollPane.HORIZONTAL_SCROLLBAR_NEVER));
    }You can verify (in System.out) that the preferred size is larger than the actual default size once you switch to the longer value in the combo box, but the actual size doesn't change. I've tried setSize, setMinimumSize, nothing makes the JScrollPane/Editor any larger. I've also tried calling and not calling various combinations of revalidate(), getParent().revalidate() and getViewport().revalidate(). What am I missing?
    Edited by: inspired2apathy on Oct 16, 2010 7:22 PM

    inspired2apathy wrote:
    ... The goal is a ScrollPane that automatically wraps the text inside it. I've just about got it, but I have one thing that's not working. If I just put the JTextArea{s} in as the Editor, then you lose the any text that doesn't fit inside whatever the initial size was. Instead, I put the JTextAreas inside a JScrollPane which works fine, except that I still have to determine the size of the JScrollPane in advance. I would like to make each Editor/JScrollPane start out with just a single line of text and expand until it reaches a certain small number of lines.
    ... What am I missing?THE BASICS. See if this isn't what you are trying to do.
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    public class Test
      public static void main(String[] args) {
        JTextArea ta = new JTextArea();
        ta.setLineWrap(true);
        ta.setWrapStyleWord(true);
        JScrollPane sp = new JScrollPane(ta);
        JFrame f = new JFrame();
        f.getContentPane().add(sp, "Center");
        f.setBounds(0, 0, 400, 300);
        f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
        f.setVisible(true); 
    }OP, your code was too long and complicated for me to compile and run. However, aren't you forgetting the two simple methods <tt>JTextArea.setLineWrap()</tt> and <tt>JTextArea.setWrapStyleWord()</tt>? Furthermore, I absolutely see no need for you to extend SWING components for demonstration this simple -- that is, if I understand your problem correctly.

  • Executable JAR file: Could not find the main class.

    Hello,
    I have a problem with making an executable JAR file.
    I have written a JAVA program that consists of five different classes of which User.java is the main class and I have saved a text document with Main-Class: User and a blank line after that.
    If I try:
    jar cmf MainClass.txt User.jar User.class Beheerder.class Operator.class Manager.class MaakVisueelSchema.class
    it makes a executable jar file which actually works! :)
    But when the Operator class trys to open the MaakVisueelSchema class the screen stays blank.
    I can run MaakVisueelSchema with java MaakVisueelSchema.
    So I tried to make an executable JAR that consists only of MaakVisueelSchema, the same way as I did for User:
    Main-Class: MaakVisueelSchema
    jar cmf MainClass.txt MaakVisueelSchema.jar MaakVisueelSchema.class
    Then I get the error message:
    Could not find the main class. Program will exit.
    from the Java Virtual Machine Launcher.
    The big difference between MaakVisueelSchema and the other classes is that MaakVisueelSchema contains a PaintComponent method and an ComponentListener. Is it possible that one of those creates the error?
    Can anyone help me with this problem?
    Thanks in advance!
    Bye!

    Yes,
    I tried:
    jar xvf MaakVisueelSchema.jar
    and it returns:
    META-INF/
    META-INF/MANIFEST.MF
    MaakVisueelSchema.classN/G. You need to manually create a manifest file in a text editor, have it point to your main class, and enter it in your jar command as an argument.

  • How to find out the port of CORBA on OAS

    Hi everyone,
    I am using OAS 4.0.8 on Solaris 5.6. From the manager, I can
    get port number for name service and ORB port respectively.
    However I still get this error:
    Communication error: Failure to access
    http://208.178.96.174:42/ows-bin/rmproxy.ior; listener
    inaccessible or configured wrongly ; nested exception:
    java.net.UnknownServiceException: no content-type
    [Root exception is java.net.UnknownServiceException: no content-
    type]javax.naming.NamingException: Failure to access
    http://208.178.96.174:42/ows-bin/rmproxy.ior; listener
    inaccessible or configured wrongly ; nested exception
    Thank you in advance.
    null

    It's a kind of hierarchy where each component has a position relative to the container that holds it. The location of the program's top level window is relative to the screen coordinates.
    You can add a ComponentListener to the top level window to respond to it being moved or resized.

  • How to find out the location of a point on my program on desktop?

    I am trying to build a java program then need to track where is specific point of the program at the desktop. For example, if I move my program at the top left, the x and y should be (0,0), then when move to another point on the destop, the x and y would be updated.
    I searched in internet for long time but still cannot find it. Seem like getLocation() just get me the location of something in a program and the location of that part within the program.
    Thanks!

    It's a kind of hierarchy where each component has a position relative to the container that holds it. The location of the program's top level window is relative to the screen coordinates.
    You can add a ComponentListener to the top level window to respond to it being moved or resized.

  • Any way to get at the title bar in JFrame?

    I'd like to either add a button to the title bar (title pane?) or override the behavior of the resize button. As far as I can tell, the LookNFeel classes don't allow you to add anything, just change colors, icons, etc. The WindowListener classes don't let you get at the resize button. I don't want to override Component.setSize() (that causes other problems), I just want to have the resize button do something different (or add another button).
    I'd appreciate any ideas!

    1) You could create your own frame that extends JWindow. This would be quite involved, since you'd need to make it respond to mouse drags, mouse resizing etc explicitly (if you wanted that functionality), but you would be able to add your own custom border, which you could make to look like a system border, or you could make comletely different.
    2) I don't know this could be persuaded to do what you want, but you could try adding a ComponentListener to the JFrame to check for resizes, and take action accordingly

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

Maybe you are looking for

  • Adobe Reader plugin(Acrobat) won't install and Update in FF4

    if I try to open FF4 and go to a pdf file Adobe Reader 10 will open then freeze FF4... I then went to Plugin check.. says Adobe Acrobat needs an Update.. I d/l it 3x.. still comes up as needing an upadate after restarting FF4... it just won't take it

  • Controling HTML form Radio Button

    I'm working on automating the check-in and check-out of items in a process queue, but the process queue is web-based. I can input usernames, lot IDs, passwords, and "press" submit buttons programatically by using ActiveX IWebBrowser2 properties (and

  • Complete My Album

    I am trying to purchase the album Dick Diver - Calendar Days. Track 2, Alice, already exists on an EP which I have previously downloaded. iTunes is giving me the "Complete My Album" option, even though this would mean that the album would be missing

  • View 6 persona management service

    I'm troubleshooting a Persona Management issue in View 6.0.1 (we had the same issue in 5.3 but didn't trouble shoot as I was already in the process of building a 6.0 environment from scratch). In my troubleshooting I noticed something that I need cla

  • Illustrator CS4 no longer previews fonts in Character palette after Yosemite upgrade

    Howdy. Recently upgraded to Yosemite. In my copy of Adobe CS4, fonts no longer preview in the dropdown menu of the Character palette, unless the mouse rolls over them. Very frustrating. Does this occur with any other version of Illustrator? Any way I