Inability to draw simple graphics in Java properly (threads and JFrame)

I am trying to use a thread to continually draw randomly positioned and randomly sized squares in the middle of a JFrame window. I have got 'something' working with the following code, however when run, the actual window doesn't come up properly. If I resize the window it does, and I get the result I wanted, but when the window is first opened it does not fully draw itself on screen. Can anybody help here? I am a bit of a novice when it comes to Java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class TestDraw extends JFrame implements Runnable {
//DECLARE VARIABLES
     private JLabel lblText;
     private JButton btnBegin;
     private JPanel contentPane;
     private int CoordX, CoordY,SizeX, SizeY, Colour;     // Co'ords for drawing the squares
     Random random = new Random();                              // Random numbers (for square dimensions and colours)
     int n_1 = 450, n_2 = 130, n_3 = 100, n_4 = 4;          // The different ranges of randoms I require
     Thread squares = new Thread(this);                         // Implements a new thread
//END OF DECLARE VARIABLES
// CALLS INITIAL PROCEDURE, SETS VISIBLE ETC
     public TestDraw() {
          super();
          initializeComponent();
          this.setVisible(true);
// INITIALISATION PROCEDURE CALL
     private void initializeComponent() {
          lblText = new JLabel();
          btnBegin = new JButton();
          contentPane = (JPanel)this.getContentPane();
          // lblText
          lblText.setText("This should draw squares on screen...");
          // btnBegin
          btnBegin.setText("Start");
          btnBegin.addActionListener(new ActionListener() {
               public void actionPerformed(ActionEvent e) {
                    btnBegin_actionPerformed(e);
          // contentPane
          contentPane.setLayout(null);
          addComponent(contentPane, lblText, 10,300,364,18);
          addComponent(contentPane, btnBegin, 144,10,101,28);
          // TestDraw
          this.setTitle("TestDraw Program for CM0246");
          this.setLocation(new Point(0, 0));
          this.setSize(new Dimension(390, 350));
// POSITION COMPONENTS ON SCREEN
     private void addComponent(Container container,Component c,int x,int y,int width,int height)     {
          c.setBounds(x,y,width,height);
          container.add(c);
// EVENT HANDLING PROCEDURES
     private void btnBegin_actionPerformed(ActionEvent e) {
          System.out.println("\nAction Event from btnBegin called...");
          squares.start(); //STARTS THE SQUARES DRAWING THREAD (Draws random squares on screen)
// THE MAIN METHOD (STARTS THE PROGRAM)
     public static void main(String[] args) {
          TestDraw bobdole = new TestDraw();
// THE SQUARE DRAWINGS THREAD (SHOULD DRAW RANDOM SIZED AND COLOURED SQUARES IN RANDOM PLACES)
     public void run() {
          System.out.println("Thread running if this prints");
               while(true) {
                    int int_1 = random.nextInt(n_1);     // chooses random int for X co'ord
                    int int_2 = random.nextInt(n_2)+70;     // chooses random int for Y co'ord
                    int int_3 = random.nextInt(n_3)+10;     // chooses random int for X dimension
                    int int_4 = random.nextInt(n_3)+10;     // chooses random int for Y dimension
                    CoordX = int_1;
                    CoordY = int_2;
                    SizeX  = int_3;
                    SizeY  = int_4;
                    repaint();
                    try {
                         squares.sleep(500);
                    catch (InterruptedException e) {
                         System.out.println(e);
// THE PAINT METHOD ATTATCHED TO THE SQUARES THREAD
     public void paint( Graphics g ) {
          System.out.print("Colour" + Colour);
          g.setColor(Color.blue);
          g.fillRect(CoordX, CoordY, SizeX, SizeY);
// END OF PROGRAM

I don't see any problem when I run the program but.. In general you shouldn't paint directly on a frame by overloading the paint method. You should rather create a custom component on which you draw.
But if you do overload paint, make sure you call super.paint before doing anything else.
More information in this tutorial: http://java.sun.com/docs/books/tutorial/uiswing/painting/index.html

Similar Messages

  • URGENT- PLEASE HELP: java.lang.threads and BC4J

    Hi,
    according to my issue "no def found for view" in the same titled thread I'm wondering how you would implement asynchronous calls of methods that use BC4J to update a couple of data.
    To be more precise:
    A requirement of our software is to start an update database job, which can take a couple of minutes/hours, from the web browser. Before it will be executed the logged-in user receives a notification that this batch job has been started.
    I dont't want to use JMS overhead and MD Beans for this simple requirement, therefore I implemented a class that extends java.lang.Thread and put all the update codings within the run method. After having called the start-method of the thread I get a JBO-25022(No XML file found) error when I try to set a new value for an attribute of the row. The row consists of attributes which belong to four entity objects that mus be updated.
    When calling the run method directly, everything works fine.
    My questions:
    * do you know any workaround how to make the xml files
    reachable?
    * how would you implement anschronous calls of long time-
    consuming jobs?
    * is this a bug of BC4J?
    Any help, tip, hint is really appreciated.
    Stefan

    Arno,
    many thanks for your reply:
    Here is an excerpt of the source code of my thread "Aenderungsdienst":
    public class Aenderungsdienst extends java.lang.Thread
    private SviAdministrationModuleImpl mSviModul;
    // Application module that contains view object
    // IKViewImpl
    public Aenderungsdienst(SviAdministrationModuleImpl aSviModul)
    mSviModul = aSviModul;
    public void run()
    ausfuehrenAenderungsdienst(mAenderungsdienstNr); <--error within this methode
    private int ausfuehrenAenderungsdienst(String aAenderungsdienstNr)
    int rAnzahlSaetze = 0;
    try
    IkViewImpl aenderungen = mSviModul.getIkView();
    aenderungen.suchenAenderungssaetze(aAenderungsdienstNr); <-- method within View Object Impl that executes a query with customized where-clauses
    if ((rAnzahlSaetze = aenderungen.getRowCount()) > 0)
    IkViewRowImpl ik = null;
    while (aenderungen.hasNext())
    ik = (IkViewRowImpl) aenderungen.next();
    ik.setBestandsstatus("B"); <-- error occurs here when setting the status of a current row in my rowset to "B"
    mSviModul.getTransaction().postChanges();
    mSviModul.getTransaction().commit();
    catch (Exception e)
    e.printStackTrace();
    mSviModul.getTransaction().rollback();
    //todo: Verarbeitungsprotokoll erstellen
    return rAnzahlSaetze;
    This thread will be called by the application module "sviAdministrationModuleImpl":
    public void ausfuehrenAenderungsdienst(String
    aAenderungsdienstNr)
    Aenderungsdienst aenderungsdienst = new
    Aenderungsdienst(this);
    aenderungsdienst.setAenderungsdienstNr
    (aAenderungsdienstNr);
    aenderungsdienst.start();
    Using the start() method of the thread causes this exception:
    [653] No xml file: /hvbg/svi/model/businessobjects/businessobjects.xml, metaobj = hvbg.svi.model.businessobjects.businessobjects
    [654] Cannot Load parent Package : hvbg.svi.model.businessobjects.businessobjects
    [655] Business Object Browsing may be unavailable
    [656] No xml file: /hvbg/svi/model/businessobjects/IK_Inlandsbankverb.xml, metaobj = hvbg.svi.model.businessobjects.IK_Inlandsbankverb
    09.03.2004 10:27:41 hvbg.common.businessobjects.HvbgEntityImpl setAttributeInternal
    SCHWERWIEGEND: Fehler beim Setzen des Attributs 1 im Entity Objekt: JBO-25002: Definition hvbg.svi.model.businessobjects.IK_Inlandsbankverb vom Typ Entitätszuordnung nicht gefunden.
    09.03.2004 10:27:42 hvbg.svi.model.dienste.Aenderungsdienst ausfuehrenAenderungsdienst
    SCHWERWIEGEND: Beim Ausführen des Aenderungsdienstes 618 trat während der DB-Aktualisierung ein schwerer Fehler auf:
    JBO-25002: Definition hvbg.svi.model.businessobjects.IK_Inlandsbankverb vom Typ Entitätszuordnung nicht gefunden.
    oracle.jbo.NoDefException: JBO-25002: Definition hvbg.svi.model.businessobjects.IK_Inlandsbankverb vom Typ Entitätszuordnung nicht gefunden.
         at oracle.jbo.mom.DefinitionManager.findDefinitionObject(DefinitionManager.java:328)
         at oracle.jbo.mom.DefinitionManager.findDefinitionObject(DefinitionManager.java:268)
         at oracle.jbo.server.MetaObjectManager.findMetaObject(MetaObjectManager.java:649)
         at oracle.jbo.server.EntityAssociation.findEntityAssociation(EntityAssociation.java:98)
         at oracle.jbo.server.AssociationDefImpl.resolveEntityAssociation(AssociationDefImpl.java:725)
         at oracle.jbo.server.AssociationDefImpl.getEntityAssociation(AssociationDefImpl.java:135)
         at oracle.jbo.server.AssociationDefImpl.hasContainer(AssociationDefImpl.java:546)
         at oracle.jbo.server.AssociationDefImpl.getContainer(AssociationDefImpl.java:468)
         at oracle.jbo.server.EntityImpl.getContainer(EntityImpl.java:1573)
         at oracle.jbo.server.EntityImpl.setValidated(EntityImpl.java:1649)
         at oracle.jbo.server.EntityImpl.setAttributeValueInternal(EntityImpl.java:2081)
         at oracle.jbo.server.EntityImpl.setAttributeValue(EntityImpl.java:1985)
         at oracle.jbo.server.AttributeDefImpl.set(AttributeDefImpl.java:1700)
         at oracle.jbo.server.EntityImpl.setAttributeInternal(EntityImpl.java:946)
         at hvbg.common.businessobjects.HvbgEntityImpl.setAttributeInternal(HvbgEntityImpl.java:56)
         at hvbg.svi.model.businessobjects.IKImpl.setBestandsstatus(IKImpl.java:174)
         at hvbg.svi.model.businessobjects.IKImpl.setAttrInvokeAccessor(IKImpl.java:770)
         at oracle.jbo.server.EntityImpl.setAttribute(EntityImpl.java:859)
         at oracle.jbo.server.ViewRowStorage.setAttributeValue(ViewRowStorage.java:1108)
         at oracle.jbo.server.ViewRowStorage.setAttributeInternal(ViewRowStorage.java:1019)
         at oracle.jbo.server.ViewRowImpl.setAttributeInternal(ViewRowImpl.java:1047)
         at hvbg.svi.model.dataviews.IkViewRowImpl.setBestandsstatus(IkViewRowImpl.java:264)
         at hvbg.svi.model.dienste.Aenderungsdienst.ausfuehrenAenderungsdienst(Aenderungsdienst.java:337)
         at hvbg.svi.model.dienste.Aenderungsdienst.run(Aenderungsdienst.java:290)
    Using run(), everything works perfectly.
    The view object IKView consists of four entity objects which are linked by associations. There exists an association between the entity objects ik and inlandbankverb. The xml-file for the association object is named "ik_inlandsbankverb.xml". It seems so that this definition could not be found when calling my thread in asynchronous (via start()-method call) mode.
    Is this a bug of JDeveloper?
    Thanks in advance,
    Stefan

  • I need Java code for a simple graphical hit counter for a webpage

    I was wondering if anybody out there could send me some code for a simple graphical hit counter for a webpage. All the sites that I've visited are garbage and of no use to me. Please help me.
    Colin

    Not as easy as you'd imagine with applets. You need some way to store the hits, usually through a file on the server. That's not gonna happen in a hurry for 2 reasons -
    - Applets can't read/write files
    - Your web server usually won't let you run programs on their machine (ie, programs that listen for socket connections from applets, then load/read/write/close a file).
    In short, no, there is no simple java solution (that I know of).
    Cheers,
    Radish21

  • How to save simple graphics drawn on canvas as gifs, bitmaps, etc.

    I figured out how to draw a graphics object which is abstract for an application rather than an applet. Now, my question is, how do I save these simple graphics (lines, rectangles, circles,etc) drawn on canvas as gifs, bitmaps, etc. so that they may later be opened using other graphical viewers.
    another question I was wondering was if graphics is a AWT only class (ie no better swing equivalent)
    thanks

    some things i have found so far are acme or java advanced imaging api... anyone know what is easier to use for my purpose?
    it appears that when using acme, i need to use java.awt.image (does that mean I would have to convert the canvas to an image?) how do i save in gif format using java advanced imaging?
    Please help

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

  • Drawing 2D graphics with no frame or no panel ?

    Hi,
    I would like to know if it is possible to draw 2D graphics directly over the OS(windows2002) ? like drawing a rectangle over the desktop without any JPanel or JFrame.
    cheers,
    sletourne

    It is possible, I've done it ;-)
    import java.awt.*;
    import java.awt.event.*;
    public class JustSomething implements WindowListener
         public static void main(String args[])
              new JustSomething();
         public JustSomething()
              Frame winf = new Frame();
              winf.setLocation(2000,2000);
              winf.add(new java.awt.Label("If you see this you have a mighty big screen"));
              Window win = new Window(winf);          
              win.setSize(width,height);
              winf.addWindowListener(this);
         public void windowOpened(WindowEvent windowevent){}
         public void windowClosing(WindowEvent windowevent){}
         public void windowClosed(WindowEvent windowevent){}
         public void windowIconified(WindowEvent windowevent){}
         public void windowDeiconified(WindowEvent windowevent){}
         public void windowActivated(WindowEvent windowevent){}
         public void windowDeactivated(WindowEvent windowevent){}

  • Graphics only display properly when acceleration turned down

    I have the latest netbeans/jdk bundle installed v4.1/5.0, the latest direct x 9.0c or whatever. ATI 9700 in my toshiba mobile desktop P35.
    A simple graphics draw arcs inside jpanel inside jframe displays distorted in full acceleration. The colors are all there but interlaced or offset or something.
    When I turn accelleration down 3 or 4 notches, so that directdraw is off, it looks fine.
    Any ideas?

    Matteo : I guess it is a good sign that only 2 of us have reported this minor glitch here . . . I may experiment with switching to a different desktop pattern and / or screen saver to see if it persists . . . also, since installing SL I have only done Sleep and of course restarts after getting the 10.6.1 update and a few others so I need to do an actual Shut Down and later start up fresh and see what happens.

  • Drawing 2d graphics

    Sorry, does anybody know the most convenient way to draw graphics? f.e to draw graphic just on two vectors of points X and Y. Rrd4J is not enough good because rrd works with time.

    To whom it may be interest.
    This is a small example to draw a chart having "values on X" and "values on Y" :-) using JFreeChart
    import java.awt.Font;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    import javax.imageio.ImageIO;
    import junit.framework.TestCase;
    import org.jfree.chart.ChartFactory;
    import org.jfree.chart.JFreeChart;
    import org.jfree.chart.axis.NumberAxis;
    import org.jfree.chart.plot.PlotOrientation;
    import org.jfree.chart.plot.XYPlot;
    import org.jfree.chart.title.TextTitle;
    import org.jfree.data.xy.XYDataset;
    import org.jfree.data.xy.XYSeries;
    import org.jfree.data.xy.XYSeriesCollection;
    public class SimpleChartTest extends TestCase {
         private XYSeriesCollection createDataset() {
              XYSeriesCollection result = new XYSeriesCollection();
              XYSeries s3 = new XYSeries("P", true, false);
              s3.add(0, 2.355450986);
              s3.add(0.5, 2.799548641);
              s3.add(1.5, 3.614688072);
              s3.add(11.5, 8.283364855);
              s3.add(12.5, 8.534275028);
              s3.add(13.5, 8.762648582);
              s3.add(14.5, 8.971407287);
              s3.add(15.5, 9.163180317);
              s3.add(16.5, 9.340328068);
              s3.add(17.5, 9.504964014);
              s3.add(19.5, 9.804039109);
              s3.add(20.5, 9.941644878);
              result.addSeries(s3);
              return result;
         private JFreeChart createChart(XYDataset dataset) {
              JFreeChart chart = ChartFactory.createXYLineChart(null,
                        "Value on X", "Value on Y", dataset, PlotOrientation.VERTICAL, true,
                        true, false);
              TextTitle t1 = new TextTitle("Title1", new Font(
                        "SansSerif", Font.BOLD, 14));
              TextTitle t2 = new TextTitle(
                        "Title2",
                        new Font("SansSerif", Font.PLAIN, 11));
              chart.addSubtitle(t1);
              chart.addSubtitle(t2);
              XYPlot plot = chart.getXYPlot();
              NumberAxis domainAxis = (NumberAxis) plot.getDomainAxis();
              domainAxis.setUpperMargin(0.12);
              domainAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
              NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
              rangeAxis.setAutoRangeIncludesZero(false);
              return chart;
         public void test() throws IOException {
              XYSeriesCollection dataset = createDataset();
              JFreeChart chart = createChart(dataset);
              BufferedImage image = chart.createBufferedImage(360, 500);
              File file = new File("test-data/charts/newimage.png");
    ImageIO.write(image, "png", file);
    }

  • Drawing 2D figures with Java (currently using GTK+)

    Hello everyone :)
    I am currently working on a college project which requires me to develop a graphical interface for a text based software and to draw 2-D drawings (basically frames of buildings) by reading data stored in formatted text files.
    Earlier on, I was working using GTK+, but the fact is that my program has to work on several different PCs with different OS and hence portability is a big concern. So, I wanted to ask if I could draw good enough 2D drawings using Java? Basically, I want to know the comparison between the drawings possible by GTK+ and Java. I know that interface won't be a problem with Java :)
    Also, is the learning curve for drawing steep in Java? I am a bit pressed for time as I spent a lot of time with GTK+ and GTKMM

    Thanks for your reply, but my main purpose was to have to some sort of comparison between the capabilities of Java 2D API and GTK+/GTKMM. I don't want a detailed answer, just a brief one.

  • I'm using Adobe Acrobat with the hope of editing a url on the graphic...a simple 3-letter change, save, close and send for printing..how do I get in edit mode to delete 3 letters and insert 3 new letters?

    ?I'm using Adobe Acrobat with the hope of editing a url on the graphic...a simple 3-letter change, save, close and send for printing..how do I get in edit mode to delete 3 letters and insert 3 new letters?

    pkg4ibm wrote:
    editing a url on the graphic...
    Not sure what you mean by that: is that URL in an image, or is it actual text?
    If it is in an image, then you need to extract the image, edit it with something like Photoshop, then add it back to the PDF.
    If the URL is actual text, I suggest that you remove the entire URL, then add the corrected link.

  • Creating a drawing (CAD) program in Java

    I'm in the planning stages of creating a drawing/drafting program in Java, and I'm fairly new to Swing, so I need some guidance.
    For a drafting program, I will need to be able to draw all kinds of objects using lines, curves, etc, connected in various ways. One thing I could do is extend JComponent and override the paint() method, and have it put up all the various objects as it repaints. The problem with this is that if a user clicks on an object, how will I detect which object he clicked on? I'll get mouse coordinates, but then how do I go from that to knowing that he clicked on a certain curve, etc?
    The alternative is to not extend JComponent, but rather to make each of the individual objects on the screen its own component and then lay them out using absolute positioning. Then I'll get mouse events as the user clicks on things. Is this a better way to do it? And if so, I guess I'll still need to create individual components that represent lines, arcs, curves, etc?
    Swing has so many features that it's hard for a beginning to get started into it. Thanks for any tips.

    Personally I wouldn't work with Swing for this functionality,
    but I would rather work with java 2D instead.
    Swing contains to much overhead for the kind of application you plan to develop.
    Look for the java.awt.Shape interface and to the java.awt.geom.* implementations of such shapes.
    It contains already most of the functionality required for painting and hit-detection of a shape on the
    screen.
    kind regards,

  • Drawing a Graphics object on a Graphics object

    Is there anyway to draw a Graphics object on another Graphics object? I'm trying to show 2 screens, side by side, on a Canvas and I'm trying to cheat a little :-P Basically, I want to take half of one screen and half of another and put them on top of each other to form one screen.
    OR is there a way to turn a Graphics object into an Image object?

    I'm not sure if this is what you're after, but you can
    - create an offscreen image using "createImage(int width, int height)" method of a Component , then
    - obtain the graphics context of the offscreen image using "getGraphics()",
    - you can then draw onto the offscreen image using the graphics context.
    hope that helps. =)

  • Can somebody help me out? I need a Corel Draw (.cdr) graphic converted to Illustrator

    I'm trying to get a logo from brandsoftheworld.com but the one I want is in .CDR. I don't have Corel Draw (who does anymore) but I see that Illustrator 6 can open it. Unfortunately, I'm still on CS5.5. Can somebody help me out?

    Send it to me. I'll save it as an EPS file for you.
    Bob AT theindesignguy DOT com
    TwitchOSX <mailto:[email protected]>
    Thursday, January 24, 2013 7:11 PM
    >
          Can somebody help me out? I need a Corel Draw (.cdr) graphic
          converted to Illustrator
    created by TwitchOSX <http://forums.adobe.com/people/TwitchOSX> in
    /InDesign/ - View the full discussion
    <http://forums.adobe.com/message/5020999#5020999

  • Why can't there be a simple utility that shows me which device connected to my Airport is using how much of the bandwidth in a simple graphical or stats format without requiring me to be a level 10 Black Belt or Chuck Norris' paternal tooth fairy?

    Why can't there be a simple utility that shows me which device connected to my Airport is using how much of the bandwidth in a simple graphical or stats format without requiring me to be a level 10 Black Belt or Chuck Norris' paternal tooth fairy?
    I need to see who is consuming the most bandwidth and limit that user/device. A very simple and dare I say it, legal, moral, and normal wish.

    They are not overloading the Airport. They are overwhelming the capacity of your Internet connection.
    No. It's not "shared equally". That's not how packet switched networks function.
    Most consumer grade routers do not have the ability to restrict bandwidth use on a per machine basis. You need relatively expensive (but readily available) equipment to do that.
    How many people are on the network? It can't be that hard to hunt them down.

  • Simple graphic program?

    I'm looking for a simple graphic program. Even Elements is overkill (price is fine but learning curve is a bit much for what I need)
    What I want to do is add text and arrows to pics. (pointing out spots)
    And highlight an area (or more preferably dim out the surrounding area)

    Try [Seashore|http://seashore.sourceforge.net/TheSeashoreProject/About.html]. It's pretty simple, and even better, it's free!

Maybe you are looking for

  • Adding Loops

    I recently purchased a macbook and was exploring garageband. My list of apple loops at the bottom of the screen is greyed out inevery category. When I click on it, it asks me if I want to download all of the garageband loops (1.2 gigs). When I accept

  • Sharing a local printer over AE's

    I have two Airport Extreme (802.11.g) base stations and one is using WDS to extend my coverage to a second floor and garage. I have a shared printer on an iMac connected to one base station (the master) and can't seem to access it while connected to

  • RAM Riser A is unrecognized + Sleep Issues

    I've had my Mac Pro for a good month now & it's been one of the best computing experiences of my life. Sadly, within the past few days two problems emerged. 1. When waking from sleep, the Mac Pro just restarts. 2. Only RAM Riser B is being recognized

  • Using Essentials 12 on Two Computers

    I live at Two locations during the year.  Nine months at one and 3 months at another location 1000 miles away duringthe summer.  Must I purchase two copies of Essentials 12.....or is there a way I can do this with one copy.  I will be the only one us

  • Migration to new Macbook

    I am migrating from a PowerBook G4 to a MacBook with 10.5.6, and ran Migration set up for six hours, which got the files from the old Mac into the new one. But I can't pull up my old Mail from the old computer on the new one, or my photos, or iTunes.