Display image in java.awt.List

hello guys,
How i can display image in java.awt.List means listbox. give me sample code. if you have
Waiting for your favorable reply.
Regards,
Bhavesh Kharwa

java.awt.List you can not.
javax.swing.JLast you can.

Similar Messages

  • Problem with Horizontal Scroll on java.awt.List

    I use the same code for a General Application as a CDC Application.
    I have no problem at all with the General Application but on the CDC I can't scroll to the right (horizontal).
    Why do I get this problem on the CDC application and not on a regular application?
    I use the PP-1.0 Profile for the CDC application. Does it not support horizontal scroll on java.awt.List?
    This is the code:
    * Main.java
    * Created on den 22 augusti 2007, 10:52
    package cdcapplication6;
    * @author  Erik Rothman
    public class Main extends java.awt.Frame {
        /** Creates new form Main */
        public Main() {
            initComponents();
              for (int i = 0; i < 10; i++) {
                   list1.add("Short text");
                   list1.add("Some very long text indeed. Some very long text indeed.");
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">                         
        private void initComponents() {
            list1 = new java.awt.List();
            addWindowListener(new java.awt.event.WindowAdapter() {
                public void windowClosing(java.awt.event.WindowEvent evt) {
                    exitForm(evt);
            add(list1, java.awt.BorderLayout.CENTER);
            pack();
        }// </editor-fold>                       
        /** Exit the Application */
        private void exitForm(java.awt.event.WindowEvent evt) {                         
            System.exit(0);
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new Main().setVisible(true);
        // Variables declaration - do not modify                    
        private java.awt.List list1;
        // End of variables declaration                  
    }

    I use the same code for a General Application as a CDC Application.
    I have no problem at all with the General Application but on the CDC I can't scroll to the right (horizontal).
    Why do I get this problem on the CDC application and not on a regular application?
    I use the PP-1.0 Profile for the CDC application. Does it not support horizontal scroll on java.awt.List?
    This is the code:
    * Main.java
    * Created on den 22 augusti 2007, 10:52
    package cdcapplication6;
    * @author  Erik Rothman
    public class Main extends java.awt.Frame {
        /** Creates new form Main */
        public Main() {
            initComponents();
              for (int i = 0; i < 10; i++) {
                   list1.add("Short text");
                   list1.add("Some very long text indeed. Some very long text indeed.");
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">                         
        private void initComponents() {
            list1 = new java.awt.List();
            addWindowListener(new java.awt.event.WindowAdapter() {
                public void windowClosing(java.awt.event.WindowEvent evt) {
                    exitForm(evt);
            add(list1, java.awt.BorderLayout.CENTER);
            pack();
        }// </editor-fold>                       
        /** Exit the Application */
        private void exitForm(java.awt.event.WindowEvent evt) {                         
            System.exit(0);
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new Main().setVisible(true);
        // Variables declaration - do not modify                    
        private java.awt.List list1;
        // End of variables declaration                  
    }

  • How to move image in Java Awt.

    Hi ,
    I am developing a simple application using Java awt.
    I have created a application which displays a image. now i want it to move automatically using a timer or something.
    How can i do it. if i have to change the x and y position of the image in which function should i do it?
    Which is the function which is called for every frame?
    Thanks
    Glen.

    public void paint(Graphics g)?
    Are you making a game by any chance?

  • Displaying Image while Dragging in List

    Hi All,
    Am using the List controls to display the data and VBox is
    my itemRenderer. As we all know,by default List/DataGrid provides
    the Drag and drop features.In the itemrenderer am displaying the
    CheckBox and some other controls along with the dataFields and when
    am trying to drag an item it's displayed as in a huge area.
    I want to replace the item with an Image( icon) while
    dragging.How do i do that? I tried with implementing the doDrag of
    Dragmanager but am unable to see any image icon while dragging .
    can anyone solve my problem?
    Any help can be appriciated and Thanks in advance.
    Here is the sample code
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="
    http://www.adobe.com/2006/mxml"
    verticalAlign="middle">
    <mx:Script>
    <![CDATA[
    import mx.collections.ArrayCollection;
    import mx.managers.DragManager;
    import mx.core.DragSource;
    import mx.controls.Image;
    import mx.events.DragEvent;
    import mx.controls.Alert;
    [Bindable]
    private var initData:ArrayCollection = new ArrayCollection([
    {book:"DBMS",author:"Sudarshan"},
    {book:"C",author:"Yaswanth Kanethkar "},
    {book:"C++",author:"JBalaguruswamy"},
    {book:"Software Engineering",author:"Pressman"}]);
    private function onDragOver(event:MouseEvent):void {
    var dragInitiator:List = List(event.currentTarget);
    var dragSource:DragSource = new DragSource();
    dragSource.addData(dragInitiator,"list");
    var displayIcon:Image = new Image();
    displayIcon.source = "resources/images/todo.png";
    DragManager.doDrag(dragInitiator,dragSource,event,displayIcon);
    ]]>
    </mx:Script>
    <mx:List width="50%" height="50%" dragEnabled="true"
    dropEnabled="true" dragMoveEnabled="true"
    dragOver="onDragOver(event)" dataProvider="{initData}">
    <mx:itemRenderer>
    <mx:Component>
    <mx:VBox width="100%" height="100%">
    <mx:HBox>
    <mx:CheckBox/>
    <mx:Label text="Book:{data.book}"/>
    </mx:HBox>
    <mx:Label text="Author:{data.author}"
    paddingLeft="25"/>
    </mx:VBox>
    </mx:Component>
    </mx:itemRenderer>
    </mx:List>
    </mx:Application>

    Hi All,
    Myself find the solution for this problem just by changing
    the
    dragOver event to
    mouseMove event.Now you can test this and can use as well if
    you want.
    Here is the latest code

  • How to display the contents of java.util.list in a frame???

    i should use awt only not applet...
    i need to display the contents of java.util.list in a frame...
    the contents contains rows queried from a oracle database.....
    the contents should be displayed similar to how a lable is displayed..
    please help me out..
    thanks
    dinesh

    Of course there is something in AWT:
    http://java.sun.com/j2se/1.5.0/docs/api/java/awt/List.
    htmlagain, if you carefully read the question, he needs a
    table to display a JDBC result set. There is no
    pre-made table component in AWT.Well, I read that he filled the data into a java.util.List and now wants to display this list. So a List-component should be sufficient. But I might be wrong...
    -Puce

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

  • Displaying image in jlabel

    when displaying an image in a jlable. the jlabel takes on the size of the image. i have tried to set the maximum bounds to the size of the original size of the jlable and even the panel the jlable sits on, but each time that i go to display the picture, it is displayed huge and not the size of the jlabel it is placed in.
    here is my creation code, my gui was created in netbeans.
    pnImage.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
            pnImage.setFocusable(false);
            pnImage.setMaximumSize(new java.awt.Dimension(395, 365));
            lblImage.setFocusable(false);
            lblImage.setMaximumSize(new java.awt.Dimension(395, 365));
            javax.swing.GroupLayout pnImageLayout = new javax.swing.GroupLayout(pnImage);
            pnImage.setLayout(pnImageLayout);
            pnImageLayout.setHorizontalGroup(
                pnImageLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(lblImage, javax.swing.GroupLayout.PREFERRED_SIZE, 393, javax.swing.GroupLayout.PREFERRED_SIZE)
            pnImageLayout.setVerticalGroup(
                pnImageLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(lblImage, javax.swing.GroupLayout.PREFERRED_SIZE, 363, javax.swing.GroupLayout.PREFERRED_SIZE)
            );and here is how i display it.
            Dimension d = pnImage.getSize();
            System.out.println("d = " + d.toString());
            pnImage.setMaximumSize(d);
            lblImage.setMaximumSize(d);
            ImageIcon icon = new ImageIcon(contact.getImage());
            lblImage.setIcon(icon);

    I've never done this (convert a byte array to an image), so I thought I'd have a go...import java.awt.Image;
    import java.awt.image.BufferedImage;
    import java.io.ByteArrayInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import javax.imageio.ImageIO;
    import javax.swing.ImageIcon;
    public class ImageTest {
        public static void main(String[] args) throws Exception {
                // Grab some image...
            File inFile = new File("resources/imageH.jpg");
            int len = (int)inFile.length();
            System.out.printf("file length = %d%n", len);
            FileInputStream in = new FileInputStream(inFile);
                // ... and create a byte array for testing
            byte[] byteArray = new byte[len];
            int num = in.read(byteArray);
            in.close();
            System.out.printf("bytes read = %d%n", num);
                // (1) Create an image from the byte array - I don't
                // know Imagio figures out what sort of image it is!
            BufferedImage im = ImageIO.read(new ByteArrayInputStream(byteArray));
            int w = im.getWidth();
            int h = im.getHeight();
            System.out.printf("width = %d, height = %d", w, h);
                // (2) Scale to fit 100x100
            if(w > h) {
                w = (100 * w) / h;
                h = 100;
            } else {
                h = (100 * h) / h;
                w = 100;
            System.out.printf(" --> %d,%d%n", w, h);
                // (3) And create the icon
            ImageIcon icon = new ImageIcon(im.getScaledInstance(w, h, Image.SCALE_SMOOTH));
            System.out.printf("The icon is: %s%n", icon);
    }The output isfile length = 54918
    bytes read = 54918
    width = 500, height = 300 --> 166,100
    The icon is: javax.swing.ImageIcon@5afd29Assuming your byte array is some (to ImageIO) recognisable image format, something
    similar should work for you.

  • Need to display image on JPanel

    Hello
    I am trying to implement a graphical version of the Knights Tour. I am done with the algorithm part of the problem itself. I am having problem with displaying the chess board. Although seemingly straightforward the images will not display on the JPanel. Below is a sample of what I am trying to do. Can anyone explain why the code does not work even though it seems okay. Thanks and best regards.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.event.*;
    public class test extends JFrame { 
    public test(){ 
    panel pane = new panel();
    getContentPane().add(pane);
    public static void main(String[]args){   
    test tst = new test();
    tst.setSize(500,500);
    tst.show();
    public class panel extends JPanel{   // inner class
    private Image img;
    private ImageIcon icon;
    public panel(){
    icon = new ImageIcon("cross.gif");
    img = icon.getImage();
    public void paintComponent(Graphics g)
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D)g;
    System.out.println("I am here");
    g.drawImage(img,40,40,this);
    }

    package com.lc.util.swing ;
    import java.awt.Color ;
    import java.awt.Graphics ;
    import java.awt.Image;
    import java.awt.Insets;
    import java.awt.Dimension ;
    import java.awt.image.ImageObserver ;
    import javax.swing.JPanel;
    import javax.swing.border.Border;
    * Panel displaying an {@link Image}.
    * <ul>
    * <li>8 positions,</li>
    * <li>
    * can stretch image for filling the whole available area, or diminish
    * its size if too large in width or height,
    * </li>
    * <li>respects borders (as defined by
    * {@link javax.swing.JComponent#setBorder( javax.swing.border.Border ) JComponent.setBorder}
    * </li>
    * </ul>
    * @author Laurent Caillette
    * @version $Revision: 1.1.1.1 $ $Date: 2002/02/19 22:12:04 $
    public class JImagePanel extends JPanel {
    public JImagePanel() {
    imageObserver = this ;
    * Constructeur assignant une image.
    public JImagePanel( Image image ) {
    this() ;
    setImage( image ) ;
    private Image image ;
    private ImageObserver imageObserver ;
    public void setImage( Image image ) {
    this.image = image ;
    adjustPreferredSize();
    public void setBorder( Border newBorder ) {
    super.setBorder( newBorder ) ;
    adjustPreferredSize() ;
    private void adjustPreferredSize() {
    if( image != null ) {
    int w = image.getWidth( imageObserver ) ;
    int h = image.getHeight( imageObserver ) ;
    Border border = getBorder() ;
    if( border != null ) {
    Insets insets = border.getBorderInsets( this ) ;
    if( insets != null ) {
    w += ( insets.left + insets.right ) ;
    h += ( insets.top + insets.bottom ) ;
    Dimension dim = new Dimension( w, h ) ;
    this.setPreferredSize( dim ) ;
    private int placement = CENTER ;
    public int getPlacement() { return placement ; }
    public void setPlacement( int placement ) {
    if( ( placement < CENTER ) || ( placement > STRETCH ) ) {
    throw new IllegalArgumentException( "Unsupported placement value" ) ;
    this.placement = placement ;
    public void paint( Graphics gr ) {
    // x of Image to draw
    int x ;
    // y of Image to draw
    int y ;
    // width of Image to draw
    int iw ;
    // height of Image to draw
    int ih ;
    // thickness of left border
    int bl = 0 ;
    // thickness of upper border
    int bt = 0 ;
    // thickness of right border
    int br = 0 ;
    // thickness of lower border
    int bb = 0 ;
    // width of drawable area
    int pw = this.getWidth() ;
    // height of drawable area
    int ph = this.getHeight() ;
    // Handle borders
    Insets insets = null ;
    Border border = getBorder() ;
    if( border != null ) {
    insets = getBorder().getBorderInsets( this ) ;
    if( insets != null ) {
    bl = insets.left ;
    br = insets.right ;
    bb = insets.bottom ;
    bt = insets.top ;
    pw = pw - bl - br ;
    ph = ph - bt - bb ;
    // Always display background, for supporting transparency.
    super.paint( gr ) ;
    if( image != null ) {
    iw = image.getWidth( imageObserver ) ;
    ih = image.getHeight( imageObserver ) ;
    if( ( placement == STRETCH ) ||
    ( iw > pw ) ||
    ( ih > ph )
    gr.drawImage(image, bl, bt, pw, ph, imageObserver ) ;
    } else {
    iw = image.getWidth( imageObserver ) ;
    ih = image.getHeight( imageObserver ) ;
    switch( placement ) {
    case CENTER :
    x = ( pw - iw ) / 2 ;
    y = ( ph - ih ) / 2 ;
    break ;
    case NORTH :
    x = ( pw - iw ) / 2 ;
    y = 0 ;
    break ;
    case NORTHEAST :
    x = pw - iw ;
    y = 0 ;
    break ;
    case EAST :
    x = pw - iw ;
    y = (ph - ih ) / 2 ;
    break ;
    case SOUTHEAST :
    x = pw - iw ;
    y = ph - ih ;
    break ;
    case SOUTH :
    x = ( pw - iw ) / 2 ;
    y = ph - ih ;
    break ;
    case SOUTHWEST :
    x = 0 ;
    y = ph - ih ;
    break ;
    case WEST :
    x = 0 ;
    y = ( ph - ih ) / 2 ;
    break ;
    case NORTHWEST :
    x = 0 ;
    y = 0 ;
    break ;
    default :
    throw new IllegalArgumentException(
    "Unsupported placement value" ) ;
    // Add border offset
    x += bl ;
    y += bt ;
    gr.drawImage( image, x, y, this ) ;
    public final static int CENTER = 0 ;
    public final static int NORTH = 1 ;
    public final static int NORTHEAST = 2 ;
    public final static int EAST = 3 ;
    public final static int SOUTHEAST = 4 ;
    public final static int SOUTH = 5 ;
    public final static int SOUTHWEST = 6 ;
    public final static int WEST = 7 ;
    public final static int NORTHWEST = 8 ;
    public final static int STRETCH = 9 ;

  • Rendering of an 8Bit-tiff with java.awt produces crap

    Hi Folks,
    i do a downsampling of tiff images. The source tiffs are colored 8 Bit greyscale with a 256 color-table. Now i have 2 possibilities to resample with java.awt:
    1. the target-tiff is of 24Bit true color:
    BufferedImage objDownsample = new BufferedImage(iTargetWidth, iTargetHeight, BufferedImage.TYPE_INT_RGB);The result is a perfect looking, but oversized tiff with 16 million colors each pixel.
    2. the target-tiff is of 8Bit like the source-tiff:
    BufferedImage objDownsample = new BufferedImage(iTargetWidth, iTargetHeight, BufferedImage.TYPE_BYTE_INDEXED,(IndexColorModel)image.getColorModel());The result is a small sized tiff image of 8Bit. Problem: it now has visible vertical stripes of two colors (which both composed result the source-color i assume).
    Does anybody know what's wrong here and how to retrieve the 8Bit color-image without stripes?
    Here comes the whole source:
        private BufferedImage resize(int newHeight, int newWidth, BufferedImage image) {
            int iTargetHeight = newHeight;
            int iTargetWidth = newWidth;
            //Create a BufferedImage that fits
            BufferedImage objDownsample = new BufferedImage(iTargetWidth, iTargetHeight, BufferedImage.TYPE_BYTE_INDEXED,(IndexColorModel)image.getColorModel());
            //A map with all necessary rendering hints to optimize the quality of the image
            Map<java.awt.RenderingHints.Key, java.lang.Object> obj_Map = new HashMap<java.awt.RenderingHints.Key, java.lang.Object>();       
            obj_Map.put(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
            obj_Map.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            obj_Map.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
          // Draw the scaled image
          Graphics2D graphics2D = objDownsample.createGraphics();
            graphics2D.addRenderingHints(obj_Map);
            graphics2D.drawImage(image, 0, 0, iTargetWidth, iTargetHeight, null);
            return objDownsample;
        }Thanks
    Albrecht

    As far as I can tell, this solution only allows compositing within the component that is currently being painted. What would be nice is if I could add a custom composite to say .. a JLabel, which paints based on the colors of the underlying pixel data (ie. from its parent container). In this way you could make a JLabel that always inverts the color of what's underneath.
    Here, painting to the screen using a composite allows me to get the pixels underneath as the destination raster, the pixels in the JLabel as the source raster, and what actually gets painted which is the destination output raster.
    If I paint to a BufferedImage instead, the composite's 'destination raster' is the new BufferedImage's default values which are all black. Thus compositing over this would not have the desired effects described above (inverting the underlying image for instance). The missing piece when rendering to the BufferedImage is first copying the underlying screen data into a BufferedImage before painting to it. How do I do that? Something tells me it's very difficult.

  • Problem In Awt List

    I am Having problem with Awt List component
    setSize
    setPrefferedSize
    setMaximumSize
    None is working I have limited screen are to use in applet Hence I want to limit the width of List
    Below Is My code I am using in Devloping Some Applet.
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.Frame;
    import java.awt.List;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    public class ListSizeProblem extends Frame {
         public List list1;
         ListSizeProblem (String t) {
              this.setTitle(t); // setting up the main window
              this.setSize(500, 400);
              this.setLocation(50, 50);
              this.setLayout(new BorderLayout());
              addWindowListener(new WindowAdapter() { // application will exit if window is closed
                 public void windowClosing(WindowEvent e) {
                      System.exit(0);
              list1 = new List(15, false);
              //list1.setSize(new Dimension(40,200));
              list1.setPreferredSize(new Dimension(40,200));
              //list1.setMaximumSize(new Dimension(40,200));
               for (int i = 1; i < 21; i++) {
                 list1.add("But"+i);
              this.add(list1,BorderLayout.WEST);
              this.pack();
              this.setVisible(true);
         public static void main (String [] args) {
              ListSizeProblem mainframe = new ListSizeProblem("List Size");
    }can somebody help me

    It is indeed a bug. Once your List has data in it, the getPreferredSize method starts calling preferredSize(int rows) method. This method in turn asks the list's peer for the size. The result is that the preferred size you set is completely ignored (hence a bug). Quick fix would be to override the getPreferredSize method like so.
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.Frame;
    import java.awt.List;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    public class ListSizeProblem extends Frame {
        public List list1;
        ListSizeProblem(String t) {
            this.setTitle(t); // setting up the main window
            this.setSize(500, 400);
            this.setLocation(50, 50);
            this.setLayout(new BorderLayout());
            addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
            list1 = new List(15, false) {
                Dimension size = new Dimension(40, 200);
                public java.awt.Dimension getPreferredSize() {
                    return size;
            for (int i = 1; i < 21; i++) {
                list1.add("But" + i);
            this.add(list1, BorderLayout.WEST);
            this.setVisible(true);
        public static void main(String[] args) {
            ListSizeProblem mainframe = new ListSizeProblem("List Size");
    }The list is not 200 pixels high, but this just comes from the fact that you don't have a BorderLayout.NORTH or BorderLayout.SOUTH object yet, so the BorderLayout is alowed to extend the height of the list.
    And you seem to havea pretty exact idea on the size you want your components to be. If the frame is not going to be resizable, then you can use no layout manager if you want. This would require you to set the exact bounds of every component you add to the frame.

  • Open Folder by double click using java.awt

    Hello Guys,
    I have a problem. I m listing directory in List(java.awt). When i single click on directory it will open. But how i can double click on that directory then and then it will open otherwise not. By using JAVA.AWT.

    According to the documentation for java.awt.List "When an item is selected or
    deselected by the user, AWT sends an instance of ItemEvent to the list. When
    the user double-clicks on an item in a scrolling list, AWT sends an instance of
    ActionEvent to the list following the item event. AWT also generates an action
    event when the user presses the return key while an item in the list is selected."
    If your directories are "opening" (whatever that means) in response to a single
    click, that it because of how you have written your code. Change it so that action
    events rather than item events cause the opening to happen.

  • How can i display multiple Pictures in a java.awt.Container best?

    hi,
    I just started with a new Project, it works just like a FileManager.
    On entering a directory all the files in it shall be displayed in a scrollable area. Displayed means here a Graphical representation of the file, in case of a picture a small preview version of it.
    I put together a javax.swing.JScrollPane with a java.awt.Container and viewport. The Container has a FlowLayout.
    Now for every image in a Directory I create a Component-class in witch I overwrote the public void paint(Graphics g) to display a scaled version of the image, this scaled version is created in the Constructor of my Component-class.
    this works fine for just a few images, but if i try to open a directory with a lot of pictures it takes a long time at the beginning and sometimes it just kills the application.
    so i changed in a way that only when a Component is in view of the visible rectangle of the scroll pane the scaled image will be created, and when the component gets out of view the image is set to null.
    now it is running without killing the application, but it takes way too long to scroll now, because the images are loaded all the time.
    so i figured i must be doing something wrong, so what is the best way to get small previews for up to a few hundred files and then display them in a scrollable area? (like in Windows Explorer if you activate the miniature preview)
    if anyone can give me some hints, that would be great
    thanks shirasuresh

    This might give you some ideas:
    import java.awt.*;
    import javax.swing.*;
    public abstract class LazyIcon implements Icon {
        private int width;
        private int height;
        private Image image;
        public LazyIcon(int width, int height) {
            this.width = width;
            this.height = height;
        protected abstract Image createImage();
        public int getIconHeight() {
            return width;
        public int getIconWidth() {
            return height;
        public void paintIcon(Component comp, Graphics g,int x, int y) {
            if (image == null)
                image = createImage();
            g.drawImage(image, x, y, comp);
    }You could also do this with a custom component class, but I like the JLabel + Icon combination.
    Any if you want to get fancy, you could load images in another thread, at low priority, so when the user is just sitting there, your code is preparing the panel for scrolling ;-)
    Message was edited by:
    BigDaddyLoveHandles

  • How to display images in the Personal Java?

    Guys,
    please help me to display the images in gif format in the standalone application using PersonalJava.
    with regards,
    Amin

    JDK:1.1.8; Personaljava:1.1Beta
    Following is my program,it can not only display image but also scroll image that biger than Panel or Canvas.
    import java.awt.*;
    import java.awt.event.*;
    //ImageCanvas object is container keeping Image
    class ImageCanvas extends Canvas
    private Image image,errorimage;
    Container pappy;
    public ImageCanvas(Image i,Container parent)
    errorimage = Toolkit.getDefaultToolkit().getImage("error.gif");
    image=i;
    pappy = parent;
    //following 5 lines can make image display smoothly
    MediaTracker tracker = new MediaTracker(this);
    tracker.addImage(image, 0);
    try { tracker.waitForID(0); }
    catch (InterruptedException e) {}
    public void paint(Graphics g)
    if(image.getWidth(this)==-1)
    image=errorimage;
    Dimension d = getSize();
    this.setSize(image.getWidth(this),image.getHeight(this));
    //Critical syntex for refresh container
    pappy.layout();
    pappy.repaint();
    g.drawImage(image, 0, 0,this);
    public class ScrollingImage implements ActionListener
    {   Frame frame;
    ScrollPane sp;
    Image im;
    public static void main(String[] args)
    ScrollingImage tests= new ScrollingImage();
    tests.go();
    public void go()
    frame = new Frame();
    frame.setLayout(new BorderLayout());
    sp = new ScrollPane();
    im =Toolkit.getDefaultToolkit().getImage("001.gif");
    //please notice following line,critical syntex to display image,I took 2 days to find it.
    sp.add(new ImageCanvas(im,sp));
    sp.setSize(240,290);
    frame.add(sp, BorderLayout.CENTER);
    //following 5 lines make frame be able to close
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    frame.pack();
    frame.setVisible(true);

  • Displaying image from binary data using java

    hi there,
    i have created a swing applet displays me a url, what the url returns me is the image in binary format, and i want to show the complete image using that binary data
    so how do i do it.
    some thing like this :
    URL url = new URL("http://192.168.1.1:8086/file-storage/download/Zerg.jpg?version_id=35688");
    JEditorPane jep = new JEditorPane();
    jep.setPage(url);
    output is in binary on my applet window.

    Hey,
    This displays an image from a url, you could check if your url is and image or not using URL.getFileName() and see if it ends in gif jpeg etc. and then display it this way.
    hope it helps
    Nick Hanlon
    import java.awt.*;
    import java.awt.Image.*;
    import java.awt.Toolkit.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.net.*;
    import java.io.*;
    import javax.swing.text.html.*;
    public class SimpleApp extends JFrame {
    public static void main(String args[]) {
    SimpleApp aFrame = new SimpleApp();
    public SimpleApp() {
    super("Frame");
    /*JEditorPane jep = new JEditorPane();
    jep.*/
    try {
    HTMLEditorKit htmlKit = new HTMLEditorKit();
    JEditorPane ep = new JEditorPane();
    try {
    ep.setEditorKit(htmlKit);
    BufferedReader in = new BufferedReader(
    new StringReader(
    "<HTML><IMG SRC=\"http://developer.java.sun.com/images/chiclet.row.gif\"></HTML>"));
    htmlKit.read(in, ep.getDocument(),0);
    getContentPane().setLayout(new BorderLayout());
    setResizable(false);
    getContentPane().add(ep, "North");
    pack();
    show();
    } catch (javax.swing.text.BadLocationException e) {}
    } catch (IOException e) {}
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) { System.exit(0); }
    }

  • Using List Class in java.awt / java.util ?

    have a program that:
    import java.util.*;
    List list = new LinkedList();
    list = new ArrayList();
    ... read a file and add elements to array
    use a static setter
    StaticGettersSetters.setArray(list);
    next program:
    import java.awt.*;
    public static java.util.List queryArray =
    StaticGettersSetters.getArray();
    If I don't define queryArray with the package and class, the compiler
    gives an error that the List class in java.awt is invalid for queryArray.
    If I import the util package, import java.util.*; , the compiler
    gives an error that the list class is ambiguous.
    Question:
    If you using a class that exists in multiple packages, is the above declaration of queryArray the only way to declare it ?
    Just curious...
    Thanks for your help,
    YAM-SSM

    So what you have to do is explicitly tell the compiler which one you really want by spelling out the fully-resolved class name:
    import java.awt.*;
    import java.sql.*;
    import java.util.*;
    public class ClashTest
        public static void main(String [] args)
            java.util.Date today    = new java.util.Date();
            java.util.List argsList = Arrays.asList(args);
            System.out.println(today);
            System.out.println(argsList);
    }No problems here. - MOD

Maybe you are looking for