Painting rectangle at an angle?

Hi,
There are 2 points, (x1,y1) and (x2,y2), a line is drawn before then using the drawline method, what I want to do it have a rectangle which will go from point (x1,y1) to (x2,y2).
However, fillrect do not support any angle parameter and I can't find a method to the rotation.
See the orange rectangle in the image:
http://img207.imageshack.us/img207/7584/javamh1.jpg
Any help will be very much appreciated.

import java.awt.*;
import java.awt.font.*;
import java.awt.geom.*;
import javax.swing.*;
public class InLineRectangle extends JPanel {
    Point p1 = new Point(100,300);
    Point p2 = new Point(300,100);
    Rectangle rect = new Rectangle(75,25);
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                            RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setPaint(Color.blue);
        g2.draw(new Line2D.Double(p1, p2));
        g2.setPaint(Color.red);
        mark(p1, g2);
        mark(p2, g2);
        // Locate rect at 1/4 the length of the line from p1 to p2.
        double theta = Math.atan2(p2.y-p1.y, p2.x-p1.x);
        double length = p1.distance(p2);
        double x = p1.x + (length/4.0)*Math.cos(theta);
        double y = p1.y + (length/4.0)*Math.sin(theta);
        // Locate rect on the line.
        AffineTransform at = AffineTransform.getTranslateInstance(x, y-rect.height/2);
        // Rotate rect about x, y on the line.
        at.rotate(theta, 0, rect.height/2);
        g2.setPaint(Color.orange);
        g2.fill(at.createTransformedShape(rect));
        // Show x, y for confirmation.
        g2.setPaint(Color.green.darker());
        mark(new Point2D.Double(x, y), g2);
        // Draw text.
        String s = "aligned";
        Font font = g2.getFont().deriveFont(16f);
        g2.setFont(font);
        FontRenderContext frc = g2.getFontRenderContext();
        float sw = (float)font.getStringBounds(s, frc).getWidth();
        LineMetrics lm = font.getLineMetrics(s, frc);
        float sh = lm.getAscent() + lm.getDescent();
        x = (rect.width - sw)/2;
        y = (rect.height + sh)/2 - lm.getDescent();
        // Position the text relative to rect.
        AffineTransform xf = AffineTransform.getTranslateInstance(x, y);
        xf.preConcatenate(at);
        g2.setFont(font.deriveFont(xf));
        g2.setPaint(Color.blue);
        g2.drawString(s, 0, 0);
    private void mark(Point2D p, Graphics2D g2) {
        g2.fill(new Ellipse2D.Double(p.getX()-2, p.getY()-2, 4, 4));
    public Dimension getPreferredSize() {
        return new Dimension(400,400);
    public static void main(String[] args) {
        JOptionPane.showMessageDialog(null, new InLineRectangle(), "", -1);
}

Similar Messages

  • Placing text within a diamond within a rectangle

    I am trying to use Pages 6 to do some very basic Chen diagrams for a database course I am taking and what would seem like a simple task eludes me.
    I want to put some text in a diamond shape, then put that diamond shape in a rectangle. I can figure out how to put the diamond shape in the rectangle just fine, but putting text in the rectangle seems like an impossibility. I have tried every option I can find by option-clicking, command-clicking, and fiddling with the Inspector, but nothing seems to work. How can I get a diamond that allows text to be inserted in it AND that can be inserted into a rectangle?
    Ideally, I also want to scale the rectangle so each angle intersects with the rectangle. If that's not possible, fine, but it would be nice.
    Thanks!

    The possibilities are endless. You need to understand the basics.
    The default object moves with text and has wrap on. To really play with object layering you need to turn both these features off. Open the Inspector and click on the wrap tab. Select 'Fixed on Page' and uncheck 'object causes wrap. Do this for each object you create.
    Objects by default are also filled. Open the Inspector, click on the object tab and from the 'fill' pull down menu select none for no fill (just the object lines).
    Pages has transparency. All objects, again in the inspector, can be made transparent by adjusting the opacity slider.
    This is just the tip of the iceberg:
    With Pages open go to the help menu and select the 'Pages User guide.' In the manual open the section called 'working with graphics and other media'. There is tons of info in there.
    Kurt

  • Painting multiple graphic objects

    Hi, I need to create something where I can paint rectangles and circles etc on a canvas.
    Almost like MS Paint.
    I guess I must use a JComponent to paint on, but my problem is how does it store all previously painted objects, e.g if i draw 3 rectangles, the minimize and maximize the window (i.e call update()), only the last rectangle is visible.
    Must I store everything in an array, and then traverse it everytime update() is called ?
    Surely there must be an easier way ?

    There is one, it called BufferedImage, you create one then get it graphics, draw on it every time you want (not in the pain method), and in the paint method you draw this bufferedimage to the graphics.
    BufferedImage b1;
    Graphics g1;
    b1 = new BufferedImage(w,h,BufferedImage.TYPE_3BYTE_BGR);
    g1 = b1.getGraphics();
    g1.setColor(Color.red);
    g1.drawRect(100,100,100,100);
    public void paintComponent(Graphics g)
    super.paintComponent(g);
    g.drawImage(b1,0,0,null);
    Noah

  • How to create a Gradientcolor from two existing swatches

    Hello all,
    I have 2 colors in the swatches palette.has anyone how to create a new gradient color from this to swatches.
    So far I can get my to colors from the palette and extract their color:
    aSwatch1 = sAISwatchList->GetSwatchByName( colList, colorName1 );
    aSwatch2 = sAISwatchList->GetSwatchByName( colList, colorName1 );
    iErr = sAISwatchList->GetAIColor( aSwatch1, &colorP1);
    iErr = sAISwatchList->GetAIColor( aSwatch2, &colorP2);
    // now somehow create a new gradient:
    iErr = sAIGradient->NewGradient( &gradientHnd );
    but what do now. to get the new color from colorP1 and colorP2. I need a simple linear gradient.
    Any hints?
    regards
    Michael

    Hello,
    > Please, excuse any ignorance below. I'm not well versed in the actual artistic side of Illustrator, just the implementation
    excused because you're the one of the few people here who give thoe most usefull answers
    > Isn't that to be expected though? From my admittedly limited understanding, the gradient being saved is really just a sequence of colour stops. I would have thought since the angle of the gradient is more of a property of how its applied to the path (or whatever) that it wouldn't make sense to save it on the gradient colour.
    No, not from my view (and needs ).
    The color for the gradient has a type of AIGradientStyleMap. this struct contains the angle für the linear gradient etc. This color is added to the swatchpalette so it shoud keep the value.
    If you replace the CreateGradientSwatch function in SnpGradien.cpp of the SnippetRunner with the following code a 2nd swatch with an different angle is added to the swatchpalette when creating a new linear gradient is created (name seems not what it should but 2 swatches are created. Applying this 2 swatches to a rectangle also the angle is changed as it should be.
    So from my point of view Illustrator doesn't take the angle when a new color/swatch is created in the swatch panel. Why the angle is saved by creating a style is another question and difficult to answer without looking inside the source of Illustrator
    ASErr SnpGradient::CreateGradientSwatch(const AIGradientHandle gradient, AISwatchRef& swatch)
    ASErr result = kNoErr;
    try {
    // Insert new swatch at end of general swatch group.
    swatch = sAISwatchList->InsertNthSwatch(NULL, -1);
    // Get gradient name.
    ai::UnicodeString gradientName;
    result = sAIGradient->GetGradientName(gradient, gradientName);
    aisdk::check_ai_error(result);
    // Set swatch name.
    result = sAISwatchList->SetSwatchName(swatch, gradientName);
    aisdk::check_ai_error(result);
    // Create the swatch color using the gradient.
    AIColor swatchColor;
    swatchColor.kind = kGradient;
    swatchColor.c.b.gradient = gradient;
    swatchColor.c.b.gradientAngle = 30;
    swatchColor.c.b.gradientLength = 1;
    AIRealPoint origin = {0,0};
    swatchColor.c.b.gradientOrigin = origin;
    swatchColor.c.b.hiliteAngle = 0;
    swatchColor.c.b.hiliteLength = 0;
    SnippetRunnerLog::Instance()->WritePrintf("gradientAngle: %.1f",swatchColor.c.b.gradientAngle);
    SnippetRunnerLog::Instance()->WritePrintf("gradientLength: %.1f",swatchColor.c.b.gradientLength);
    SnippetRunnerLog::Instance()->WritePrintf("gradientOrigin (v / h): %.1f /  %.1f", swatchColor.c.b.gradientOrigin.v, swatchColor.c.b.gradientOrigin.h);
    SnippetRunnerLog::Instance()->WritePrintf("gradientAngle: %.1f",swatchColor.c.b.gradientAngle);
    SnippetRunnerLog::Instance()->WritePrintf("hiliteLength: %.1f",swatchColor.c.b.hiliteLength);
    // Set the swatch color.
    result = sAISwatchList->SetAIColor(swatch, &swatchColor);
    aisdk::check_ai_error(result);
    // making a 2nd swatch
    AISwatchRef swatch2;
    swatch2 = sAISwatchList->InsertNthSwatch(NULL, -1);
    result = sAISwatchList->SetSwatchName(swatch2, (ai::UnicodeString("Grad2")));
      // Create the swatch color using the gradient.
      AIColor swatchColor2;
      swatchColor2.kind = kGradient;
      swatchColor2.c.b.gradient = gradient;
      swatchColor2.c.b.gradientAngle = 60;
      swatchColor2.c.b.gradientLength = 1;
      swatchColor2.c.b.gradientOrigin = origin;
      swatchColor2.c.b.hiliteAngle = 0;
      swatchColor2.c.b.hiliteLength = 0;
    result = sAISwatchList->SetAIColor(swatch2, &swatchColor2);
    catch (ai::Error& ex) {
    result = ex;
    return result;
    The CS3/CS4 question is easy: for CS3 i use the CS3 SDK and for CS4 I#m working with the CS4 SDK :-)

  • Animation problem ( badly needs) ?

    Hello,
    Sorry i 'm posting again and again. because nobody couldn't respond . I badly need this application to be run. Here is what am doing. First applet should start and display '+'( by painting) after keypressed(eg spacebar) then sleep for a while and paint rectangles and next arrow then sleep and etc . this goes on until i keypressed again. Here is that i wrote code , could u please check and modify it. Where i stucked is that KeyPressed code is not working. Please see the code modify it wherever is necessary.
    Thanks in advance,
    - Balaji
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.Applet;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Color;
    import java.awt.Rectangle;
    import java.awt.GradientPaint;
    import java.awt.geom.GeneralPath;
    import java.awt.Polygon;
    //<applet code="ExptA4.class" width=300 height=300></applet>
    public class ExptA4 extends Applet implements Runnable {
         Thread animator;
         Dimension appSize;
         boolean frozen = false;
         int appWidth = 1000, appHeight = 800;
         int delay = 500;
         java.awt.geom.Ellipse2D.Double circle;
         public void init(){
              appSize = new Dimension(appWidth,appHeight);
              this.setSize(appSize);
             addKeyListener(new KeyAdapter(){
                  public void keyPressed(KeyEvent e){
                  ExptA4 exptA4 = (ExptA4) e.getSource();
                  if (e.getKeyCode() == KeyEvent.VK_SPACE)
                       System.out.println("in the keypressed method ");
                  }// end of if      
                  } // end of keyPressed method
         } // end of init
         public void start(){
              if(frozen)
               { // do nothing
              else
                 if(animator == null) {
                           animator = new Thread(this);
                animator.start();  
               } // end of else
               requestFocus(); 
         } // end of start
         public void stop(){
              // stop the animation thread
              animator = null ;
         } // end of stop
         public void run(){
              Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
              while(Thread.currentThread() == animator)
                      repaint();
                      try {
                     Thread.sleep(5400);
                       } catch (InterruptedException e) {
                             break;
         } // end of run
         public void paint(Graphics g){
              Graphics2D g2 = (Graphics2D)g;
            Rectangle leftRect,rightRect,plus_horz,plus_vert;
            Polygon downArrow = new Polygon();    
           // drawing the plus               
           int xHPoint = 440,yHPoint = 350, widthP = 30, heightP = 30;
           plus_horz = new Rectangle(xHPoint,yHPoint,widthP,heightP-27);
           plus_vert = new Rectangle(xHPoint+10,yHPoint-10,widthP-17,heightP-10);
           // black interior
            g2.setColor(Color.black);
            g2.fill(plus_horz);
            // black border
            g2.setColor(Color.black);
            g2.draw(plus_horz);
           // black interior
            g2.setColor(Color.black);
            g2.fill(plus_vert);
            // black border
            g2.setColor(Color.black);
            g2.draw(plus_vert);
               try{
                     Thread.sleep(4000);
                 } catch (InterruptedException ie)
           // drawing the Rectangle
                  leftRect = new Rectangle(300,300,100,100);
             rightRect = new Rectangle(500,300,100,100);
             // white interior
            g2.setColor(Color.white);
            g2.fill(leftRect);
            // black border
            g2.setColor(Color.black);
            g2.draw(leftRect);
            // white interior
            g2.setColor(Color.white);
            g2.fill(rightRect);
            // black border
            g2.setColor(Color.black);
            g2.draw(rightRect);
           try{
                     Thread.sleep(4000);
                 } catch (InterruptedException ie)
           // drawing downArrow
            int xPointA = 340,yPointA = 340, widthA = 30, heightA = 30;
             downArrow.addPoint(xPointA,yPointA);
            downArrow.addPoint(xPointA+25,yPointA-25);
            downArrow.addPoint(xPointA+13,yPointA-25);
            downArrow.addPoint(xPointA+13,yPointA-75);
            downArrow.addPoint(xPointA-13,yPointA-75);
            downArrow.addPoint(xPointA-13,yPointA-25);
            downArrow.addPoint(xPointA-25,yPointA-25);
            g2.setColor(Color.white);
            g2.fill(downArrow);
            // black border
            g2.setColor(Color.black);
            g2.draw(downArrow);
           try{
                     Thread.sleep(4000);
                 } catch (InterruptedException ie)
       // drawing circle             
           int xPoint = 340,yPoint = 340, width = 30, height = 30;
           circle = new java.awt.geom.Ellipse2D.Double(xPoint,yPoint,width,height);
            // black interior
            g2.setColor(Color.black);
            g2.fill(circle);
            // black border
            g2.setColor(Color.black);
            g2.draw(circle);
           try{
                     Thread.sleep(4000);
                 } catch (InterruptedException ie)
         } // end of paint method
    }

    hi ,
    here is modified code . I kept all sleep methods in the run method.
    But the problem is i couldn't get any response from the keyboard.
    What i need is that whenever key presses then animation should starts.
    please help me in this regard.i 'm putting my code here, please modify
    it according to my requirements. Once again i badly need this one to be run. i really appreciate if anyone help in this one.
    Thanks,
    -balaji
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.Applet;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Color;
    import java.awt.Rectangle;
    import java.awt.GradientPaint;
    import java.awt.geom.GeneralPath;
    import java.awt.Polygon;
    //<applet code="ExptA5.class" width=300 height=300></applet>
    public class ExptA5 extends Applet implements Runnable,KeyListener {
         Thread animator;
         Dimension appSize;
         boolean frozen = false;
         int appWidth = 1000, appHeight = 800;
         int delay = 500;
      // drawing circle and arrow.
         DrawCircle circle = new DrawCircle();
        DrawArrow downArrow = new DrawArrow();
         public void init(){
            // setting dimension for applet
              appSize = new Dimension(appWidth,appHeight);
              this.setSize(appSize);
              // adding key listener
             addKeyListener(this);
         } // end of init
    // to activate keys
         public void keyPressed(KeyEvent e ){
              System.out.println("in the keypressed method ");
              ExptA5 exptA5 = (ExptA5) e.getSource();
        // when space bar presses then start the thread and animation starts
              if( e.getKeyCode() == KeyEvent.VK_SPACE)
               if ( Thread.currentThread() == animator)
                     exptA5.animator.start();
              } // end of if
         } // end of keyPressed
    // other key methods
         public void keyTyped(KeyEvent e){}
         public void keyReleased(KeyEvent e){}
         // applet starts and animation starts .
         public void start(){
              if(frozen)
               { // do nothing
              else
                 if(animator == null) {
                           animator = new Thread(this);
                animator.start();
               } // end of else
         } // end of start
         public void stop(){
              // stop the animation thread
              animator = null ;
         } // end of stop
         public void run(){
              Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
              while(Thread.currentThread() == animator)
              try {
                 Graphics g = getGraphics();
                   Graphics2D g2 = (Graphics2D)g;          
                  // drawing arrow which is calling from other class
                 downArrow.drawPoly(g2);
                 // sleeps for a while                               
                 Thread.sleep(5400);
                    // drawing circle which is calling from other class
                    circle.drawCircle(g2);
                    // sleeps for a while
                 Thread.sleep(5400);
                 repaint();   
                       } catch (InterruptedException e) {
                             break;
         } // end of run
         public void paint(Graphics g){
         } // end of paint method
    // drawing circle
    public class DrawCircle{
       java.awt.geom.Ellipse2D.Double circle;
       public void drawCircle(Graphics2D g2)
              int xPoint = 340,yPoint = 340, width = 30, height = 30;
          circle = new java.awt.geom.Ellipse2D.Double(xPoint,yPoint,width,height);
          // black interior
          g2.setColor(Color.black);
          g2.fill(circle);
            // black border
          g2.setColor(Color.black);
          g2.draw(circle);
    // drawing Arrow
    public class DrawArrow{
          Polygon downArrow = new Polygon();
       public void drawPoly(Graphics2D g2)
              // drawing downArrow
            int xPointA = 340,yPointA = 340, widthA = 30, heightA = 30;
             downArrow.addPoint(xPointA,yPointA);
            downArrow.addPoint(xPointA+25,yPointA-25);
            downArrow.addPoint(xPointA+13,yPointA-25);
            downArrow.addPoint(xPointA+13,yPointA-75);
            downArrow.addPoint(xPointA-13,yPointA-75);
            downArrow.addPoint(xPointA-13,yPointA-25);
            downArrow.addPoint(xPointA-25,yPointA-25);
            g2.setColor(Color.white);
            g2.fill(downArrow);
            // black border
            g2.setColor(Color.black);
            g2.draw(downArrow);
    }

  • SetBackground() useless for JComponent?

    if you extend JComponent and then use setBackground(Color.RED), actually there is no change of the background.
    According to the API doc,
    public void setBackground(Color bg)
    Sets the background color of this component. The background color is used only if the component is opaque, and only by subclasses of JComponent or ComponentUI implementations. Direct subclasses of JComponent must override paintComponent to honor this property.
    It is up to the look and feel to honor this property, some may choose to ignore it.
    even if I set the JComponent to be opaque or override paintComponent() method, it doesn't work.
    codes are as follow:
    class MyComponent extends JComponent
    {   public void paintComponent(Graphics g)
        {    setOpaque(true);
             setBackground(Color.RED);  // no use :(
    }so how to interpretate that method detail of api doc? and how to use setBackgound() method to set the background color of a JComponent.
    BTW, if i extend JPanel instead, then in the paintComponent() method, I have to call super.paintComponent(g) --> why so?
    thx in advance

    so if i want to fill the background with RED (it already has some shapes painted on it)I suggest you read about Swing's painting architecture, as described in the tutorial .
    When paintComponent() is invoked (by the Swing painting framework) it is supposed to paint everything (background +++ "other shapes") in the painting rectangle, except:
    - the components underneath (which may appear if your own component is translucent, but that's a bit involved), including the immediate parent Container and its parent container hierarchy, which have automatically paint themselves in that area when their own paintComponent method, before your paintComponent() method was called in turn
    - the components above, which will automatically paint themselves over what your paintComponent() method is just painting, when their own paintComponent method is called in turn.
    If your JComponent subclass paints two things (say, a background fill, and green squares on top of that), it has to paint both each time your paintComponent is called, on the supllied Graphics rectangle.
    class MyComponent extends JComponent
    {   public MyComponent()
        {    setBackground(Color.RED);
        public void paintComponent(Graphics g)
        {    Graphics2D g2=(Graphics2D)g;
             g2.fill(...); // rectangle of background color
             g2.draw(...); // whatever is supposed to appear on top
    if it is g2.fillRect(0,0,getWidth(),getHeight()), then it will cover other drawings on the component.Maybe, but you will redraw those drawings just after filling the rectangle, so they will appear anyway.
    Now if you're concerned with doing an animation, there are a lot of techniques to optimize painting so as to not repaint everything, but do some practice and research before discussing them, as you seem to begin with Swing.
    Good luck.

  • How to Merge Cells in a JTable?

    First, a brief background. I have a 1.3.1 Swing application, and have a custom table framework that is extended from Swing. My table model manages row classes. Each row class has its own collection of renderers and editors. Renderers and editors are never shared; each cell has its own. My custom table asks each row for the renderer/editor as needed. This allows the GUI programmer to customize every cell of a row class, down to the renderer/editor, including which cells are editable. Essentially, my custom table framework puts all the brains into row classes. Each screen has its own row class. So, it's very granular but very powerful. However, I need more power.
    I need a way to merge cells across columns (column spanning). These merged cells do NOT need to be editable for now. I don't know how I can get the table to render one cell across others in the same row. I suspect this is largely a painting issue, and could really use some help.
    Thanks!
    Andy

    Thanks for the direction, Ian! That got me on my way.
    I subclassed BasicTableUI and copy-pasted the private methods into my subclass, and made them protected. I then modified the paintCell( ) method to change the rendering for the particular table row I'm interested in (test case).
    To make the first cell span the entire row, I changed the width of the painting rectangle to be the width of the table, instead of the width of the cell. I also had to NOT render any other cells in that row, so they wouldn't "interfere" with the first renderer. In other words, if I allow cell 3 to be rendered, it will prevent cell 0 from spanning, since cell 3 is rendered AFTER cell 0.
    Here's an example of my proof-of-concept (POC):
    // For row 5, only render cell 0
    if (row == 5) {
        if (column == 0) {
            rendererPane.paintComponent(g, component, table, cellRect.x, cellRect.y, table.getWidth(), cellRect.height, true);
        return;
    }You can see that only cell 0 will be rendered, and it will be as wide as the table.
    My next step will be to experiment with multiple spans in the same row, and then having a cell in the middle span the entire row. I'll post my results for the sake of posterity.

  • Illustratro CS 5.1 snap issues

    Out of the blue now, Illustrator is driving me nuts.
    I am trying to create a rectangle in an existing Illustrator drawing and rotate it into place.
    I draw the rectangle and then click on the "election" arrow to rotate the rectangle to the angle I need. However, as soon as I click on the selection arrow, a bounding box that includes the rectangle and a significant area outside the rectangle is selected. This causes a problem because the rectangle is not the size I need and when I try to rotate and strectch it to fit the area I want, the handles encompass and area much larger and rather than being able to just drag the handles to the size I want, I must play around with them to try to get them to fit.
    I've searched a number of different forums and this appears to be an on-going problem. A number of people said to turn offf snap to grid, snap top point, smart guides, etc. All of these are turned off, but Illustrator continually insists on drawing the recatangle at the initial size I want, but then encompassing a much larger area outside the actual rectangle. Someon suggested going to the Transform menu and turning off an element there, but I wasn't able to find that specific element (perhaps a newer of older version of Illustrator). Someone else said to else suggested going to the align menu and making a change there. Again, my align menu doesn't provide the option that was suggested. I have tried everything I can think of and am getting incredibly irritated.
    Here is a screen shot of what I'm talking about -
    When I draw the rectangle it looks the way I expected it to. However, as soon as I pcik the selection arrow, I get the huge bounding box that has no  correlation to the rectanlge I drew.
    I even treid drawing the rectangle off the artboard and moving it into place, but the same thing happens, wherever I draw the rectangle.
    I had preivously been using Illustrator CS3 and NEVER had this issue. Only in Illustrator CS 5.1.
    I'm ready to dump CS 5.1 and go back to CS 3 - since it works as expected.
    Any help/suggestions would be greatly appreciated!

    This drawing is from an AutoCad file so there are a lot of layers. I did try to create a blank layer and draw the rectangle on it, but same result.
    That said, the vast majority of my files are from AutoCad and I've never had this issue previously, i.e. the past 10-12 years.

  • Maze Application

    I'm not very familiar with a lot of java gui stuff, yet here I am trying to create a fancy gui for a honors project. I've read up on most of the basics, but I haven't seen anything that looks like what I'm trying to do. I have one class called MazeApplication with the program's main method that creates a MazeWindow object in the MazeApplication constructor and sets its location, size, and look and feel. A MazeApplication object is created in the main method.
    The MazeWindow extends JFrame. It has a content pane with a BorderLayout. In the SOUTH is a JPanel which is the control panel for the application. It contains JButtons and JSliders. In the EAST is supposed to be a scrollable JPanel (i'm not yet sure how to use the JScrollbar). In the CENTER is a JPanel containing the Maze object.
    Now this is what I want to do. I have JButtons with actionListeners set up and I want them to run methods from the Maze class when they are pushed. The methods should paint the animations for the create and solve processes on the mazePanel in the MazeWindow. At certain moments I need to simultaneously either paint rectangles representing stacks in the stackPanel or add JLabels to the JPanel from the bottom up if that's possible while certain actions are performed in the maze processes.
    I have most of the coding done. I just need to figure out how to work at connecting all the classes in regards to Threading and the Graphics. Can anyone tell me if there's a MUCH easier approach? My main problem is the JPanel for displaying the stacks; I have no idea how to 1) connect this with the maze animations and 2) draw on the JPanel from the bottom up (since I don't have a limit as to the maze # of maze cell locations that will be pushed onto the stack).

    CROSSPOST.
    http://forum.java.sun.com/thread.jspa?threadID=578765&tstart=0

  • Maze Application help

    I'm not very familiar with a lot of java gui stuff, yet here I am trying to create a fancy gui for a honors project. I've read up on most of the basics, but I haven't seen anything that looks like what I'm trying to do. I have one class called MazeApplication with the program's main method that creates a MazeWindow object in the MazeApplication constructor and sets its location, size, and look and feel. A MazeApplication object is created in the main method.
    The MazeWindow extends JFrame. It has a content pane with a BorderLayout. In the SOUTH is a JPanel which is the control panel for the application. It contains JButtons and JSliders. In the EAST is supposed to be a scrollable JPanel (i'm not yet sure how to use the JScrollbar). In the CENTER is a JPanel containing the Maze object.
    Now this is what I want to do. I have JButtons with actionListeners set up and I want them to run methods from the Maze class when they are pushed. The methods should paint the animations for the create and solve processes on the mazePanel in the MazeWindow. At certain moments I need to simultaneously either paint rectangles representing stacks in the stackPanel or add JLabels to the JPanel from the bottom up if that's possible while certain actions are performed in the maze processes.
    I have most of the coding done. I just need to figure out how to work at connecting all the classes in regards to Threading and the Graphics. Can anyone tell me if there's a MUCH easier approach? My main problem is the JPanel for displaying the stacks; I have no idea how to 1) connect this with the maze animations and 2) draw on the JPanel from the bottom up (since I don't have a limit as to the maze # of maze cell locations that will be pushed onto the stack).

    When I tried simply adding a Maze object to a JPanel in the MazeWindow, I had the problem of my Graphics object of the Maze object being null since, as I mentioned, I'm not sure of what paint methods to use. But now, I'm trying something different. I'm changing the name of the Maze class to MazePanel which extends JPanel. I have a paintComponent(Graphics g) method in the class. The MazePanel class has all the threading, yes. So now, i'm just adding the MazePanel object to the MazeWindow object. Also for the display of the stack, i'm looking into the GridBagLayout and the GridBagConstraints class. I see a SOUTH static variable that might allow me to add JLabel components from the bottom up in the stackPanel. The JLabel objects would contain the coordinates of whatever maze cell is being pushed onto the stack while the solve or create thread is running. Would I have any graphical problems in dynamically adding and deleting components from a container in connection with a thread running?

  • From JPanel to DOS

    Hello all,
    I have a program that runs from DOS by typing "java myProgram" which calls a JFrame class "myClass" that implements some button actions.
    Is it possible to create a new JButton("Return to DOS") with an action that closes the current frame window and returns to the DOS prompt from where we ran the "java myProgram" command?
    Thanks as usual for your help!

    OK maybe with some code the picture is more clear...
    So let's say I have 2 classes, 'DrawRectangle' and 'menu' as follows:
    import java.awt.geom.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class DrawRectangle extends JPanel implements ActionListener
       Rectangle2D.Float rectangle2D;
       protected JButton menu;
       public DrawRectangle()
           //PS: I know that the following should not be in the constructor.
           //This is just a sample example.
           rectangle2D = new Rectangle2D.Float(50F,50F,200,200);
           menu = new JButton("Return to DOS menu");
           add(menu);
           menu.addActionListener(this);
       public void actionPerformed(ActionEvent e)
          if (e.getSource() == menu)
             System.exit(0);           
       public void paint(Graphics g)
           Graphics2D g2 = (Graphics2D)g;
           g2.setPaint(Color.blue);
           g2.draw(rectangle2D);      
        public static void main ()
           JFrame rectangle = new JFrame("My Project");
           rectangle.setSize(400, 400);     
           Container container = rectangle.getContentPane();              
           container.add(new DrawRectangle());      
           rectangle.setVisible(true);      
    import java.io.*;
    class menu
        menu()
           int choice = -1;
           while (choice != 0)
              System.out.println("Please choose an option from 1 to 4, 0 to exit\n");
              BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
              try
                 choice = Integer.parseInt(in.readLine());
                 switch(choice)
                    case 1: choice1(); break;
                    case 2: choice2(); break;
                    case 3: choice3(); break;
                    case 4: choice4(); break;
              catch (Exception ex)
           System.out.println("Exit");       
       private void choice1()
           new DrawRectangle().main();
       private void choice2()
           System.out.println("Choice 2");
       private void choice3()
           System.out.println("Choice 3");      
       private void choice4()
           System.out.println("Choice 4");      
       public static void main(String [] args)
           new menu();
    }Now just to explain, I open a DOS prompt, type 'java menu' and you have four options: 1,2,3,4 and 0 to exit. If you type 2, the system returns "Choice 2" and you can choose another option (which is what I want). If you type 1, the system calls the main method of class 'DrawRectangle' and a JFrame with a painted rectangle opens up. When I click the "Return to DOS menu" button, the JFrame closes and the DOS window is active again. However, the DOS goes on C:\ prompt and not on "Please choose an option from 1 to 4, 0 to exit" as I want. And you have to type again 'java menu' to run the program. Instead, any other option like 2,3 or 4 will give you the chance to choose another option.
    I know that all this sound strange to you, but unfortunately the requirements given to me is to run the program from a DOS prompt and to be able to choose another option without the need of typing again 'java menu'.
    Thanks for your help and attention.

  • I have a graphics 2D object which takes ages to draw....

    I have made a graphics 2D object which draws rectangles of sizes (5,5) accross the width and height of the screen on at a time.
    As you can imagine, this takes ages!!!
    does any one have an idea of how to make this quicker without sacrificing the resolution???
    thanks!

    well, withought code I just can give you some tipps:
    * don't create a new Color in the loop, try to share it
    * try to paint rectangles with same color at one time -> minimize the time how often setColor is called
    * do not create new Objects (like Color) in your paint-loop, share share share...
    btw. I would cache it in an image, otherwise everytime the window-content is invalidated (which can happen quite frequently) your slow drawing code is called.
    btw2. I can't smell your mistakes over the net, already told you to show your rendeing code.

  • Input player name etc

    Hello,
    I am new to Java, so may question may sound silly, but anyway, I need advice.
    I've got class Board:
    public class Board extends JPanel implements RunnableI've got board background image, and all other game graphics in Paint method.
    I'm using game loop, where I call repaint() method. Also I've got KeyListener and MouseListener in this class. Everything works perfectly at this stage. But now I need to create input of player names and other player info (human/nonhuman, credits, etc.). And my question is how to organize this data input?
    That is, I need to create game stage lets say 'DataInput' and during this stage to show input fields to player and to use entered data. What is the best strategy to do that? Should I paint rectangles, listen to keyboard, and print some entered text in that rectangles and accordingly emulate radiobuttons? Or maybe there is some ready, better solution?
    Waiting for any advice,
    Best regards,
    dbpr

    dbprog wrote:
    Thanks for reply. Yes, of course I could use it. But how to switch between JPanels?There are many ways. I can't tell you what you want to do though. Some things to consider: CardLayout , JTabbedPane , or like I already said, using another JFrame or JDialog .

  • Compiler error for implementing custom ButtonUI.

    UIDefaults.getUI() failed: no ComponentUI class for: com.sun.java.swing.plaf.windows.WindowsScrollBarUI$WindowsArrowButton[,0,0,0x0,invalid,layout=javax.swing.OverlayLayout,alignmentX=null,alignmentY=
    null,border=,flags=0,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,disabledSelectedIcon=,margin=null,paintBorder=true,paintFocus=true,pressedIcon=,rolloverEnabled=false,rolloverI
    con=,rolloverSelectedIcon=,selectedIcon=,text=,defaultCapable=true]
    java.lang.Error
    at javax.swing.UIDefaults.getUIError(UIDefaults.java:691)
    at javax.swing.UIDefaults.getUI(UIDefaults.java:721)
    at javax.swing.UIManager.getUI(UIManager.java:784)
    at javax.swing.JButton.updateUI(JButton.java:119)
    Here is implementation of ButtonUI:
    public class DefaultButtonUI extends ButtonUI{
    public DefaultButtonUI() {
    // TODO Auto-generated constructor stub
    super();
    static {
    String DEFAULTCLASSID = "com.pjx.gui.view.laf.plaf.defaultlaf.DefaultLookAndFeel";//$NON-NLS-1$
    UIManager.put(DEFAULTCLASSID, "com.pjx.gui.view.laf.plaf.defaultlaf.DefaultLookAndFeel");
    protected static DefaultButtonUI buttonUI;
    // Instance Methods - Getters and Setters
    // <----------------------------- PUBLIC ------------------------------> //
    public void installUI(JComponent c) {
    super.installUI(c);
    public void uninstallUI(JComponent c) {
    super.uninstallUI(c);
    public static ComponentUI createUI (JComponent c) {
    if (buttonUI == null) {
    buttonUI = new DefaultButtonUI();
    return buttonUI;
    public void paint(Graphics g, JComponent c)
    //Invoke the original UI delegate
    buttonUI.paint( g, c );
    // Now do the custom painting
    Rectangle r = c.getBounds();
    g.setColor( Color.GREEN );
    g.drawLine( 0, 0, r.width, r.height );
    g.drawLine( 0, r.height, r.width, 0 );
    super.paint(g, c);
    public void update(Graphics g, JComponent c) {
    paint(g, c);
    }

    Parameter naming is important. This should work:
    CREATE OR REPLACE PACKAGE reportingaut
    AS
       FUNCTION authenticator (p_username IN VARCHAR2, p_password IN VARCHAR2)
          RETURN BOOLEAN;
    END reportingaut;
    CREATE OR REPLACE PACKAGE BODY reportingaut
    AS
       FUNCTION authenticator (p_username IN VARCHAR2, p_password IN VARCHAR2)
          RETURN BOOLEAN
       AS
       BEGIN
          RETURN TRUE;
       END authenticator;
    END reportingaut;Denes Kubicek
    http://deneskubicek.blogspot.com/
    http://www.apress.com/9781430235125
    http://apex.oracle.com/pls/apex/f?p=31517:1
    http://www.amazon.de/Oracle-APEX-XE-Praxis/dp/3826655494
    -------------------------------------------------------------------

  • Button, or other panel related question

    so, if any of you have read my previous topic about painting rectangles in a panel, that worked great, but now i need to mkae those rectangles components so that when someone hovers over it or clicks on it it displays information at a certain area. I know how to make listeners and how to add buttons in a panel, BUT how do I add buttons at a specific coordinate. This program graphs data on a specific scale and therefore adding a button in the approximate area using a grid layout will not be good enough. Is there anyway for me to place the the button/component/object at the extact location that I want?
    thanks in advance

    In future GUI related questions should be posted in the appropriate GUI forum (likely Swing).
    so, if any of you have read my previous topic about
    painting rectangles in a panel, that worked great,
    but now i need to mkae those rectangles components so
    that when someone hovers over it or clicks on it it
    displays information at a certain area. What?

Maybe you are looking for

  • Does this service work with Google+?

    Does Adobe's Cloud services like Light Room work with photos that were automatically uploaded to Google=?

  • Problem Logging in to Application Post Upgrade to 4.1

    Hello. I have upgraded my APEX install from 4.0 to 4.1. I actually removed the old 4.0 install and did a fresh install. Everything seems OK, I can get into my admin pages etc, except that the application that I developed under 4.0 won't let me past t

  • CS6 & Windows 8.1

    I have PS CS6 and just updated to Win 8.1.  Now my CS6 is not working correctly.  Bridge often comes up "Not Responding" and PS blinks with a b & w checker board while working within a photo.  I believe this to be a settings issue, however been unabl

  • Submit Button to Submit Form From Browser

    I have created a form in Adobe Acrobat Pro and uploaded it to my website. On my website, all the functions are working except for the Sumbit Button. I know that I can change the address in the properties to mailto:[email protected] but when someone s

  • Installtion JDEV1012 at Windows2000 Advance Server -Not running

    Dear All I am new to JDeveloper. I download Jdev1012 zip file then Unzip it into D:\jdev. When I click on Jdev or Jdevw (both in D:\jdev\jdev\bin) just a screen flash and closes? what is the wrong and what I should have to do in addtion? Please expla