Help on drawing in GUI

Attached is the file that i need to draw on the GUI. Anyone can tell me how to code it? Each ring distance is 5km away from one another. Maximum is 20km. If i want to have a "cross" on 9 O'clock at distance 15km on it, how should i do it?
Thanks in advance.
http://i4.photobucket.com/albums/y119/Ryoichi/1.gif

Extend JPanel and override the public void paintComponent(Graphics g) method.
Use the graphics primatives provided by the Graphics object provided as an argument to the method. You can also cast the g to a Graphics2D object which gives a more comprehensive set of drawing methods.
public class MyPanel extends JPanel {
  public void paintComponent(Graphics g) {
    Graphics2D g2d = (Graphics2D)g;
    g2d.draw...
}

Similar Messages

  • I need help to draw in a frame, please

    Hi Im new to java and I need some help to draw a rainbow in a frame. I already made the frame , but i dont know how to draw inside the frame.
    here is my code so far:
    import java.awt.*;
    import javax.swing.*;
    public class Regnbue {
         public static void main(String[]args){
              JFrame ramme = new JFrame();
              ramme.setSize(600,300);
              Container cp = ramme.getContentPane();
              cp.setBackground(Color.white);
              ramme.setVisible(true);
    any help to finish this simple draw would be nice!!
    thanx

    I forgot , here is my code so far :
    import java.awt.*;
    import javax.swing.*;
    public class Regnbue {
         public static void main(String[]args){
              Rainbowpanel r= new Rainbowpanel();// her is where i make
    // my frame I think.
              JFrame ramme = new JFrame();
              ramme.setSize(600,300);
              Container cp = ramme.getContentPane();
              cp.setBackground(Color.white);
              ramme.setVisible(true);
    class Rainbowpanel extends JPanel {
         public void paintComponent(Graphics g) {// this is the part that I
    // dont understand, how can I put the arc into the container above??
              super.paintComponent(g);
              g.fillArc(5, 5, 10, 50, 0, 180);
         thanks
    elektropan

  • Need Help to Draw and Drag Triangle - URGENT

    Hi everyone - I am developing various proofs of the pythagora's theorem
    and the following code draws a triangle on screen and the proof follows -
    but i need to know how to drag the triangle such tht 1 angle is always set to 90 degrees.
    i.e. i need to resize the triangle by dragging its vertex points by which the1 angle remains at 90 no matter what the size.
    The proof has got some graphics code hardcoded in it - i.e. LINES AND POLYGONS have been hardcoded
    i need to reconfigure that such that everytime the user increases the size of the triagnle and clicks on next it draws the lines and polygons in the correct area and place
    PLEASE HELP
    the code is as follows
    MAIN CLASS
    import java.awt.BorderLayout;
    import java.awt.Container;
    import java.awt.*;
    import java.awt.event.*;
    import java.text.*;
    import javax.swing.*;
    public class TestProof {
        TestControl control;          // the controls for the visual proof
        TestView view;          // the drawing area to display proof
        // called upon class creation
        public TestProof() {
            view = new TestView();
    view.setBackground(Color.WHITE);
            control = new TestControl(view);
            Frame f = new Frame("Pythagoras");
            f.add(view,"Center");
            f.add(control,"South");
            f.setSize(600,600);
            f.setBackground(Color.lightGray);
            f.addMouseMotionListener(
            new MouseMotionListener() { //anonymous inner class
                //handle mouse drag event
                public void mouseMoved(MouseEvent e) {
                    System.out.println("Mouse  " + e.getX() +","  + e.getY());
                public void mouseDragged(MouseEvent e) {
                    System.out.println("Draggg: x=" + e.getX() + "; y=" + e.getY());
            JMenu File = new JMenu("File");
            JMenuItem Exit = new JMenuItem("Exit");
            Exit.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    ExitActionPerformed(evt);
            JMenuBar menuBar = new JMenuBar();
            menuBar.add(File);
       File.add(Exit);
            f.add(menuBar,"North");
            f.show();
        private JMenuBar getMenuBar() {
            JMenu File = new JMenu("File");
            JMenuItem Exit = new JMenuItem("Exit");
            Exit.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    ExitActionPerformed(evt);
            JMenuBar menuBar = new JMenuBar();
            menuBar.add(File);
                 File.add(Exit);   
            return menuBar;
        private void ExitActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
            System.exit(0);
        // for standalone use
        public static void main(String args[]) {
      TestProof TP = new TestProof();
    }Test VIEW
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.text.*;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class TestView extends Canvas {
        int TRANSLUCENT = 1;
        int sequence;          // sequencer that determines what should be drawn
        // notes matter
        int noteX = 100;     // note coordinates
        int noteY = 60;
        int fontSize = 11;     // font size
        int lineSpacing     // space between two consecutive lines
        = fontSize + 2;
        Font noteFaceFont;     // font used to display notes
        // objects matter
        Polygon tri;          // right-angled triangle with sides A, B, and C
        Polygon tri1;
        Polygon sqrA;          // square with side of length A
        Polygon sqrB;          // square with side of length B
        Polygon sqrC;          // square with side of length C
        Polygon parA;          // parallelogram of base A and height A
        Polygon parB;          // parallelogram of base B and height B
        Polygon poly1;
        Polygon poly2;
        Polygon poly3;
        Polygon poly4;
        Polygon poly5;
        Polygon poly6;
        int X0 = 350;          // coordinates of triangle
        int Y0 = 350;
        int A = 90;//60;          // triangle size
        int B = 120;//80;
        int C = 150;//100;
        //CORDS of 2nd triangle
        int X1 = 350;
        int Y1 = 500;
        // notes: three lines per note
        String notes[] = {
            // note 0
            // note 1
            // note 2
            // note 3
            // note 4
            // note 5
            // note 6
            // note 7
            // note 8
            // note 9
            // note 10
            // note 11
            // note 12
            // note 13
            // note 14
        // constructor
        public TestView() {
            addMouseMotionListener(
            new MouseMotionListener() { //anonymous inner class
                //handle mouse drag event
                public void mouseMoved(MouseEvent e) {
                    System.out.println("Mouse  " + e.getX() +","  + e.getY());
                public void mouseDragged(MouseEvent e) {
                    System.out.println("Draggg: x=" + e.getX() + "; y=" + e.getY());
            // set font
            noteFaceFont = new Font("TimesRoman", Font.PLAIN, fontSize);
            // (coordinates specified w.r.t. to P0, unless otherwise specified)
            // create the triangle
            tri = new Polygon();
            tri.addPoint(0, 0);                    // add P0 coordinate
            tri.addPoint(A*A/C, -A*B/C);          // add A3 coordinate
            tri.addPoint(C, 0);                    // add C1 coordinate
            tri.translate(X0, Y0);               // place triangle
            tri1 = new Polygon();
            tri1.addPoint(0,0);                    // add P0 coordinate
            tri1.addPoint(A*A/C +38, +A*B/C);          // add A3 coordinate
            tri1.addPoint(C, 0);                    // add C1 coordinate
            tri1.translate(X1, Y1);
            // create square of side A
            sqrA = new Polygon();
            sqrA.addPoint(0, 0);               // add P0 coordinate
            sqrA.addPoint(-A*B/C, -A*A/C);          // add A1 coordinate
            sqrA.addPoint(-A*(B-A)/C, -A*(A+B)/C);     // add A2 coordinate
            sqrA.addPoint(A*A/C, -A*B/C);          // add A3 coordinate
            sqrA.translate(X0, Y0);               // place square
            // create square of side B
            // warning: the coordinate of this object are specified relative to C1
            sqrB = new Polygon();
            sqrB.addPoint(0, 0);               // add C1 coordinate
            sqrB.addPoint(B*A/C, -B*B/C);          // add B1 coordinate
            sqrB.addPoint(B*(A-B)/C, -B*(A+B)/C);     // add B2 coordinate
            sqrB.addPoint(-B*B/C, -B*A/C);          // add A3 coordinate
            sqrB.translate(X0 + C, Y0);               // place square
            // create square of side C
            sqrC = new Polygon();
            sqrC.addPoint(0, 0);               // add P0 coordinate
            sqrC.addPoint(C, 0);               // add C1 coordinate
            sqrC.addPoint(C, C);               // add C2 coordinate
            sqrC.addPoint(0, C);               // add C3 coordinate
            sqrC.translate(X0, Y0);               // place square
            poly1 = new Polygon();
            poly1.addPoint(405,279);
            poly1.addPoint(413,350);
            poly1.addPoint(432,500);
            poly1.addPoint(442,571);
            poly1.addPoint(500,500);
            poly1.addPoint(500,350);
            poly2 = new Polygon();
            poly2.addPoint(279,297);
            poly2.addPoint(404,280);
            poly2.addPoint(571,254);
            poly2.addPoint(500,350);
            poly2.addPoint(350,350);
            //Polygon 3
            poly3 = new Polygon();
            poly3.addPoint(404,280);
            poly3.addPoint(350,350);
            poly3.addPoint(414,350);
            poly4 = new Polygon();
            poly4.addPoint(350,350);
            poly4.addPoint(350,500);
            poly4.addPoint(442,572);
            poly4.addPoint(433,500);
            poly4.addPoint(414,350);
            poly5 = new Polygon();
            poly5.addPoint(476,183);
            poly5.addPoint(332,225);
            poly5.addPoint(278,295);
            poly5.addPoint(404,279);
            poly5.addPoint(571,254);
            poly6= new Polygon();
            poly6.addPoint(405,278);
            poly6.addPoint(332,224);
            poly6.addPoint(476,182);
            // create parallelogram of height A
            parA = new Polygon();
            parA.addPoint(0, 0);               // add P0 coordinate
            parA.addPoint(0, C);               // add C3 coordinate
            parA.addPoint(A*A/C, C - A*B/C);          // add Q0 coordinate
            parA.addPoint(A*A/C, -A*B/C);          // add A3 coordinate
            parA.translate(X0,Y0);               // place parallelogram
            // create parallelogram of height B
            // warning: the coordinate of this object are specified from C1
            parB = new Polygon();
            parB.addPoint(0, 0);               // add C1 coordinate
            parB.addPoint(-B*B/C, -B*A/C);          // add A3 coordinate
            parB.addPoint(A*A/C - C, C - A*B/C);     // add Q0 coordinate
            parB.addPoint(0, C);               // add C2 coordinate
            parB.translate(X0 + C, Y0);
            // place parallelogram
        // depending on the sequence number we draw certain objects
        public void paint(Graphics gfx) {
            super.paint(gfx);
            Graphics2D g = (Graphics2D) gfx;
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);
            // text first, then objects (and animation)
            // we always output some notes
            g.drawString(notes[3*sequence], noteX, noteY);
            g.drawString(notes[3*sequence + 1], noteX, noteY + lineSpacing);
            g.drawString(notes[3*sequence + 2], noteX, noteY + 2*lineSpacing);
            // the object are drawn in an order so that they are properly overlapped
            if(sequence == 13) {
                g.setColor(Color.green);
                g.fillPolygon(poly1);
                g.fillPolygon(poly2);
                g.fillPolygon(poly3);
                g.fillPolygon(poly4);
                g.fillPolygon(poly5);
                g.setColor(Color.RED);
                g.setColor(Color.GREEN);
                g.drawLine(413,351,433,499);
                g.setColor(Color.white);
                g.fillPolygon(tri);
                g.fillPolygon(tri1);
                g.fillPolygon(poly6);
            if(sequence == 12 ) {
                g.setColor(Color.green);
                g.fillPolygon(poly1);
                g.fillPolygon(poly2);
                g.fillPolygon(poly3);
                g.fillPolygon(poly4);
                g.fillPolygon(poly5);
                g.setColor(Color.BLACK);
            if(sequence == 11){
                g.setColor(Color.green);
                g.fillPolygon(poly1);
                g.fillPolygon(poly3);
                g.fillPolygon(poly4);
                g.setColor(Color.BLACK);
            if(sequence == 8 ){
                g.setColor(Color.green);
                g.fillPolygon(poly5);
                g.setColor(Color.MAGENTA);
                g.drawString("E",578,254);
                g.drawString("D",268,302);
                g.setColor(Color.black);
                g.drawArc(250,150,350,250,320,65);
            else if (sequence == 9 ){
                g.setColor(Color.green);
                g.fillPolygon(poly2);
                g.setColor(Color.MAGENTA);
                g.drawString("E",578,254);
                g.drawString("D",268,302);
                g.setColor(Color.black);
                g.drawArc(250,150,350,250,320,65);
            if( sequence == 10){
                g.setColor(Color.green);
                g.fillPolygon(poly2);
                g.fillPolygon(poly5);
                g.setColor(Color.black);
                g.setColor(Color.MAGENTA);
                g.drawString("E",578,254);
                g.drawString("D",268,302);
                g.setColor(Color.black);
                g.drawArc(250,150,350,250,320,65);
            if(sequence == 7){
                g.setColor(Color.green);
                g.fillPolygon(poly2);
                g.setColor(Color.MAGENTA);
                g.drawString("E",578,254);
                g.drawString("D",268,302);
                g.setColor(Color.black);
            if(sequence == 6){
                g.setColor(Color.yellow);
                g.fillPolygon(poly2);
                g.setColor(Color.green);
                g.fillPolygon(poly3);
                g.setColor(Color.blue);
                g.fillPolygon(poly4);
                g.setColor(Color.black);
                g.drawArc(250,175,350,275,300,65);
                //g.drawArc(250,150,350,250,320,65);
                g.drawLine( 606,309,599,299);
                g.drawLine(592,313, 599,299);
                g.drawString("+90 degrees",605,378);
            if (sequence == 5 ) {
                g.setColor(Color.yellow);
                g.fillPolygon(poly2);
                g.setColor(Color.black);
            if (sequence == 4) {
                g.setColor(Color.YELLOW);
                g.fillPolygon(poly1);
                g.setColor(Color.black);
                g.drawArc(319,310,250,195,89,-35);
                g.drawLine(499,319, 492,312);
                g.drawLine(499,319, 492,325);
                g.drawArc(200,180, 233,238,-120,-60);
                g.drawLine(200,298, 208,309);
                g.drawLine(200,298, 194,313);
                g.drawString("-90 degrees",227,347);
            if (sequence >= 3) {
                g.drawLine(404,279,442,572);
            // draw the squares
            if (sequence >= 2) {
                g.drawLine(278,296,572,254);
            // draw the squares
            if (sequence >= 1) {
                g.drawLine(333,224,476,182);
                g.drawPolygon(tri1);
            // always draw the triangle
            g.drawPolygon(tri);
            g.drawPolygon(sqrA);
            g.drawPolygon(sqrB);
            g.drawPolygon(sqrC);
            g.setColor(Color.MAGENTA);
            g.drawString("C", X0 + C/2 - fontSize/2, Y0 + lineSpacing);
            g.drawString("A",
            X0 + A*A/(2*C) - fontSize*A/B/2,
            Y0 - A*B/(2*C) - lineSpacing*A/B);
            g.drawString("B",
            X0 + C - B*B/(2*C) - fontSize*A/B/2,// the last "-" isn't log.
            Y0 - B*A/(2*C) - lineSpacing*A/B);
        public void redraw(int sequence) {
            this.sequence = sequence;
            repaint();
    }TEST CONTROL
    * TestControl.java
    * Created on 28 February 2005, 11:16
    import java.awt.*;
    import java.awt.event.*;
    import java.text.*;
    import javax.swing.JFrame;
    * @author  Kripa Bhojwani
    public class TestControl extends Panel implements ActionListener {
      TestView view;
      int sequence;                    // event sequence
      // constructor
      public TestControl(TestView view) {
        Button b = null;
        Label label = new Label("A^2 ");
        this.view = view;          // initialize drawble area
        sequence = 0;               // initialize sequence
        b = new Button("Prev");
        b.addActionListener(this);
        add(b);
        b = new Button("Next");
        b.addActionListener(this);
        add(b);
        add(label);
      // exported method
      public void actionPerformed(ActionEvent ev) {
        String label = ev.getActionCommand();
        if (label.equals("Prev")) {
          if (sequence >0) {
         --sequence;
        else {
          if (sequence < 15) {
         ++sequence;
        this.setEnabled(false);          // disable the controls
        view.redraw(sequence);
        this.setEnabled(true);          // enable the controls
    }Please help --- really need to sort this out...
    THANKS

    One of the problems you face is that it is hard to recognise which parts of your code are drawing the triangle. This is because you are writing code in a procedural way rather than an object oriented way.
    In object oriented code you would have a triangle object that could draw itself. You would create the triangle object by specifying its sizes and angles in some way. Then it should be easy to change the triangles sizes and angles and ask all the drawn objects to redraw themselves.

  • Help with drawing strings on JFrame?!?!

    Hey guys, I'm really new to Java (just started AP Comp Sci last month), and we had a project to build a Mastermind application using numbers, which I did. However, I'm trying to learn more on my own, and was hoping to use the example code my teacher gave me to output what I want to say to a JFrame instead of just the command prompt.
    Here is the code for my Mastermind class:
    Code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Mastermind extends JFrame
         public static void main(String args[])
              int master[] = new int[4];
              int win = 0;
              for(int x = 0; x<4; x++)
                   master[x] = (int)(Math.random()*10);
              System.out.println();
              do {
                   int guess[] = new int[4];
                   int countMaster[] = new int[4];
              String numguess = JOptionPane.showInputDialog("Enter your guess (4 digits, please)");
              for (int x = 0;x<4;x++)
                   guess[x] = (numguess.charAt(x)-48);
              int correctlyPlaced = 0;
              int correct = 0;
              for (int x = 0;x<4;x++)
                   if(master[x] == guess[x])
                        correctlyPlaced += 1;
              for (int x = 0; x<4;x++)
                             for (int y = 0; y<4;y++)
                                  if((guess[x]==master[y]) && (countMaster[y]==0)) {
                                       correct++;
                                       countMaster[y]=1;
                                       y=5;
              System.out.print("Guess:\t\t\t");
              for (int x = 0;x<4;x++) {
                   System.out.print(guess[x]);
              System.out.println();
              System.out.println("Correct:\t\t"+correct);
              System.out.println("Correctly Placed:\t"+correctlyPlaced);
              if (correctlyPlaced==4) {
                   win=1;
         } while(win<1);
         System.out.println("You win!");
              System.exit(0);
    And here is the example code that my teacher gave me for how to draw a string on a JFrame:
    Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Fonts extends JFrame {
         public Fonts()
              super("Using Fonts");
              setSize(420,125);
              show();
         public void paint(Graphics g)
              super.paint(g);
              g.setFont(new Font("Serif", Font.BOLD, 12));
              g.drawString("Serif 12 point bold.",20,50);
         public static void main(String args[])
              Fonts application = new Fonts();
              application.setDefaultCloseOperation (
                   JFrame.EXIT_ON_CLOSE);
    I would like to be able to put "Guess," "Correct," and "Correctly Placed," on a JFrame, with their respective variables. Any ideas? Thank you!!!

    800045 wrote:
    And DrClap, I get that, but I'm not sure how to put my existing code into the class file that uses the JFrame.You wouldn't put your existing code in there. Your existing code is designed to run as a console app and most of it is concerned with the machinery of getting input from the user. If you want to write it as a Swing app, then you wouldn't need any code which writes to a JFrame in the first place.
    So if your goal for learning on your own is to write GUI applications instead of console applications, then go off and read the Swing tutorials. Right now you're going down the wrong road. However if you're trying to learn something else on your own (I can't tell what that might be) then explain what it is you're trying to learn.

  • I need help to draw an image and move it plz plz : )

    Ok, so I have this whole code and I understand most of it but not all of it but I'm trying to make image "drop.gif" to move down the right side of the window. For each shot that is taken the image moves down ever so much and if the image hits the Entity ship "background" than notify death. PLease anyone help me !
    there are 7 classes but here is the main ...
    package spaceinvaderss;
    import java.awt.Canvas;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics2D;
    import java.awt.Image;
    import java.awt.Toolkit;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.awt.image.BufferStrategy;
    import java.util.ArrayList;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class Main extends Canvas {
    /*A Canvas component represents a blank rectangular area of the screen onto which the application can draw or from which the application can trap input events from the user.
    An application must subclass the Canvas class in order to get useful functionality such as creating a custom component.
    The paint method must be overridden in order to perform custom graphics on the canvas.*/
    /** The stragey that allows us to use accelerate page flipping.*/
    private BufferStrategy strategy;
    /** True if the game is currently "running", i.e. the game loop is looping */
    private boolean gameRunning = true;
    /** The list of all the entities that exist in our game */
    private ArrayList entities = new ArrayList();
    /** The list of entities that need to be removed from the game this loop */
    private ArrayList removeList = new ArrayList();
    /** The entity representing the player */
    private Entity ship;
    /** The entity representing the alien */
    private Entity alien;
    /** The speed at which the player's ship should move (pixels/sec) */
    private double moveSpeed = 600;
    /** The time at which last fired a shot */
    private long lastFire = 0;
    /** The interval between our players shot (ms) */
    private long firingInterval = 400;
    /** timer */
    private long time = 0;
    /** The number of aliens left on the screen */
    private int alienCount;
    /** The message to display which waiting for a key press */
    private String message = "";
    /** True if we're holding up game play until a key has been pressed */
    private boolean waitingForKeyPress = true;
    /** True if the left cursor key is currently pressed */
    private boolean leftPressed = false;
    /** True if the right cursor key is currently pressed */
    private boolean rightPressed = false;
    /** True if we are firing */
    private boolean firePressed = false;
    /** True if game logic needs to be applied this loop, normally as a result of a game event */
    private boolean logicRequiredThisLoop = false;
    private static Image drop;
    /** The constant for the width*/
    private int DOMAIN = 800;
    /** The constant fot the length*/
    private int RANGE = 950;
    /** The constant for the number of rows of aliens */
    private int numbaofrows = 8;
    /** The constant for the number of aliens per row */
    private int aliensperrow = 12;
    /** The constant for the percent of which the speed increases*/
    private double speedincrease = 1.02;
    /** Starts the variable that counts the shots*/
    private int shotsfired = 0;
    /** Construct our game and set it running.*/
    public Main() {
    // Creates a frame to contain Main.
    JFrame container = new JFrame("SPACE INVADERS !!! WOOT !!! WOOT !!!");
    // Gets a hold of the content of the frame and sets up the resolution of the game
    // Names the inside of the "container" as panel.
    JPanel panel = (JPanel) container.getContentPane();
    // Stes the demensions of the panel.
    panel.setPreferredSize(new Dimension(DOMAIN,RANGE));
    //Sets the layout as nothing which overrides any automatic properties.
    panel.setLayout(null);
    // Sets up our canvas size and puts it into the content of the frame
    setBounds(0, 0, DOMAIN, RANGE);
    panel.add(this);
    // Tell AWT not to bother repainting our canvas since we're
    // going to do that our self in accelerated mode.
    setIgnoreRepaint(true);
    // Actually sizes the window approximately.
    container.pack();
    // Makes it so that the window can't be resized.
    container.setResizable(false);
    // Makes the window visible.
    container.setVisible(true);
    // Add a listener to respond to the user pressing the x.
    // End the program when the window is closed.
    container.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    // add a key input system (defined below) to our canvas
    // so we can respond to key pressed
    addKeyListener(new KeyInputHandler());
    // request the focus so key events come to us
    requestFocus();
    // Create the buffering strategy which will allow AWT
    // to manage our accelerated graphics.
    createBufferStrategy(2);
    strategy = getBufferStrategy();
    // initialise the entities in our game so there's something
    // to see at startup
    initEntities();
    time = System.currentTimeMillis();
    * Start a fresh game, this should clear out any old data and
    * create a new set.
    private void startGame() {
    // clear out any existing entities and intialise a new set
    entities.clear();
    initEntities();
    // blank out any keyboard settings we might currently have
    leftPressed = false;
    rightPressed = false;
    firePressed = false;
    * Initialise the starting state of the entities (ship and aliens). Each
    * entitiy will be added to the overall list of entities in the game.
    private void initEntities() {
    ClassLoader cloader = Main.class.getClassLoader();
    drop = Toolkit.getDefaultToolkit().getImage(cloader.getResource("drop.gif"));
    prepareImage(drop, this);
    // create the player ship and place it in the center of the screen
    ship = new ShipEntity(this,"background.gif", 0, (RANGE - 75));
    entities.add(ship);
    ship = new ShipEntity(this,"ship.gif", (DOMAIN / 2) - 0, (RANGE - 50));
    entities.add(ship);
    // create a block of aliens
    alienCount = 0;
    for (int row = 0; row < numbaofrows; row++) {
    for (int x = 0; x < aliensperrow; x++) {
    alien = new AlienEntity(this,"alien.gif", 100 + (x*50),(50)+row*30);
    entities.add(alien);
    alienCount++;
    * Notification from a game entity that the logic of the game
    * should be run at the next opportunity (normally as a result of some
    * game event)
    public void updateLogic() {
    logicRequiredThisLoop = true;
    * Remove an entity from the game. The entity removed will
    * no longer move or be drawn.
    * Remove the entity
    public void removeEntity(Entity entity) {
    removeList.add(entity);
    /**Notify that the player has died.*/
    public void notifyDeath() {
    message = "Oh no! The aliens win, wanna try again?";
    waitingForKeyPress = true;
    /** Notification that the player has won since all the aliensare dead.*/
    public void notifyWin() {
    long time2;
    time2 = (System.currentTimeMillis() - time) / 1000;
    int acuracy = 1000*(aliensperrow*numbaofrows)/shotsfired;
    message = "Congradulations! You win! Your time was: " + time2 + " seconds. Your acuracy was " + acuracy + "%.";
    waitingForKeyPress = true;
    /**Notification that an alien has been killed*/
    public void notifyAlienKilled() {
    // reduce the alient count, if there are none left, the player has won!
    alienCount--;
    if (alienCount == 0) {
    notifyWin();
    // if there are still some aliens left then they all need to get faster, so
    // speed up all the existing aliens
    for (int i = 0; i < entities.size(); i++) {
    Entity entity = (Entity) entities.get(i);
    if (entity instanceof AlienEntity) {
    // speed up every time the aliens move down
    entity.setHorizontalMovement(entity.getHorizontalMovement() * speedincrease);
    /**Attempt to fire a shot from the player. Its called "try" since we must first
    * check that the player can fire at this point, i.e. has he/she waited long
    * enough between shots.*/
    public void tryToFire() {
    // check that we have been waiting long enough to fire
    if (System.currentTimeMillis() - lastFire < firingInterval) {
    return;
    // if we waited long enough, create the shot entity, and record the time.
    lastFire = System.currentTimeMillis();
    ShotEntity shot = new ShotEntity(this, "bullet.gif", ship.getX() + 27, ship.getY() - 30);
    entities.add(shot);
    * The main game loop. This loop is running during all game
    * play as is responsible for the following activities:
    * - Working out the speed of the game loop to update moves
    * - Moving the game entities
    * - Drawing the screen contents (entities, text)
    * - Updating game events
    * - Checking Input
    public void gameLoop() {
    long lastLoopTime = System.currentTimeMillis();
    // Keep looping around till the game ends.
    while (gameRunning) {
    // Work out how long its been since the last update, this
    // will be used to calculate how far the entities should
    // move this loop.
    long delta = System.currentTimeMillis() - lastLoopTime;
    lastLoopTime = System.currentTimeMillis();
    // Get hold of a graphics context for the accelerated
    // surface and black it out.
    Graphics2D g = (Graphics2D) strategy.getDrawGraphics();
    g.setColor(Color.black);
    g.fillRect(0, 0, DOMAIN, RANGE);
    // Cycle around asking for each entity to move itself.
    if (!waitingForKeyPress) {
    for (int i = 0; i < entities.size(); i++) {
    Entity entity = (Entity) entities.get(i);
    entity.move(delta);
    // cycle round drawing all the entities we have in the game
    for (int i = 0; i < entities.size(); i++) {
    Entity entity = (Entity) entities.get(i);
    entity.draw(g);
    // brute force collisions, compare every entity against
    // every other entity. If any of them collide notify
    // both entities that the collision has occured
    for (int p = 0; p < entities.size(); p++) {
    for (int s = p + 1; s < entities.size(); s++) {
    Entity me = (Entity) entities.get(p);
    Entity him = (Entity) entities.get(s);
    if (me.collidesWith(him)) {
    me.collidedWith(him);
    him.collidedWith(me);
    // remove any entity that has been marked for clear up
    entities.removeAll(removeList);
    removeList.clear();
    // if a game event has indicated that game logic should
    // be resolved, cycle round every entity requesting that
    // their personal logic should be considered.
    if (logicRequiredThisLoop) {
    for (int i = 0; i < entities.size(); i++) {
    Entity entity = (Entity) entities.get(i);
    entity.doLogic();
    logicRequiredThisLoop = false;
    // if we're waiting for an "any key" press then draw the
    // current message
    if (waitingForKeyPress) {
    g.setColor(Color.green);
    g.drawString(message,(DOMAIN-g.getFontMetrics().stringWidth(message)) / 2, 250);
    g.drawString("TO PLAY, PRESS ANY KEY : )", (DOMAIN-g.getFontMetrics().stringWidth("TO PLAY, PRESS ANY KEY : )")) / 2, 40);
    // Clear up the graphics.
    g.dispose();
    // Flip the buffer over.
    strategy.show();
    // resolve the movement of the ship. First assume the ship
    // isn't moving. If either cursor key is pressed then
    // update the movement appropraitely
    ship.setHorizontalMovement(0);
    if ((leftPressed) && (!rightPressed)) {
    ship.setHorizontalMovement(-moveSpeed);
    } else if ((rightPressed) && (!leftPressed)) {
    ship.setHorizontalMovement(moveSpeed);
    // if we're pressing fire, attempt to fire
    if (firePressed) {
    shotsfired++;
    tryToFire();
    // finally pause for a bit. Note: this should run us at about
    // 100 fps but on windows this might vary each loop due to
    // a bad implementation of timer
    try { Thread.sleep(10); } catch (Exception e) {}
    * A class to handle keyboard input from the user. The class
    * handles both dynamic input during game play, i.e. left/right
    * and shoot, and more static type input (i.e. press any key to
    * continue)
    * This has been implemented as an inner class more through
    * habbit then anything else. Its perfectly normal to implement
    * this as seperate class if slight less convienient.
    private class KeyInputHandler extends KeyAdapter {
    /** The number of key presses we've had while waiting for an "any key" press */
    private int pressCount = 1;
    * Notification from AWT that a key has been pressed. Note that
    * a key being pressed is equal to being pushed down but NOT
    * released. Thats where keyTyped() comes in.
    * @param e The details of the key that was pressed
    public void keyPressed(KeyEvent e) {
    // if we're waiting for an "any key" typed then we don't
    // want to do anything with just a "press"
    if (waitingForKeyPress) {
    return;
    if (e.getKeyCode() == KeyEvent.VK_LEFT) {
    leftPressed = true;
    if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
    rightPressed = true;
    if (e.getKeyCode() == KeyEvent.VK_SPACE) {
    firePressed = true;
    * Notification from AWT that a key has been released.
    * @param e The details of the key that was released
    public void keyReleased(KeyEvent e) {
    // if we're waiting for an "any key" typed then we don't
    // want to do anything with just a "released"
    if (waitingForKeyPress) {
    return;
    if (e.getKeyCode() == KeyEvent.VK_LEFT) {
    leftPressed = false;
    if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
    rightPressed = false;
    if (e.getKeyCode() == KeyEvent.VK_SPACE) {
    firePressed = false;
    * Notification from AWT that a key has been typed. Note that
    * typing a key means to both press and then release it.
    * @param e The details of the key that was typed.
    public void keyTyped(KeyEvent e) {
    // if we're waiting for a "any key" type then
    // check if we've recieved any recently. We may
    // have had a keyType() event from the user releasing
    // the shoot or move keys, hence the use of the "pressCount"
    // counter.
    if (waitingForKeyPress) {
    if (pressCount == 1) {
    // since we've now recieved our key typed
    // event we can mark it as such and start
    // our new game
    waitingForKeyPress = false;
    startGame();
    pressCount = 0;
    } else {
    pressCount++;
    // if we hit escape, then quit the game
    if (e.getKeyChar() == 27) {
    System.exit(0);
    * The entry point into the game. We'll simply create an
    * instance of class which will start the display and game
    * loop.
    * @param argv The arguments that are passed into our game
    public static void main(String argv[]) {
    Main g = new Main();
    // Starts the main game loop, this method will not return until the game has finished running. Hence we are
    // using the actual main thread to run the game.
    g.gameLoop();
    }                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    Ap_Compsci_student_13 wrote:
    ok sorry but doesn't sscce say to post the whole code?the first S is Short, and yes, it needs to be all the code needed to illustrate the problem and let use reproduce it. If you were developing a new Web framework, your example might be short, but for a student game it's very long.

  • Need help to draw recangle on video

    Hi guys ,
    Below I have pasted my code . In this code I have defined frame and in that frame stored video run. The other class has defined rectangle in cnvas . My problem is that I want rectangle to be drawn on video player and I havnt been successful.
    So its my reequest to please help me out.
    Thanks a ton in advance........
    public class Map extends JFrame
    * MAIN PROGRAM / STATIC METHODS
    public static void main(String args[])
    Map mdi = new Map();
    static void Fatal(String s)
    MessageBox mb = new MessageBox("JMF Error", s);
    * VARIABLES
    JMFrame jmframe = null;
    JDesktopPane desktop;
    FileDialog fd = null;
    CheckboxMenuItem cbAutoLoop = null;
    Player player = null;
    Player newPlayer = null;
    //JPanel glass = null;
    SelectionArea drawingPanel;
    String filename;
    // code//
    //ArrayList<Rectangle> rectangles = new ArrayList<Rectangle>();
    // boolean stop=false;
    * METHODS
    public Map()
    super("Java Media Player");
    drawingPanel = new SelectionArea(this);
    // Add the desktop pane
    setLayout( new BorderLayout() );
    desktop = new JDesktopPane();
    desktop.setDoubleBuffered(true);
    add("Center", desktop);
    setMenuBar(createMenuBar());
    setSize(640, 480);
    setVisible(true);
    //add(drawingPanel);
    //drawingPanel.setVisible(true);
    try
    UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
    catch (Exception e)
    System.err.println("Could not initialize java.awt Metal lnf");
    addWindowListener( new WindowAdapter()
    public void windowClosing(WindowEvent we)
    System.exit(0);
    Manager.setHint(Manager.LIGHTWEIGHT_RENDERER, new Boolean(true));
    private MenuBar createMenuBar()
    ActionListener al = new ActionListener()
    public void actionPerformed(ActionEvent ae)
    String command = ae.getActionCommand();
    if (command.equals("Open"))
    if (fd == null)
    fd = new FileDialog(Map.this, "Open File",
    FileDialog.LOAD);
    fd.setDirectory("/movies");
    fd.show();
    if (fd.getFile() != null)
    String filename = fd.getDirectory() + fd.getFile();
    openFile("file:" + filename);
    else if (command.equals("Exit"))
    dispose();
    System.exit(0);
    MenuItem item;
    MenuBar mb = new MenuBar();
    // File Menu
    Menu mnFile = new Menu("File");
    mnFile.add(item = new MenuItem("Open"));
    item.addActionListener(al);
    mnFile.add(item = new MenuItem("Exit"));
    item.addActionListener(al);
    // Options Menu
    Menu mnOptions = new Menu("Options");
    cbAutoLoop = new CheckboxMenuItem("Auto replay");
    cbAutoLoop.setState(true);
    mnOptions.add(cbAutoLoop);
    mb.add(mnFile);
    mb.add(mnOptions);
    return mb;
    * Open a media file.
    public void openFile(String filename)
    String mediaFile = filename;
    Player player = null;
    // URL for our media file
    URL url = null;
    try
    // Create an url from the file name and the url to the
    // document containing this applet.
    if ((url = new URL(mediaFile)) == null)
    Fatal("Can't build URL for " + mediaFile);
    return;
    // Create an instance of a player for this media
    try
    player = Manager.createPlayer(url);
    catch (NoPlayerException e)
    Fatal("Error: " + e);
    catch (MalformedURLException e)
    Fatal("Error:" + e);
    catch (IOException e)
    Fatal("Error:" + e);
    if (player != null)
    this.filename = filename;
    JMFrame jmframe = new JMFrame(player, filename);
    desktop.add(jmframe);
    if (player.getVisualComponent() != null)
    getContentPane().add(player.getVisualComponent());
    player.start();
    jmframe.add(drawingPanel);
    drawingPanel.setVisible(true);
    /*validate();
    public void paint(Graphics g)
    drawingPanel.repaint();
    public void update(Graphics g)
    paint(g);
    drawingPanel.repaint();
    class SelectionArea extends Canvas implements ActionListener, MouseListener, MouseMotionListener
    Rectangle currentRect;
    Map controller;
    //for double buffering
    Image image;
    Graphics offscreen;
    public SelectionArea(Map controller)
    super();
    this.controller = controller;
    addMouseListener(this);
    addMouseMotionListener(this);
    public void actionPerformed(ActionEvent ae)
    repaintoffscreen();
    public void repaintoffscreen()
    image = createImage(this.getWidth(), this.getHeight());
    offscreen = image.getGraphics();
    Dimension d = size();
    if(currentRect != null)
    //Rectangle box = new Rectangle();
    //box.getDrawable(currentRect, d);
    Rectangle box = getDrawableRect(currentRect, d);
    //Draw the box outline.
    offscreen.drawRect(box.x, box.y, box.width - 1, box.height - 1);
    repaint();
    public void mouseEntered(MouseEvent me) {}
    public void mouseExited(MouseEvent me){ }
    public void mouseClicked(MouseEvent me){}
    public void mouseMoved(MouseEvent me){}
    public void mousePressed(MouseEvent me)
    currentRect = new Rectangle(me.getX(), me.getY(), 0, 0);
    repaintoffscreen();
    public void mouseDragged(MouseEvent me)
    System.out.println("here in dragged()");
    currentRect.setSize(me.getX() - currentRect.x, me.getY() - currentRect.y);
    repaintoffscreen();
    repaint();
    public void mouseReleased(MouseEvent me)
    currentRect.setSize(me.getX() - currentRect.x, me.getY() - currentRect.y);
    repaintoffscreen();
    repaint();
    public void update(Graphics g)
    paint(g);
    public void paint(Graphics g)
    g.drawImage(image, 0, 0, this);
    Rectangle getDrawableRect(Rectangle originalRect, Dimension drawingArea)
    int x = originalRect.x;
    int y = originalRect.y;
    int width = originalRect.width;
    int height = originalRect.height;
    //Make sure rectangle width and height are positive.
    if (width < 0)
    width = 0 - width;
    x = x - width + 1;
    if (x < 0)
    width += x;
    x = 0;
    if (height < 0)
    height = 0 - height;
    y = y - height + 1;
    if (y < 0)
    height += y;
    y = 0;
    //The rectangle shouldn't extend past the drawing area.
    if ((x + width) > drawingArea.width)
    width = drawingArea.width - x;
    if ((y + height) > drawingArea.height)
    height = drawingArea.height - y;
    return new Rectangle(x, y, width, height);
    }

    Chances of someone reading a gazillion lines of unformatted code: < 1%
    Paste your code (from the source), highlight it and click the CODE button to retain formatting and make it readable.

  • Need help to draw a graph from the output I get with my program please

    Hi all,
    I please need help with this program, I need to display the amount of money over the years (which the user has to enter via the textfields supplied)
    on a graph, I'm not sure what to do further with my program, but I have created a test with a System.out.println() method just to see if I get the correct output and it looks fine.
    My question is, how do I get the input that was entered by the user (the initial deposit amount as well as the number of years) and using these to draw up the graph? (I used a button for the user to click after he/she has entered both the deposit and year values to draw the graph but I don't know how to get this to work?)
    Please help me.
    The output that I got looked liked this: (just for a test!) - basically this kind of output must be shown on the graph...
    The initial deposit made was: 200.0
    After year: 1        Amount is:  210.00
    After year: 2        Amount is:  220.50
    After year: 3        Amount is:  231.53
    After year: 4        Amount is:  243.10
    After year: 5        Amount is:  255.26
    After year: 6        Amount is:  268.02
    After year: 7        Amount is:  281.42
    After year: 8        Amount is:  295.49
    After year: 9        Amount is:  310.27
    After year: 10        Amount is:  325.78
    After year: 11        Amount is:  342.07
    After year: 12        Amount is:  359.17
    After year: 13        Amount is:  377.13
    After year: 14        Amount is:  395.99
    After year: 15        Amount is:  415.79
    After year: 16        Amount is:  436.57
    After year: 17        Amount is:  458.40And here is my code that Iv'e done so far:
    import javax.swing.*;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.RenderingHints;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.lang.Math;
    import java.text.DecimalFormat;
    public class CompoundInterestProgram extends JFrame implements ActionListener {
        JLabel amountLabel = new JLabel("Please enter the initial deposit amount:");
        JTextField amountText = new JTextField(5);
        JLabel yearsLabel = new JLabel("Please enter the numbers of years:");
        JTextField yearstext = new JTextField(5);
        JButton drawButton = new JButton("Draw Graph");
        public CompoundInterestProgram() {
            super("Compound Interest Program");
            setSize(500, 500);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            amountText.addActionListener(this);
            yearstext.addActionListener(this);
            JPanel panel = new JPanel();
            panel.setBackground(Color.white);
            panel.add(amountLabel);
            amountLabel.setToolTipText("Range of deposit must be 20 - 200!");
            panel.add(amountText);
            panel.add(yearsLabel);
            yearsLabel.setToolTipText("Range of years must be 1 - 25!");
            panel.add(yearstext);
            panel.add(drawButton);
            add(panel);
            setVisible(true);
            public static void main(String[] args) {
                 DecimalFormat dec2 = new DecimalFormat( "0.00" );
                CompoundInterestProgram cip1 = new CompoundInterestProgram();
                JFrame f = new JFrame();
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                f.getContentPane().add(new GraphPanel());
                f.setSize(500, 500);
                f.setLocation(200,200);
                f.setVisible(true);
                Account a = new Account(200);
                System.out.println("The initial deposit made was: " + a.getBalance() + "\n");
                for (int year = 1; year <= 17; year++) {
                      System.out.println("After year: " + year + "   \t" + "Amount is:  " + dec2.format(a.getBalance() + a.calcInterest(year)));
              @Override
              public void actionPerformed(ActionEvent arg0) {
                   // TODO Auto-generated method stub
    class Account {
        double balance = 0;
        double interest = 0.05;
        public Account() {
             balance = 0;
             interest = 0.05;
        public Account(int deposit) {
             balance = deposit;
             interest = 0.05;
        public double calcInterest(int year) {
               return  balance * Math.pow((1 + interest), year) - balance;
        public double getBalance() {
              return balance;
    class GraphPanel extends JPanel {
        public GraphPanel() {
        public void paintComponent(Graphics g) {
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setColor(Color.red);
    }Your help would be much appreciated.
    Thanks in advance.

    watertownjordan wrote:
    http://www.jgraph.com/jgraph.html
    The above is also good.Sorry but you need to look a bit more closely at URLs that you cite. What the OP wants is a chart (as in X against Y) not a graph (as in links and nodes) . 'jgraph' deals with links and nodes.
    The best free charting library that I know of is JFreeChart from www.jfree.org.

  • Need Help with drawing in Photoshop CC

    I am drawing a picture and want to select and copy an element but don't know how.  Can someone help me please?

    If element is on it's own layer, from Layers panel right click and select duplicate layer.
    Nancy O.

  • Desperate need of HELP for a Java GUI !

    Hy people,
    I am working on a project trying to display a GUI where its output is dependant on the user's input.
    Here is a brief example of what Im trying to do:
    You have a GUI that contains 2 panels. buttonPanel and DisplayPanel.
    buttonPanel contains:
    a dropdown list: includes choices of colors,
    2 textfields: the length: (can enter from 1 to 100),
    the width: (can enter from 1 to 100),
    a checkbox: random
    and a start button.
    Now when I enter ALL the information needed in the components and then press start button, it should display its result in the DisplayPanel.
    In my case, I want to display just one rectangle to start off. That will have its color changed by the dropdown choice made. Now Im forgetting about the length and width textfield for now cause that will be incorporated for something else later on.
    I created a buttonLitener for the start button and an ItemListener for the dropDown List.
    I declared and drew a rectangle specific to the color chosen by the user in a class I created called DrawingCanvas that extends Canvas and that overrides the paint method.
    BUT My problem is that it does not display the rectangle I created in my DisplayPanel when I press on the Start button.
    I provided a screenshot of the GUI interface, and my 2 java files. Is someone brave enough to fix my problem or even tell me what Im doing wrong ?!
    ScreenShot:
    http://www.hybrid.concordia.ca/~boumbo/GUIProblem.jpg
    Java Files:
    http://www.hybrid.concordia.ca/~boumbo/GUI.zip]Java Files
    PLEASE I am not Amazing with Java, and pulling my hair out in figuring out my problem.
    Thank you.

    Seriously, look at the first reply in the following thread. It gives a pretty good idea of generally accepted good practices in the forum.
    http://forum.java.sun.com/thread.jspa?threadID=603683
    It is probably better to post code directly on the forum than to try to get people to take the extra steps to download, unzip, and compile your code. That way, they can just cut and paste to try to compile. Be sure to use [code][/code] tags to make your code easier to use. And, try to provide a small example of your problem if the code is very long or complex.
    Another piece of advice. Don't try to challenge the regulars in this forum to prove that they are smart enough, brave enough, whatever enough to tackle YOUR problem. The regulars here include software engineers, authors, and generally very smart and experienced people They don't need to prove themselves to anyone.
    What they want to see is that you have genuinely tried to understand your problem, rather than just running to the forum the first time you get a compiler error.
    You seem to have been working on this problem. Go ahead and create a test case that shows what the problem is. Quite frequently, just doing that will help you solve the problem yourself.
    Good luck.
    RD-R
    � {�
    Mon Mar 07 00:57:45 EST 2005
    Pseudo-random saying number 257 of 635
    For every complex problem, there is a solution that is simple, neat,
    and wrong.
                    -- Henry Louis Mencken

  • Help with a better GUI??

    hi everyone!!
    i am thinking for a better GUI i have already made..earlier my GUI was not reflecting any changes but with the help and suggestions by many of you i have tried to change it..but i still find it is not reflecting to be a good interface.i really need some help..i am hereby posting the code ..hope to get a good GUI than i have..
    Thanks a lot
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.filechooser.*;
    public class front3 extends JFrame
         JRadioButton split,zip,rename,unzip;
             ButtonGroup radioGroup;
          public front3()
          Container c = getContentPane();
             c.setLayout(new  GridLayout(0,1)); 
          c.setBackground(Color. cyan);
           setSize(530,120);
          setResizable(false); // to disable  the maximize  button
            ImageIcon ip= new ImageIcon("title.jpg");
            JLabel j1=new JLabel("Choose the operation to be done :",ip,JLabel.CENTER);
    j1.setBackground(Color.red);
    c.add(j1);
             ImageIcon ii= new ImageIcon("split.jpg");
             split=new JRadioButton("Splitter",ii,false);
             split.setBackground(Color.cyan);
          ImageIcon ij= new ImageIcon("zip.jpg");
             zip=new JRadioButton("Zipper",ij,false);
             zip.setBackground(Color.cyan);
          ImageIcon ik= new ImageIcon("rename.jpg");
             rename=new JRadioButton("Rename all",ik,false);
          rename.setBackground(Color.cyan);
          ImageIcon il= new ImageIcon("unzip.jpg");
             unzip=new JRadioButton("unzip",il,false);
             unzip.setBackground(Color.cyan);
             c.add (split);
             c.add(zip);
             c.add(unzip);
             c.add(rename);
      // create logical relationship between JRadioButtons
          radioGroup = new ButtonGroup();
             radioGroup.add(split );
             radioGroup.add( zip);
             radioGroup.add(rename );
             radioGroup.add( unzip);
          //  setPosition(250,250);
    setTitle("FILE UTILITY SOFTWARE");
    setSize(300,500);
             setVisible(true);
    split.addItemListener(new ItemListener()
    public void itemStateChanged(ItemEvent event)
    if(split.isSelected())
    Gui file = new Gui();
    zip.addItemListener(new ItemListener()
    public void itemStateChanged(ItemEvent event)
    if(zip.isSelected())
    zipping file = new zipping();
    unzip.addItemListener(new ItemListener()
    public void itemStateChanged(ItemEvent event)
    if(unzip.isSelected())
    decompress file = new decompress();
    rename.addItemListener(new ItemListener()
    public void itemStateChanged(ItemEvent event)
    if(rename.isSelected())
    rename file = new rename();
       public static void main(String args[])
                  front3 f=new front3();
                  f.addWindowListener(
                       new WindowAdapter() {
                            public void windowClosing(WindowEvent e)
                                 System.exit(0);
      }

    simply run this code to see the GUI-
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.filechooser.*;
    public class front33 extends JFrame
         JRadioButton split,zip,rename,unzip;
             ButtonGroup radioGroup;
          public front33()
          Container c = getContentPane();
             c.setLayout(new  GridLayout(0,1)); 
          c.setBackground(Color. cyan);
           setSize(530,120);
          setResizable(false); // to disable  the maximize  button
            ImageIcon ip= new ImageIcon("title.jpg");
            JLabel j1=new JLabel("Choose the operation to be done :",ip,JLabel.CENTER);
    j1.setBackground(Color.red);
    c.add(j1);
             ImageIcon ii= new ImageIcon("split.jpg");
             split=new JRadioButton("Splitter",ii,false);
             split.setBackground(Color.cyan);
          ImageIcon ij= new ImageIcon("zip.jpg");
             zip=new JRadioButton("Zipper",ij,false);
             zip.setBackground(Color.cyan);
          ImageIcon ik= new ImageIcon("rename.jpg");
             rename=new JRadioButton("Rename all",ik,false);
          rename.setBackground(Color.cyan);
          ImageIcon il= new ImageIcon("unzip.jpg");
             unzip=new JRadioButton("unzip",il,false);
             unzip.setBackground(Color.cyan);
             c.add (split);
             c.add(zip);
             c.add(unzip);
             c.add(rename);
      // create logical relationship between JRadioButtons
          radioGroup = new ButtonGroup();
             radioGroup.add(split );
             radioGroup.add( zip);
             radioGroup.add(rename );
             radioGroup.add( unzip);
          //  setPosition(250,250);
    setTitle("FILE UTILITY SOFTWARE");
    setSize(300,500);
             setVisible(true);
    public static void main(String args[])
                  front33 f=new front33();
                  f.addWindowListener(
                       new WindowAdapter() {
                            public void windowClosing(WindowEvent e)
                                 System.exit(0);
      }

  • Help hiding button in GUI

    Hi,
    I need some help. I want to hide a button in my app's GUI if a related file is not present in the Documents. Here's the code that tries to hide the button:
    tmpStr = [currTxtPath stringByReplacingOccurrencesOfString:@"txt" withString:@"dt"];
    NSLog(tmpStr);
    BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:tmpStr];
    NSLog((fileExists) ? @"YES" : @"NO");
    [picInfoButton setHidden:NO];
    if (!fileExists) {
    [picInfoButton setHidden:YES];
    The here's the output on the console, indicating that the file is not present.
    2010-05-14 17:47:39.978 myApp[8169:207] */Users/me/Library/Application Support/iPhone Simulator/3.2/Applications/4A86E2E1-8F75-4DC0-9767-63AE1963AD2A/Documents/Text_ 0001.dt*
    2010-05-14 17:47:39.979 myApp[8169:207] NO
    Given the log info, can someone tell me why the button does not get hidden?
    Many thanks,
    Sam

    Hey Sam -
    Your code looks fine, so it's most likely the 'picInfoButton' ivar doesn't point to the button object you're observing. Add another log statement to check that:
    tmpStr = [currTxtPath stringByReplacingOccurrencesOfString:@"txt" withString:@"dt"];
    NSLog(tmpStr);
    BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:tmpStr];
    NSLog((fileExists) ? @"YES" : @"NO");
    NSLog(@"picInfoButton=%@", picInfoButton); // <-- does this print "(null)"?
    [picInfoButton setHidden:NO];
    if (!fileExists) {
    [picInfoButton setHidden:YES];
    If the ivar is nil and the button is defined in a xib, make sure the controller's 'picInfoButton' outlet is connected to the button. If the ivar isn't nil, verify that the address printed in the log is actually the address of the visible button. For example, make sure you didn't reset 'picInfoButton' to a newly created button that was never added to the superview. Also make sure there isn't a second button covering the button that's connected to the ivar.
    - Ray

  • Search Help works in SAP GUI but not in PCUI - CRM_UI

    Hi,
    I have created a Search Help for creaing Complaints w/ref to Invoice(using the BADI CRM_COPY_BADI_EXTERN) and in the search help i have used standard data elements, so that it brings the standard Search Helps for the fields in the actual Search Help. I get the F4 values in the standard screen (CRMD_ORDER) in the SAP GUI, however i dont see the Searh Help values in WEB UI.
    Is there anything else i need to do for me to get the F4 option in the Web UI as well?
    Thanks
    Sri

    Hi Harshit,
    I have tried F2 and found out the component and did some research on it:
    1) I wasn't able to press F2 once the Pop Up for the Search Help triggered. I was able to press F2 in the screen before i pressed F4. That is, i was able to get the component of the Reference Field in the Complaint Transaction. I wasn't able to press F2 once i get the Search Help.
    2) I used the component that i found and tried to change properties, but all that the component has is regarding the Reference Field only. I dont see where i can give the code for the fields in search help.
    Am i missing something here? Is it that we can't define properties for the fields within the search help?
    Please share your thoughts.
    Thanks
    Sri

  • Search Help works in SAP GUI but not in WEB UI - CRM

    Hi,
    I have created a Search Help for creaing Complaints w/ref to Invoice and in the search help i have used standard data elements, so that it brings the standard Search Helps for the fields in the actual Search Help. I get the F4 values in the standard screen (CRMD_ORDER) in the SAP GUI, however i dont see the Searh Help values in WEB UI.
    Is there anything else i need to do for me to get the F4 option in the Web UI as well?
    Thanks
    Sri

    Hi sri tayi ,
    Can you just tell how you solve this problem ? I am also facing same problem . So , please kindly help for same.....
    Thank You ,

  • Help in drawing graphics.

    Hi friends,
    I'm newbie in drawing graphics with Java, and I need some help in a specific part of my program.
    What I want to do is to draw a waveform of a sound file. That waveform is built based on the amplitude of each sound sample. So I have a big vector full of those amplitudes. Now what I need to do is plot each point on the screen. The x coordinate of the point will be its time position in the time axis. The y coordinate of the point will be the amplitude value. Ok... Now I have a lot of doubts...
    1 - can someone give me a simple example on how to plot points in a java app? I know I have to extend a JPainel class, but I don't know much about those paint, and repaint methods. It's all weird to me. I already searched through the tutorial and the web, but I couldn't see a simple, good example. Can someone hand me this?
    2 - Once I know how to draw those graphics, I need to find a way to put a button, or anything like that, in my app, so the user can press that button to see to next part of the waveform, since the wave is BIG, and doesn't fit entirely on the screen. Is this button idea ok? Can I use some sort of SCROLL on it, would it be better?
    Well... I'm trying to learn it all. ANY help will be appreciated, ANY good link, little hint, first step, anything.
    Thanks for all, in advance.
    Leonardo
    (Brazil)

    This will lead you, in this sample you have a panel and a button,
    every click will fill a vector with random 700 points and draw them on the panel,
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    public class Wave extends Frame implements ActionListener
         WPanel   pan    = new WPanel();
         Vector   points = new Vector();
         Button   go     = new Button("Go");
         Panel    cont   = new Panel();
    public Wave()
         super();
         setBounds(6,6,700,400);     
         addWindowListener(new WindowAdapter()
        {     public void windowClosing(WindowEvent ev)
                   dispose();     
                   System.exit(0);
         add("Center",pan);
         go.addActionListener(this);
         cont.add(go);
         add("South",cont);
         setVisible(true);
    public void actionPerformed(ActionEvent a)
         points.removeAllElements();
         for (int j=0; j < 700; j++)
              int y = (int)(Math.random()*350);
              points.add(new Point(j,y+1));
         pan.draw(points);
    public class WPanel extends Panel
         Vector   points;
    public WPanel()
         setBackground(Color.pink);
    public void draw(Vector points)
         this.points = points;
         repaint();
    public void paint(Graphics g)
         super.paint(g);
         if (points == null) return;
         for (int j=1; j < points.size(); j++)
              Point p1 = (Point)points.get(j-1);
              Point p2 = (Point)points.get(j);
              g.drawLine(p1.x,p1.y,p2.x,p2.y);
    public static void main (String[] args)
         new Wave();  
    Noah

  • Help with implementing Swing GUI within jpg image

    Dear Java Experts,
    I have a question, is there a way to implement java swing objects (ie jbutton, jcombobox, etc) within an imageicon. Basically, i am trying to juggle between ways of getting JSwing GUI into a background jpg image. Please help me. I thank you all in advance.

    You've it back to front.
    Create an transparent extension of JPanel that paints an image on it's
    background before running it's super class paint method.
    You'll need to extend this example to stretch, center or tile the image
    but otheriwse it's complete.
    BTW - you have to pass an argument to this example that is the path of
    the image you want on the background of the panel, like:
    java -cp <whatever> MyJavaProject1 images/something.gif
    Enjoy.
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class MyJavaProject1
         static class BackgroundPanel
              extends JPanel
              private ImageIcon mIcon;
              public BackgroundPanel(ImageIcon icon) {
                   mIcon= icon;
                   super.setOpaque(false);
              public void setOpaque(boolean flag) { }
              public void paint(Graphics g)
                   g.drawImage(mIcon.getImage(), 0, 0, null);
                   super.paint(g);
         public static void main(String[] argv)
              JFrame frame= new JFrame(argv[0]);
              BackgroundPanel panel= new BackgroundPanel(new ImageIcon(argv[0]));
              panel.setLayout(new GridLayout(0,2,4,4));
              panel.setBorder(new EmptyBorder(4,4,4,4));
              panel.add(new JLabel("Name"));
              panel.add(new JTextField());
              panel.add(new JLabel("Address"));
              panel.add(new JTextField());
              panel.add(new JLabel("Phone"));
              panel.add(new JTextField());
              frame.getContentPane().add(panel, BorderLayout.CENTER);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.pack();
              frame.setResizable(false);
              frame.setVisible(true);
    }

Maybe you are looking for