Drawing oval

Here i draw net consist of 6 rows and 7 columns , then i want to draw oval in the top of the net . I think i wrote correct code but the oval not appear .
I want to know why ??
my simple code :
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JFrame;
public class TestNet extends JFrame {
    private DrawingNet drawingNet;
    public TestNet() {
        drawingNet = new DrawingNet();
        getContentPane().add(drawingNet, BorderLayout.CENTER);
    public static void main(String[] args) {
        TestNet testNet = new TestNet();
        testNet.setDefaultCloseOperation(TestNet.EXIT_ON_CLOSE);
        testNet.setSize(new Dimension(600, 300));
        testNet.setLocationRelativeTo(null);
        testNet.setVisible(true);
        testNet.setExtendedState(MAXIMIZED_BOTH);
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JPanel;
class DrawingNet extends JPanel {
    private static final int ROW = 6, COL = 7;
    private int X_START, Y_START, DISTANCE_Y, DISTANCE_X;
    private int x_OVAL = 348, y_OVAL = 17, OVAL_Width = 83, OVAL_HEIGHT = 83;
    public DrawingNet() {
        MyOval myOval = new MyOval();
        myOval.setOval_X(x_OVAL);
        myOval.setOval_Y(y_OVAL);
        myOval.setOVAL_WIDTH(OVAL_Width);
        myOval.setOVAL_HEIGHT(OVAL_HEIGHT);
        add(myOval);
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        drawingNet(g2d);
    private void drawingNet(Graphics2D g2d) {
        X_START = 97;
        Y_START = 100;
        DISTANCE_Y = 0;
        DISTANCE_X = 0;
        g2d.setColor(Color.BLACK);
        for (int r = 0; r < ROW; r++) {
            g2d.drawLine(X_START, Y_START + DISTANCE_Y, X_START * COL, Y_START + DISTANCE_Y);
            DISTANCE_Y += 83;
        for (int c = 0; c <= COL; c++) {
            g2d.drawLine(X_START + DISTANCE_X, Y_START, X_START + DISTANCE_X, (Y_START * ROW) - 83);
            DISTANCE_X += 83;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JPanel;
class MyOval extends JPanel {
    private int oval_X, oval_Y;
    private int OVAL_WIDTH, OVAL_HEIGHT;
    public MyOval() {
    public void setOVAL_HEIGHT(int OVAL_HEIGHT) {
        this.OVAL_HEIGHT = OVAL_HEIGHT;
    public void setOVAL_WIDTH(int OVAL_WIDTH) {
        this.OVAL_WIDTH = OVAL_WIDTH;
    public void setOval_X(int oval_X) {
        this.oval_X = oval_X;
    public void setOval_Y(int oval_Y) {
        this.oval_Y = oval_Y;
    public int getOVAL_HEIGHT() {
        return OVAL_HEIGHT;
    public int getOVAL_WIDTH() {
        return OVAL_WIDTH;
    public int getOval_X() {
        return oval_X;
    public int getOval_Y() {
        return oval_Y;
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.setColor(Color.BLUE);
        g2d.fillOval(getOval_X(), getOval_Y(), getOVAL_WIDTH(), getOVAL_HEIGHT());
}Thanks

ok, i but in MyOval button to test if it will appear or no and i add someLayouts like this but the buttont also not appear . why ??
see the updated code :
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JFrame;
public class TestNet extends JFrame {
    private DrawingNet drawingNet;
    public TestNet() {
        drawingNet = new DrawingNet();
        drawingNet.setLayout(new BorderLayout());
        getContentPane().add(drawingNet, BorderLayout.CENTER);
    public static void main(String[] args) {
        TestNet testNet = new TestNet();
        testNet.setDefaultCloseOperation(TestNet.EXIT_ON_CLOSE);
        testNet.setSize(new Dimension(600, 300));
        testNet.setLocationRelativeTo(null);
        testNet.setVisible(true);
        testNet.setExtendedState(MAXIMIZED_BOTH);
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JPanel;
class DrawingNet extends JPanel {
    private static final int ROW = 6, COL = 7;
    private int X_START, Y_START, DISTANCE_Y, DISTANCE_X;
    private int x_OVAL = 348, y_OVAL = 17, OVAL_Width = 83, OVAL_HEIGHT = 83;
    public DrawingNet() {
        MyOval myOval = new MyOval();
        myOval.setLayout(new BorderLayout());
        myOval.setOval_X(x_OVAL);
        myOval.setOval_Y(y_OVAL);
        myOval.setOVAL_WIDTH(OVAL_Width);
        myOval.setOVAL_HEIGHT(OVAL_HEIGHT);
        add(myOval,BorderLayout.NORTH);
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        drawingNet(g2d);
    private void drawingNet(Graphics2D g2d) {
        X_START = 97;
        Y_START = 100;
        DISTANCE_Y = 0;
        DISTANCE_X = 0;
        g2d.setColor(Color.BLACK);
        for (int r = 0; r < ROW; r++) {
            g2d.drawLine(X_START, Y_START + DISTANCE_Y, X_START * COL, Y_START + DISTANCE_Y);
            DISTANCE_Y += 83;
        for (int c = 0; c <= COL; c++) {
            g2d.drawLine(X_START + DISTANCE_X, Y_START, X_START + DISTANCE_X, (Y_START * ROW) - 83);
            DISTANCE_X += 83;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
class MyOval extends JPanel {
    private int oval_X, oval_Y;
    private int OVAL_WIDTH, OVAL_HEIGHT;
    public MyOval() {
        JButton button = new JButton("OVAL");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(null, "HIIIIIIIIIIII");
        add(button, BorderLayout.NORTH);
    public void setOVAL_HEIGHT(int OVAL_HEIGHT) {
        this.OVAL_HEIGHT = OVAL_HEIGHT;
    public void setOVAL_WIDTH(int OVAL_WIDTH) {
        this.OVAL_WIDTH = OVAL_WIDTH;
    public void setOval_X(int oval_X) {
        this.oval_X = oval_X;
    public void setOval_Y(int oval_Y) {
        this.oval_Y = oval_Y;
    public int getOVAL_HEIGHT() {
        return OVAL_HEIGHT;
    public int getOVAL_WIDTH() {
        return OVAL_WIDTH;
    public int getOval_X() {
        return oval_X;
    public int getOval_Y() {
        return oval_Y;
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.setColor(Color.BLUE);
        g2d.fillOval(getOval_X(), getOval_Y(), getOVAL_WIDTH(), getOVAL_HEIGHT());
}

Similar Messages

  • Get # from JTextfield, draw that # ovals, push button for color

    all
    i have an assignment that requires the user to enter a JTextField integer value.
    that value is then used to draw an equal # of ovals.
    after the ovals are drawn user selects a color button (red/blue) to fill the ovals already drawn based on the button color.
    i have everything coded and working except the coloring.
    i need help because i can't seem to figure out where or how to fill the ovals with the colors of the button pushed.
    OvalDriver7b invokes OvalFrame7B invokes OvalPanel7B.
    thanx
    75gator
    * OvalDriver7B.java
    * Created on April 26, 2004, 1:50 PM
    * @author  dbraxton
    // declare OvalDriver7b class
    public class OvalDriver7B  {
      public static void main (String [ ] args)  {
        OvalFrame7B oframe = new OvalFrame7B();
        oframe.setTitle("Request ovals by text ");
        oframe.show();
      }// terminate main
    }// terminate OvalDriver7B
    * OvalFrame7B.java
    * Created on April 26, 2004, 2:35 PM
    // @author  dbraxton
    // import JAVA API classes
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    // class declaration
    public class OvalFrame7B extends JFrame  {
      private JTextField numOvals;
      private JLabel labelField;
      private JButton rButton, bButton;
      private JPanel textPanel, buttonPanel;
      private OvalPanel7B opanel;
      final int WIDTH = 300;
      final int HEIGHT = 300;
      public OvalFrame7B()  {
        setSize(800,565);
        this.addWindowListener(new WindowCloser());
        opanel = new OvalPanel7B();
        labelField = new JLabel("Enter integer for # ovals: ");
        numOvals = new JTextField(2);
        rButton = new JButton("RED");
        bButton = new JButton("BLUE");
        numOvals.addActionListener(new TextFieldListener());
        Color rColor = new Color(255,0,0);
        Color bColor = new Color(0,0,255);
        buttonPanel  = new JPanel();
        buttonPanel.setLayout(new GridLayout (1,2));
        buttonPanel.add(rButton);
        buttonPanel.add(bButton);
        //JButton colorButton = new JButton("Change circle color?");
            //colorButton.addActionListener(new ColorListener());
        rButton.addActionListener(new ActionListener()  {
            public void actionPerformed(ActionEvent event)  {
                //color ovals red ????????
               opanel.repaint();
        bButton.addActionListener(new ActionListener()  {
            public void actionPerformed(ActionEvent event)  {
              //color ovals blue ????????
              opanel.repaint();
        textPanel = new JPanel();
        textPanel.setLayout(new GridLayout (1,2));
        textPanel.add(labelField);
        textPanel.add(numOvals);
        Container contentPane = getContentPane();
        contentPane.setLayout(new BorderLayout());
        contentPane.add(opanel, "Center");
        contentPane.add(textPanel, "South");
        contentPane.add(buttonPanel, "North");
      private class TextFieldListener implements ActionListener  {
        public void actionPerformed(ActionEvent event)  {
          String input = numOvals.getText();
          opanel.setOvalCount(Integer.parseInt(input));
          numOvals.setText("");
      private class WindowCloser extends WindowAdapter  {
        public void WindowClosing (WindowEvent wex)  {
          System.exit(0);
    * OvalPanel7B.java
    * Created on April 26, 2004, 2:35 PM
    * @author  dbraxton
    // import JAVA API classes
    import javax.swing.*;
    import java.awt.*;
    import java.awt.geom.*;
    import java.util.Random;
    // begin class declaration
    class OvalPanel7B extends JPanel  {
      private int ovalcount;
      private static final double O_WIDTH = 50;
      private static final double O_HEIGHT = 100;
      double w1 = 100,  h1 = 100;
      OvalPanel7B()  {
      public void paintComponent(Graphics g)  {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        Random rnd = new Random();
        g2.setBackground(Color.WHITE);
        for ( int i=0; i < ovalcount; i++)  {
          double x = rnd.nextDouble() +  w1;
          double y = rnd.nextDouble() +  h1;
          w1 = w1 + 50;
          h1 = h1 + 0;
          Ellipse2D.Double oval = new Ellipse2D.Double(x,y,O_WIDTH,O_HEIGHT);
          g2.setColor(Color.BLACK);
          if ( i % 2 > 0)  {
            g2.draw(oval);
          else
             x = rnd.nextDouble() +  w1;
             y = rnd.nextDouble() +  h1;
             g2.draw(oval);
        }w1 = 100;  h1 = 100;
      public void setOvalCount (int cntx)  {
        ovalcount = cntx;
        repaint();
    }

    Hi,
    This forum is for asking questions about using Sun Java Studio so the kind of people who might know the answer might not be reading these posts.
    I am thinking that a better place to get answers for this question is https://java-net.dev.java.net/servlets/ForumMessageList?forumID=95

  • Hi, odd error in my code with a draw circle method

    Hey, I am a first year computer science student who uses java in class.
    We have recently been playing with guis
    I have created code that when it runs it draws random circles with random gradiants.
    However, the code will sometimes draw a random square, any ideas.
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import javax.imageio.*;
    * Class for animations, if I dont finish this lab I will have egg on my face
    public class AnimationStation {
         private JFrame frame; //the jframe
         private IView viewer; //the viewer
         * Constructor
         public AnimationStation() {
              frame = new JFrame(); //makes jframe
              viewer = new IView(); //makes iview
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //window closes
              frame.setSize(300, 500); //biggie or smallie
              frame.getContentPane().add(BorderLayout.CENTER,viewer); //place it
              frame.setVisible(true);
         * Main Method
         public static void main(String[] args) {
              AnimationStation cutie = new AnimationStation();
         * The IView inner class
         class IView extends JPanel {
              int x = 0; //x pos
              int y = 0; //w pos
              int d = 0; //diameter
              Color randomColor1; //random color     
              Color randomColor2; // random color
              private boolean imageOn = true; //do we care about the background, or are we looking for that square?
              * Default constructor
              public IView() {
              //wonders... is this neccessary.... ::thinks:: well it works so lets not mess with it
              * Builds our pretty pictures
              public void paintComponent(Graphics g) {
                         g.setColor(Color.white); //make background
                         g.fillRect(0,0,this.getWidth(),this.getHeight()); //background
                   for(int x = 0; x < 10; x++) { //no? draw ovals
                             drawOval(g);
              * Method to make ovals
              *(and apparently a random square, although I think its good luck if you do! So its a feature, not a bug)
              public void drawOval(Graphics g) {
                   d = (int)((Math.random() * 10) + (this.getWidth() / 5)); //set diameter
                   x = (int)(Math.random() * (this.getWidth() - d)); //set x dont let it off the screen
                   y = (int)(Math.random() * (this.getHeight() - d)); //set y dont let it off the screen
                   randomColor1 = randomColor(); //set random color one
                   randomColor2 = randomColor(); //set random color two
                   Graphics2D g2d = (Graphics2D) g; //make a graphics 2d object, helps with gradiants
                   GradientPaint gradient; //make gradiant
                   gradient = new GradientPaint(x, y, randomColor1, x+d, y+d, randomColor2); //set gradiant
                   g2d.setPaint(gradient); //set paint
                   g2d.fillOval(x,y,d,d); //make that oval
              * Method which makes a random color
              public Color randomColor() {
                   Color a = new Color((int)(Math.random() * 255), (int)(Math.random() * 255), (int)(Math.random() * 255));
                   return a;
              * Checks to see if a file is an image file (I REALLY hope this is not how other programs do it,
              *  becuase technically I can make this a graphic "mv ImageViewer.java fake.gif")
              public boolean isImageFile(String filename) {
                   String ending = "" + filename.charAt(filename.length() - 4) + filename.charAt(filename.length() - 3) + filename.charAt(filename.length() - 2) +
                        filename.charAt(filename.length() - 1); //make a string with the last four letters
                   if(ending.equalsIgnoreCase(".jpg") || ending.equalsIgnoreCase(".gif") || ending.equalsIgnoreCase(".bmp")) { //is it an image?
                        return true; //yes
                   } else {
                        return false; //no
    }thanks,
    Bachmann

    well, let me explain some more. Its more of an irritation, then a crippling error....
    The squares are quite clear. I mean, its not like a small circle that looks squareish, I have seen a square appear and it could be larger than the circles that I see.
    It is also very rare, so yeah, it could have something to do with the random aspects.
    It just kinda bothers me since nither me, my classmates, or my professor can figure out why this happens and no one else has mentioned this problem.

  • Drawing state diagrams?

    hello,
    my problem is about drawing state diagrams with java.
    I have a database that stores the states and transitions.
    I want to draw state diagrams with the data in this database.
    I use simple Graphics object to draw. It was a bit successfull.
    However the API of Graphics are not enough for this job (like: drawLine, drawOval etc.)
    For example I can not draw oval lines and I can not associate any string to this lines properly. Or it is very hard to do.
    So,
    Is there any classes to help me while drawing state diagrams or
    any simple way to make this?
    Like using a Tool that will take my database as an input and draw all state diagrams.
    Thanks

    firstly
    thanks for your advices.
    I created my objects. Actually I drawed simple diagrams.
    I used oval for every state. And I decided 4 points on a state to connect another state. (points are obvious). And an algorithm to connect to state with proper points.
    And I drawLine from one oval to another.
    Then I drawString to the connection point of the first state. (for the description of transition like T23).
    This works for simple diagrams,
    but for complex ones it doew not work.
    First problem is when s1->s2 and s2->s1 It only draws 1 line (normally). This problem is not so important.
    Second problem is the labels. When T1 is s1->s2 and T2 is s1->s3 It was confusing one point but two label which one goes to s1? Simply ! can not write label on line.
    So that I look for a present library or algorithms to draw diagrams.

  • Drawing help!!!

    Hi everyone,
    I just needed help with my java drawing program. I have to create a program that will allow user input to choose the demo they want. For example, demo1 will be "draw lines", demo 2 will be "draw oval" and so on.. However, my main problem is, how will i draw 10 lines?? would i use a loop? This is what i have so far and it's been driving me nuts because it only draws one line... i'd like it to offset by 1... but it doesn't seem possible no matter what i do. Also there's a circledemo in there where it requires me to use drawOval to draw the circles and have them in a pattern... the third demo wants me to color them. and the last demo which is a rectangle demo wants me to place any rectangle randomly on the applet... This is what i have so far.
    import javax.swing.JOptionPane;
    import java.awt.*;
    import javax.swing.*;
    import java.applet.*;
    * @author
    * @version
    public class Shapes2 extends JApplet
    String input;
    int choice;
    int lines=10;
    public void init()
    do
    input = JOptionPane.showInputDialog("Enter 1 to draw lines\n" + "Enter 2 to draw rectangles\n" +
    "Enter 3 to draw ovals\n" + "Enter 4 to draw polygons");
    choice = Integer.parseInt(input);
    //paint(Graphics g);
    repaint();
    }while (choice > 4);
    public void paint(Graphics g)
    switch (choice)
    case 1:
    if (choice == 1)
    {lineDemo(g);
    break;}
    case 2:
    if (choice == 2)
    {circleDemo(g);
    break;}
    case 3:
    if (choice == 3)
    {circleDemo2(g);
    break;}
    case 4:
    if (choice == 4)
    {rectDemo(g);
    break;}
    default: break;
    } g.drawString("Please enter 1, 2, 3 or 4", 20, 20);
    private void lineDemo(Graphics g)
    g.drawLine(20,20,280,280); // how do i draw 10 lines here???
    private void circleDemo(Graphics g) // draw circles all over the screen ...using nested for loops
    private void circleDemo2(Graphics g) //color the drawn circles from above
    private void rectDemo(Graphics g) // draw any graphical item on the screen randomly
    Edited by: blackcoda786 on May 23, 2009 9:41 PM
    Edited by: blackcoda786 on May 23, 2009 9:43 PM

    import javax.swing.JOptionPane;
    import java.awt.*;
    import javax.swing.*;
    import java.applet.*;
    * create a shape then have it repeat 100x.
    * @author
    * @version
    public class Shapes2 extends JApplet
        String input;
        int choice;
        int lines=10;
        public void init()
            do
                input = JOptionPane.showInputDialog("Enter 1 to draw lines\n" + "Enter 2 to draw rectangles\n" +
                                      "Enter 3 to draw ovals\n" + "Enter 4 to draw polygons"); 
                choice = Integer.parseInt(input);
                //paint(Graphics g);
                repaint();
            }while (choice > 4); 
    public void paint(Graphics g)
                    switch (choice)
                        case 1:
                            if (choice == 1)
                                    {lineDemo(g);
                                    break;}
                        case 2:
                            if (choice == 2)
                                    {circleDemo(g);
                                    break;}
                        case 3:   
                            if (choice == 3)
                                    {circleDemo2(g);
                                    break;}
                        case 4:
                            if (choice == 4)
                                    {rectDemo(g);
                                    break;}
                            default: break;
                    }       g.drawString("Please enter 1, 2, 3 or 4", 20, 20);
               private void lineDemo(Graphics g)
                   // how do i draw 10 lines here???
                    for(int i=0; i<10; i++)
                     g.drawLine(20,20,280,280)
                private void circleDemo(Graphics g) // draw circles all over the screen ...using nested for loops
                private void circleDemo2(Graphics g) //color the drawn circles from above
                private void rectDemo(Graphics g)  // draw any graphical item on the screen randomly
            }Hi cotton, thanks for your reply, i know how to write a for loop, however im not sure if what i did above is correct... it seems to only create 1 line each time...

  • Something trivial but I can't work it out :/

    Okay basically, I want my buttonOval to draw an oval for me. Here is my code:
    import java.awt.*;                                                  //Import all the classes within the abstract windows toolkit
    import java.applet.*;                                                  /Import applet class
    import java.awt.event.*;
    import java.awt.Graphics.*;
    public class Shapes extends Applet implements ActionListener
         Button buttonOval, buttonRectangle;                              //Declaration of button variables
         Font fontVerdana;                                        //Declare fonts
         TextField textx, texty, textwidth, textheight, areatext;          //Declare text fields
         Label labelx, labely, labelh, labelw;                              //Declare label fields
         int x;                                                       //Declare variable x asinteger v
         int y;
         int height;
         int width;
         int area;
         double pi = 3.14;
         public void init()
              setSize(800,500);                                                       //Size of the applet viewer
              setBackground(Color.yellow);
              fontVerdana = new Font("Verdana", Font.BOLD,10);                //Set the font
              labelx = new Label("Enter in the x co-ordinate here:");          //Declares a new label
              labelx.setBackground(Color.yellow);                                   //Background colour becomes yellow
              labelx.setFont(fontVerdana);                                        //Label prompt uses the Verdana font
              add(labelx);                                                            //Add prompt to the applet
              textx = new TextField(1);                                             //Declares a textfield for input
              add(textx);                                                                 //Adds the textfield to the applet
              textx.setForeground(Color.white);                                   //Textfield font becomes white
              textx.setBackground(Color.black);                                   //Textfield background colour becomes black
              textx.addActionListener(this);
              labely = new Label("Enter in the y co-ordinate here:");
              labely.setBackground(Color.yellow);
              labely.setFont(fontVerdana);
              add(labely);
              texty = new TextField(1);
              add(texty);
              texty.setForeground(Color.white);
              texty.setBackground(Color.black);
              texty.addActionListener(this);
              labelw = new Label("Enter in the width here:");
              labelw.setBackground(Color.yellow);
              labelw.setFont(fontVerdana);
              add(labelw);
              textwidth = new TextField(1);
              add(textwidth);
              textwidth.setForeground(Color.white);
              textwidth.setBackground(Color.black);
              textwidth.addActionListener(this);
              labelh = new Label("Enter in height here:");
              labelh.setBackground(Color.yellow);
              labelh.setFont(fontVerdana);
              add(labelh);
              textheight = new TextField(1);
              add(textheight);
              textheight.setForeground(Color.white);
              textheight.setBackground(Color.black);
              textheight.addActionListener(this);
              areatext = new TextField(20);
              areatext.setEditable(false);
              add(areatext);
              areatext.addActionListener(this);
              buttonOval = new Button("Draw Oval");
              buttonOval.setForeground(Color.white);
              buttonOval.setBackground(Color.black);
              add(buttonOval);
              buttonRectangle = new Button("Draw Rectangle");
              buttonRectangle.setForeground(Color.white);
              buttonRectangle.setBackground(Color.black);
              add(buttonRectangle);
              buttonOval.addActionListener(this);
              buttonRectangle.addActionListener(this);
         public void paint(Graphics g)
              g.drawOval(x, y, width, height);
              g.drawRect(x, y, width, height);
         public void actionPerformed(ActionEvent ev)
              if (ev.getSource() == buttonRectangle)
                   x = Integer.parseInt(textx.getText());
                   y = Integer.parseInt(texty.getText());
                   width = Integer.parseInt(textwidth.getText());
                   height = Integer.parseInt(textheight.getText());
                   area = width * height;
                   areatext.setText("The area is = " + area + "cm�");
                   areatext.setEditable(false);
              else if (ev.getSource() == buttonOval)
                   x = Integer.parseInt(textx.getText());
                   y = Integer.parseInt(texty.getText());
                   width = Integer.parseInt(textwidth.getText());
                   height = Integer.parseInt(textheight.getText());
                   area = width * height;
                   areatext.setText("The area is = " + area + "cm�");
                   areatext.setEditable(false);
    I've used the paint method to set out the oval attributes 'g.drawOval(x, y, width, height' and I've declared all the integers and got the integer results from the textfields in which the integers are entered 'x = Integer.parseInt(textx.getText());'
    but when I click the buttonOval I want it to draw the oval which is defined in the paint method. Any ideas how I can do this? As plus, it would be great if someone could tell me how to implement the area of an oval too. :D
    I do apologise if this sort of thread has been posted before! Thank you for any help I appreciate. :)
    Have a good day,
    Jay

    I've ried to compile the following but no luck...
    Boolean ovalYes, rectYes;
    then in the paint method...
    public void paint(Graphics graf)
              if buttonOval = ovalYes
                   graf.drawOval(x,y,width,height);
              else if buttonRectangle = ovalYes
                   graf.drawRect(x,y,width,height);
    then in the actionPerformed method...
    public void actionPerformed(ActionEvent ev)
              if (ev.getSource() == buttonRectangle)
                   x = Integer.parseInt(textx.getText());
                   y = Integer.parseInt(texty.getText());
                   width = Integer.parseInt(textwidth.getText());
                   height = Integer.parseInt(textheight.getText());
                   repaint(rectYes);
                   area = width * height;
                   areatext.setText("The area is = " + area + "cm�");
                   areatext.setEditable(false);
              else if (ev.getSource() == buttonOval)
                   x = Integer.parseInt(textx.getText());
                   y = Integer.parseInt(texty.getText());
                   width = Integer.parseInt(textwidth.getText());
                   height = Integer.parseInt(textheight.getText());
                   repaint(ovalYes);
                   area = width * height;
                   areatext.setText("The area is = " + area + "cm�");
                   areatext.setEditable(false);
    It doesn't work. :s

  • Creating Gradient-filled shapes via JSFL CS5.5?

    I'm trying to use JSFL to create a number of oval shapes on a layer, that have a gradient fill applied to them.  I've stripped down the JSFL to very bare bones which I will post here:
    var flashDoc = fl.getDocumentDOM();
    var flashLib = flashDoc.library;
    var flashTimeline = flashDoc.getTimeline();
    // Set fill color for all shapes
    var fill = flashDoc.getCustomFill();
    fill.style = "radialGradient";
    fill.color = "#FFFFFF";    // For some reason if I don't assign at least *something* here, the color array doesn't work and I get fully black shapes
    fill.colorArray = ["#0033CC", "#FFFFFF"];
    fill.posArray = [0, 255];
    fill.focalPoint = 0;
    fill.linearRGB = true;
    flashDoc.setCustomFill( fill );
    for( var i = 0; i < 10; ++i )
        var x = Math.random() * 500;
        var y = Math.random() * 400;
        var radius = Math.random() * 25 + 25;
        var left = x - radius;
        var top = y - radius;
        var right = x + radius;
        var bottom = y + radius;
        flashDoc.addNewOval( {left:left, top:top, right:right, bottom:bottom}, false, true );
    When I run this script I do not get the results I'm expecting.  I get a number of oval shapes that all share the same gradient transform, i.e., each shape only gets part of the gradient.  The documentation says this function should be equivalent to using the draw oval tool, yet when you use that tool each oval you draw is associated with its own gradient transform.
    My Questions:
    1. Am I missing a piece here to create shapes each with their own gradient transform?
    2. Is it a bug that I have to set something into fill.color, even though I'm supplying a color array?  If I set nothing there, all the shapes will draw in full black.
    3. Is there a way to specify gradient colors that include alpha?
    Thanks for your time.

    Yep, that made the rest of my whole day!! Works excelllent in the demo, and i'm just replacing all the  Image<->Triangle commands. Wonderfulll & thanks a lot, LitDev. (enjoint the sb sample in your Test-DL :-))
    PS:
    Controls.SetTextBoxText(Controls.AddTextBox(10,10), "Enter your name here...")
    Controls.AddButton(".. then press the Button", 180,10)
    LDGraphicsWindow.Capture("","")
    GraphicsWindow.Clear()
    GraphicsWindow.DrawImage("ImageList1", 0,0)

  • QUICK MAX DUKE DOLLARS!!!

    Project.java is a simple drawing program.
    Modify the program to draw not only circles, but rectangles,
    filled circles, filled rectanges and lines. Modify the program
    so the user can change the color of a shape and clear the
    drawing.
    Use proper object orient techniques in making your modifications.
    There is some code that is in the sample program that could
    be improved. Make any modifications that you feel are necessary
    to improve the code. The code simple shows you how to perform
    the drawing operations.
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    * This is a simply drawing program which lets the user draw basic shapes
    * (lines, ovals and rectangles). This program currently only lets the
    * user draw ovals, and the only color displayed is black.
    * The drawing program uses rubberbanding so that the user can see the
    * shape as they drag it. When the use clicks down on the mouse it
    * sets the starting, or anchor, point for the drawing. When they release
    * the button the shape is drawn. As the user holds down the button and
    * drags the mouse, the shape is constantly displayed.
    public class Project extends Panel
    Panel controlPanel; // Contains for controls to determine shape and color
    ScrollPane drawPane; // A scrollable drawing pane
    Label shapeLabel; // A label for the shape drop down list
    Label colorLabel; // a label for the color drop down list
    Choice shapeChoice; // Drop down list (combbox) for selecting the shape
    Choice colorChoice; // drop down lsit for selecting the color
    Button clearButton; // For clearing the drawing canvas
    Color currentColor = Color.black; // The current color used to draw shapes
    DrawCanvas drawCanvas; // a Canva on which we draw the shapes
    Vector shapes; // A vector to hold all of the shapes
    protected String []shapeTypes = {"circle", "rectangle", "filled circle",
    "filled rectangle", "line" };
    protected String []colors = {"red", "blue", "green", "yellow", "orange",
    "white", "black", "gray", "dark gray", "light gray",
    "cyan", "magenta", "pink"};
    Point anchorPoint; // The anchor point
    Point endPoint; // The point where the mouse was released
    Point stretchPoint; // The point where the user dragged the mouse to
    Point lastPoint; // The previous drag point
    boolean firstTime = true; // first time drawing this shape?
    * Add GUI components
    public Project()
    // GridBagLayout is the most powerful and difficult to
    // use Layout manager
    // The layout manager determines were components are placed on
    // the screen. There is no need to modify it in any way.
    GridBagLayout gbl = new GridBagLayout();
    GridBagConstraints gc = new GridBagConstraints();
    // Create the control panel
    setLayout(gbl);
    controlPanel = new Panel();
    setConstraints(controlPanel, gbl, gc, 0, 0,
    GridBagConstraints.REMAINDER, 1, 0, 0,
    GridBagConstraints.CENTER,
    GridBagConstraints.NONE,
    0, 0, 0, 0);
    add(controlPanel, gc);
    shapeLabel = new Label("Shape"); // The Label for the shape drop down list
    controlPanel.add(shapeLabel);
    shapeChoice = new Choice(); // The dropdown list
    controlPanel.add(shapeChoice);
    colorLabel = new Label("Color"); // The label or the color drop down list
    controlPanel.add(colorLabel);
    colorChoice = new Choice(); // The drop down list
    controlPanel.add(colorChoice);
    clearButton = new Button("Clear"); // the clear button
    controlPanel.add(clearButton); // Doesn't do anything
    // Event handelers
    // Handle the event when the user selects a new shape
    shapeChoice.addItemListener(new ShapeHandler());
    // Event when user selects new color
    colorChoice.addItemListener(new ColorHandler());
    // Event when user click clear button
    clearButton.addActionListener(new ClearHandler());
    //Create the drawing area
    drawPane = new ScrollPane();
    setConstraints(drawPane, gbl, gc, 0, 1,
    GridBagConstraints.REMAINDER, 1, 1, 1,
    GridBagConstraints.CENTER,
    GridBagConstraints.BOTH,
    5, 0, 5, 0);
    add(drawPane, gc);
    drawPane.setSize(300,300);
    drawCanvas = new DrawCanvas(400,400);
    drawPane.add(drawCanvas);
    initShapes(); // initialize the shape choice control
    initColors(); // initialzie the color choice control
    shapes = new Vector();
    // Convenience method for GridBagLayout
    private void setConstraints(
    Component comp,
    GridBagLayout gbl,
    GridBagConstraints gc,
    int gridx,
    int gridy,
    int gridwidth,
    int gridheight,
    int weightx,
    int weighty,
    int anchor,
    int fill,
    int top,
    int left,
    int bottom,
    int right)
    gc.gridx = gridx;
    gc.gridy = gridy;
    gc.gridwidth = gridwidth;
    gc.gridheight = gridheight;
    gc.weightx = weightx;
    gc.weighty = weighty;
    gc.anchor = anchor;
    gc.fill = fill;
    gc.insets = new Insets(top, left, bottom, right);
    gbl.setConstraints(comp, gc);
    // Initialize the shape control
    private void initShapes()
    for(int i = 0; i < shapeTypes.length; i++){
    shapeChoice.add(shapeTypes);
    // Initialzie the color control
    private void initColors()
    for(int i = 0; i < colors.length; i++){
    colorChoice.add(colors);
    * Handle the shape selection
    * This doesn't currently do anything
    public class ShapeHandler implements ItemListener
    public void itemStateChanged(ItemEvent e)
    // Use get index method to get the index of the chosen shape
    // shapeType = shapeChoice.getSelectedItem();
    * Handle the color seclection
    * This doesn't do anything either
    public class ColorHandler implements ItemListener
    public void itemStateChanged(ItemEvent e)
    String color = colorChoice.getSelectedItem();
    System.out.println("Selected color " + color);
    // Handle the clear button
    // This doesn't do anything
    public class ClearHandler implements ActionListener
    public void actionPerformed(ActionEvent e)
    * A canvas to draw on
    public class DrawCanvas extends Component
    int width; // The Width of the Canvas
    int height; // The Height of the Canvas
    /** Create an area to draw on
    *@param width - the width of the drawing area
    *@param height - the height of the drawing area
    public DrawCanvas(int width, int height)
    // Handle mouse press and release events
    addMouseListener(new MouseHandler());
    // handle mouse drag events
    addMouseMotionListener(new MouseDragHandler());
    this.width = width;
    this.height = height;
    * Draw all of the shapes
    * Not very efficient
    public void paint(Graphics g)
    for (Enumeration e = shapes.elements() ; e.hasMoreElements() ;)
    Circle c = (Circle )e.nextElement();
    System.out.println("drawing Circle " + c.toString());
    c.draw(g);
    * Let everyone know what the preferred size of the drawing
    * canvas is
    public Dimension getPreferredSize()
    return new Dimension(width, height);
    * Used with rubberbanding. The way to erase a shape is
    * to draw it again in XOR mode.
    private void eraseLast(Graphics g)
    int x, y;
    int width, height;
    if (anchorPoint == null || lastPoint == null)
    return;
    // The draw methods assume that the width and height are
    // not negative so we do the following caculations to
    // insure that they are not
    if (anchorPoint.x < lastPoint.x)
    x = anchorPoint.x;
    else
    x = lastPoint.x;
    if (anchorPoint.y < lastPoint.y)
    y = anchorPoint.y;
    else
    y = lastPoint.y;
    width = Math.abs(lastPoint.x - anchorPoint.x);
    height = Math.abs(lastPoint.y - anchorPoint.y);
    // Draw the circle (or oval) at the rectagle bounded by
    // the rectange with the upper left hand corner of x,y
    // and with the specified width and height
    g.drawOval(x, y, width, height);
    // To draw a rectable
    //g.drawRect(x, y, width, height);
    // To draw a Filled Oval
    //g.fillOval(x, y, width, height);
    // To draw a Filled Rect
    //g.fillRect(x, y, width, height);
    // To draw a line
    //g.drawLine(anchorPoint.x, anchorPoint.y, lastPoint.x, lastPoint.y);
    * Do the rubber band drawing
    private void drawRubber(Graphics g)
    int x, y;
    int width, height;
    if (anchorPoint.x < stretchPoint.x)
    x = anchorPoint.x;
    else
    x = stretchPoint.x;
    if (anchorPoint.y < stretchPoint.y)
    y = anchorPoint.y;
    else
    y = stretchPoint.y;
    width = Math.abs(stretchPoint.x - anchorPoint.x);
    height = Math.abs(stretchPoint.y - anchorPoint.y);
    g.drawOval(x, y, width, height);
    * Handle the start and end of rubberbanding. At the end
    * draw the final shape
    public class MouseHandler extends MouseAdapter
    // Get the starting point
    public void mousePressed(MouseEvent e)
    anchorPoint = e.getPoint(); // Point where mouse was clickec
    firstTime = true; // The first point
    // Get the end point
    public void mouseReleased(MouseEvent e)
    endPoint = e.getPoint(); // Point where mouse was released
    Graphics g = getGraphics(); // Get the object to draw on
    g.setXORMode(getBackground()); // Set XOR mode
    eraseLast(g); // Erase the previous shape
    // Add the shape to our vector
    //Obviously you will need to do something different here
    shapes.addElement( new Circle(anchorPoint, endPoint, currentColor));
    repaint(); // Repaint the entire drawing
    g.dispose(); // Need to dispose of Graphics objects
    * Handle the rubber banding
    public class MouseDragHandler extends MouseMotionAdapter
    // Every time the mouse is moved while the mouse button is pressed
    public void mouseDragged(MouseEvent e)
    Graphics g = getGraphics();
    g.setXORMode(getBackground());
    stretchPoint = e.getPoint(); // Get the point we just dragged to
    if (firstTime == true)
    firstTime = false; // nothing to erase the first time
    else
    eraseLast(g); // Erase the last drawing
    drawRubber(g); // Draw the new one
    g.dispose(); // Anytime we do a getGraphics we must dispose of it
    lastPoint = stretchPoint; // Set the lastPoint to lastest last point
    * In real program this should extend Shape or implement a Shape
    * interface and it should be in it's own file
    * Note that even though this is called Circle, it is really an oval
    public class Circle
    int x, y; // X and Y cooridinates of bounding rectangle (upper left)
    int width, height; // width and height of bounding rectangle
    Point p2; // opposite corner of bounding retangle
    Color color; // color of circle
    public Circle(Point p1, Point p2, Color color)
    // The width and height cannot be negative.
    // x and y must always be the upper left corner
    if ( p1.x < p2.x)
    x = p1.x;
    else
    x = p2.x;
    if (p1.y < p2.y)
    y = p1.y;
    else
    y = p2.y;
    width = Math.abs( p2.x - p1.x);
    height = Math.abs(p2.y - p1.y);
    this.color = color;
    * This method is called automatically by repaint and whenever the
    * window needs to be redrawn
    public void draw(Graphics g)
    Color c = g.getColor(); // Save the current color
    g.setColor(color); // Set the color to draw the circle
    g.drawOval(x, y, width, height); // draw the circle
    g.setColor(c); // set the color back to what is was before
    * a toString method is a convienent way of
    * displaying the attributes of a class
    public String toString()
    return "Circle " + color + width + height;
    * Main method creates a Frame and adds in our drawing control
    public static void main(String []args)
    // Create the main window
    Frame frame = new Frame();
    // add a listener to close the window properly
    frame.addWindowListener(new WindowAdapter(){
    public void windowClosing(WindowEvent e){
    System.exit(0); // simply exit
    // Create our control
    Project panel = new Project();
    // add it to our window
    frame.add(panel, BorderLayout.CENTER);
    // size our window to 640 by 480 pixels
    frame.setSize(640, 480);
    // display our window
    frame.setVisible(true);
    }

    Sure, I'll do it, no problem... Anything to help a fellow hard working computer science student... I'm just curious what college you attend. Could you tell me? I promise I'll get you the code then.

  • MousePaint help!!!!

    I am currently learning how I can use the mouse paint, though the functions are working perfectly however there is some visible but not opaque "duplicates" of the actions' display (for example - combobox "duplicates" when that combobox is clicked and selected).
    Please help me! I have to get this assignment over as we are to do our own programs that we did not learn before.
    The codings:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.Dimension;
    public class MousePaint extends JPanel implements MouseListener,
    MouseMotionListener {
    private static final int WIDTH = 480, HEIGHT = 450; // set initial size
    private static final int LEFT = 10; // Reference points
    private static final int TOP = 40;
    private static final int BORDER = 30;
    private static final Color lineColor = Color.black; // Outline color
    private final static int
    BLACK = 0,
    RED = 1, // Some constants to make
    GREEN = 2, // the code more readable.
    BLUE = 3, // These numbers code for
    CYAN = 4, // the differnet drawing colors.
    MAGENTA = 5,
    YELLOW = 6,
    PINK = 7;
    private Point mouse = new Point(); // Mouse's current location
    private int shapeWidth = 3; // Drawing Oval width
    private int shapeHeight = 3; // Drawing Oval height
    private Color drawColor = Color.black; // Drawing Oval outline color
    private JPanel controls = new JPanel();
    private GridLayout gridLayout1 = new GridLayout();
    private JLabel jLabel1 = new JLabel();
    private JLabel jLabel2 = new JLabel();
    private String[] widths = {"3", "4", "5", "6", "7", "8", "9", "10", "11", "12",
    "13", "14", "15", "16", "17", "18", "19", "20"};
    private JComboBox dotWidthHeight = new JComboBox(widths);
    private String[] colors = {"Black", "Red", "Green", "Blue", "Cyan", "Magenta",
    "Yellow", "Pink"};
    private JComboBox dotColor = new JComboBox(colors);
    * MousePaint() constructor sets the size of the window and registers
    * the mouse listeners. A MouseMotionListener listens for drag and move
    * events. A MoustListener listens for click events.
    public MousePaint() {
    try {
    jbInit();
    addMouseMotionListener(this); // Add mouse and mouse motion listeners
    addMouseListener(this);
    setSize(WIDTH, HEIGHT); //set the size of the frame
    } catch (Exception ex) {
    ex.printStackTrace();
    } // MousePaint()
    private void jbInit() throws Exception {
    controls.setLayout(gridLayout1); // set the layout of panel
    jLabel1.setText("Dot Size:");
    jLabel2.setText("Dot Color:");
    controls.setEnabled(true);
    controls.setPreferredSize(new Dimension(396, 20));
    dotWidthHeight.addActionListener(new MousePaint_dotWidth_actionAdapter(this));
    dotColor.addActionListener(new MousePaint_dotColor_actionAdapter(this));
    controls.add(jLabel1); // Add label
    controls.add(dotWidthHeight);
    controls.add(jLabel2); // Add label
    controls.add(dotColor);
    this.add(controls);
    * paintComponent() paints the component each time it is invoked. It must
    * distinguish whether the mouse is in the top-left corner of the window,
    * in which case it clears the window, or whether the user is drawing.
    public void paintComponent(Graphics g) {
    Dimension d = getSize();
    g.setColor(lineColor);
    g.fillRect(0, 0, LEFT, TOP); // The clear rectangle
    g.drawRect(LEFT, TOP, d.width - BORDER, d.height - BORDER - 30); // The drawing area
    g.drawString("Drag to draw. Click top left corner to clear.", LEFT,
    d.height - 5);
    g.setColor(drawColor); // Set drawing color
    //If the mouse is within the drawing area, draw a dot
    if ((mouse.x > LEFT) && (mouse.x < LEFT + d.width - BORDER)
    && (mouse.y > TOP) && (mouse.y < TOP + d.height - BORDER - 30)) {
    g.fillOval(mouse.x, mouse.y, shapeWidth, shapeHeight); //display the height and width of the dotted drawing oval
    // If the mouse is clicked at top left corner clear the drawing
    if ((mouse.x < LEFT) && (mouse.y < TOP)) {
    g.clearRect(LEFT + 1, TOP + 1, d.width - BORDER - 1,
    d.height - BORDER - 30 - 1);
    } // paintComponent()
    /* Mouse Handling Interfaces: MouseMotionListener and MouseListener */
    * mouseDragged() handles the mouse drag event. In this case it merely
    * gets the mouse's location and repaints the window.
    public void mouseDragged(MouseEvent e) { // When the mouse is dragged (mouse motion listener)
    mouse = e.getPoint(); // get its coordinates
    repaint();
    * mouseClick() handles mouse click events. In this case it just
    * gets the mouse's location and repaints the window.
    public void mouseClicked(MouseEvent e) { // When mouse is clicked (mouse listener)
    mouse = e.getPoint(); // get its coordinates
    repaint();
    public void mouseEntered(MouseEvent e) {} // These five interface methods are not used
    public void mouseExited(MouseEvent e) {} // but must be defined.
    public void mousePressed(MouseEvent e) {}
    public void mouseReleased(MouseEvent e) {}
    public void mouseMoved(MouseEvent e) {}
    * main() creates a top-level window and gives it a drawing panel.
    public static void main(String args[]) {
    JFrame fr = new JFrame(); // Create the top-level window
    fr.setTitle("Drawing Window");
    MousePaint mpaint = new MousePaint(); // And give it a drawing panel
    fr.getContentPane().add(mpaint);
    fr.setSize(WIDTH, HEIGHT);
    fr.setVisible(true);
    fr.addWindowListener(new WindowAdapter() { // Quit the application
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    } // main()
    public void dotWidth_actionPerformed(ActionEvent e) {
    shapeWidth = (int) dotWidthHeight.getSelectedIndex() + 3; // set the width of drawing dot
    shapeHeight = (int) dotWidthHeight.getSelectedIndex() + 3; // set the height of drawing dot
    public void dotColor_actionPerformed(ActionEvent e) {
    int colornum = dotColor.getSelectedIndex();
    switch (colornum) {
    case BLACK:
    drawColor = Color.black;
    break;
    case RED:
    drawColor = Color.red;
    break;
    case GREEN:
    drawColor = Color.green;
    break;
    case BLUE:
    drawColor = Color.blue;
    break;
    case CYAN:
    drawColor = Color.cyan;
    break;
    case MAGENTA:
    drawColor = Color.magenta;
    break;
    case YELLOW:
    drawColor = Color.yellow;
    break;
    case PINK:
    drawColor = Color.pink;
    break;
    } // MousePaint
    class MousePaint_dotColor_actionAdapter implements ActionListener {
    private MousePaint adaptee;
    MousePaint_dotColor_actionAdapter(MousePaint adaptee) {
    this.adaptee = adaptee;
    public void actionPerformed(ActionEvent e) {
    adaptee.dotColor_actionPerformed(e);
    class MousePaint_dotWidth_actionAdapter implements ActionListener {
    private MousePaint adaptee;
    MousePaint_dotWidth_actionAdapter(MousePaint adaptee) {
    this.adaptee = adaptee;
    public void actionPerformed(ActionEvent e) {
    adaptee.dotWidth_actionPerformed(e);
    }

    Your paintComponent() only paints the last recorded
    mouse position, but it does not
    clear the screen. The result is that a picture gets
    built up based on how the user
    clicks and drags the mouse.
    When a combo box item is selected the last recorded
    mouse position changes
    colour or size. Of course the area under where the
    combo box pops up gets cleared
    and any mouse dots that it used to contain disappear,
    but, other than that, I can't
    see any strange artifacts when using the combo boxes.As you mentioned that, when a combo box item is selected, the area under the combo box pops up gets cleared. My side is different from yours. The mouse dots will still remain in the drawing panel but the combo boxes and its item areas will be on the drawing panel when they should not be there. Is there any solutions to that?
    My intention of doing this program is to ensure that the drawing panel can accept different colors and shapes.
    Thank you very much, Dennis

  • Applet content disappears

    Whenever I make applets. As soon as I minimize the applet or resize it or move any other window over the applet...the content of the applet disappears. can someone please tell me how to get rid of it and how to retain the contents of the applet even after it is minimized or resized. Thanks :)

    I am an absolute beginner. I made the following code.
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    <applet code ='Scribble.java' width=300 height =300>
    </applet>
    public class Scribble extends Applet
    implements MouseListener,ActionListener, MouseMotionListener,ItemListener
    Choice shape;
    String msg="";
    int last_x = 0;
    int last_y = 0;
    int clickx=0,clicky=0;
    public void init()
    shape = new Choice();
    shape.add("Line");
    shape.add("FreeHand");
    shape.add("Oval");
    shape.select("FreeHand");
    shape.addItemListener(this);
    add(shape);
    Button clear = new Button("clear");
    add(clear);
    addMouseListener(this);
    addMouseMotionListener(this);
    clear.addActionListener(this);
    public void paint(Graphics g)
    g.drawString(msg,30,40);
        public void mousePressed(MouseEvent me)
         last_x=me.getX();
         last_y=me.getY();
         clickx=me.getX();
         clicky=me.getY();
         public void mouseEntered(MouseEvent me)
         public void mouseExited(MouseEvent me)
         public void mouseReleased(MouseEvent me)
         public void mouseClicked(MouseEvent me)
         public void mouseMoved(MouseEvent me)
         public void mouseDragged(MouseEvent me)
         //For drawing Freehand
         if(shape.getSelectedItem().equals("FreeHand"))
         Graphics g = getGraphics();
         g.drawLine(last_x,last_y,me.getX(),me.getY());
         last_x = me.getX();
            last_y = me.getY();
         //For Drawing Line
         if(shape.getSelectedItem().equals("Line"))
         Graphics g = getGraphics();
         g.setColor(Color.white);
         g.drawLine(clickx,clicky,last_x,last_y);
         g.setColor(Color.red);
            g.drawLine(clickx,clicky,me.getX(),me.getY());
         last_x = me.getX();
            last_y = me.getY();
         //For Drawing Oval
         if(shape.getSelectedItem().equals("Oval"))
         Graphics g = getGraphics();
         g.setColor(Color.white);
         g.drawOval(clickx,clicky,last_x-clickx,last_y-clicky);
         g.setColor(Color.red);
            g.drawOval(clickx,clicky,me.getX()-clickx,me.getY()-clicky);
         last_x = me.getX();
            last_y = me.getY();
              /*For Button*/
         public void actionPerformed(ActionEvent ae)
         String str=ae.getActionCommand();
         if(str.equals("clear"))
         repaint();
         public void itemStateChanged(ItemEvent ie)
    }I've got loads of doubts with this.
    1. The applet content disappears when I resize/minimize it.
    2. I've tried to do it the MSpaint/Photoshop way. Where if you are drawing a Line/Shape then while the mouse is dragged ..the user gets an idea as to what is being drawn. So for that..for every new pixel position the mouse is dragged to, I've redrawn the previous shape in WHITE color. But then that gives me a problem that if a previous shape was already drawn at that position. It gets erased too. So I would like to rectify that too.
    3. I Don't know how to use getGraphics to the fullest. [Guide me to a tutorial?]
    Thanks.
    Edited by: axl.r0se on Mar 28, 2010 1:04 AM

  • How to create magnification effect around the mouse.

    Hi everybody,
    I have a problem which really freaks me out at the moment. I am working on an image sorting software and I try to implement a magnification glass. The problem seems to be easy: Create the Region OF Interest, "zoom" in ,display result at the MousePosition. I got it so far:
    bimage is a BufferedImage
                            Graphics2D gi = bimage.createGraphics();
                            gi.setClip(0, 0, bimage.getWidth(), bimage.getHeight());
                   gi.drawImage(bimage, 0, 0, null);
                   //paints red rectangle around mouse position
                   gi.setColor(Color.blue);
                   gi.draw(new Rectangle(mousePosX-100, mousePosY-100, 200, 200));
                   Rectangle zoomRect = new Rectangle(mousePosX-100, mousePosY-100, 200,     200);
                   gi.setClip(zoomRect);
                   gi.copyArea(mousePosX-100, mousePosY-100, 200,     200, 0, 0);
                   gi.scale(1.1, 1.1);
                   gi.translate(-20, -20);
                   gi.drawImage(bimage, 0, 0, null);What happens is, that as soon as I translate it to the right position, the copy area copy's the scaled copy and so on. It looks horrible. Does anyone knows how to make it better?
    Thx in advance.

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.BufferedImage;
    import javax.swing.*;
    public class Magnifier extends JPanel implements ActionListener {
        OverlayComponent overlayComponent;
        public void actionPerformed(ActionEvent e) {
            boolean magnify = ((AbstractButton)e.getSource()).isSelected();
            overlayComponent.setMagnify(magnify);
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            int cols = 3, rows = 3, pad = 20;
            int w = getWidth(), h = getHeight();
            double dx = (double)(w - 2*pad)/cols;
            double dy = (double)(h - 2*pad)/rows;
            // Draw ovals.
            Color[] colors = {
                Color.cyan, Color.magenta, Color.yellow, Color.orange
            for(int j = 0, count = 0; j < rows; j++) {
                double y = pad + j*dy;
                for(int k = 0; k < cols; k++) {
                    double x = pad + k*dx;
                    int index = j*cols + k;
                    Color color = (index % 2 == 0) ? Color.blue
                                                   : colors[count++];
                    if(count > 3) count = 0;
                    g2.setPaint(color);
                    g2.fill(new Ellipse2D.Double(x, y, dx, dy));
            // Draw grid.
            g2.setPaint(Color.red);
            for(int j = 0; j <= rows; j++) {
                double y = pad + j*dy;
                g2.draw(new Line2D.Double(pad, y, w-pad, y));
            for(int j = 0; j <= cols; j++) {
                double x = pad + j*dx;
                g2.draw(new Line2D.Double(x, pad, x, h-pad));
        private JPanel getContent() {
            overlayComponent = new OverlayComponent(this);
            JPanel panel = new JPanel();
            OverlayLayout overlay = new OverlayLayout(panel);
            panel.setLayout(overlay);
            panel.add(overlayComponent);
            panel.add(this);
            return panel;
        private JPanel getLastPanel() {
            JCheckBox checkBox = new JCheckBox("magnify", true);
            checkBox.addActionListener(this);
            JPanel panel = new JPanel();
            panel.add(checkBox);
            return panel;
        public static void main(String[] args) {
            Magnifier test = new Magnifier();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(test.getContent());
            f.getContentPane().add(test.getLastPanel(), "Last");
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
    class OverlayComponent extends JComponent {
        Magnifier component;
        BufferedImage image;
        Point loc;
        boolean magnify = true;
        OverlayComponent(Magnifier m) {
            component = m;
            addMouseMotionListener(mma);
        public void setMagnify(boolean magnify) {
            this.magnify = magnify;
            repaint();
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            if(magnify) {
                if(image == null) {
                    int type = BufferedImage.TYPE_INT_RGB;
                    image = new BufferedImage(200, 200, type);
                    updateImage(new Point(getWidth()/2, getHeight()/2));
                int x = loc.x - image.getWidth()/2;
                int y = loc.y - image.getHeight()/2;
                g.drawImage(image, x, y, this);
        private void updateImage(Point p) {
            loc = p;
            Graphics2D g2 = image.createGraphics();
            g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                                RenderingHints.VALUE_INTERPOLATION_BICUBIC);
            double scale = 1.25;
            int x = (int)(scale*p.x) - image.getWidth()/2;
            int y = (int)(scale*p.y) - image.getHeight()/2;
            g2.translate(-x, -y);
            g2.scale(scale, scale);
            component.paint(g2);
            g2.dispose();
        private MouseMotionAdapter mma = new MouseMotionAdapter() {
            public void mouseMoved(MouseEvent e) {
                if(magnify) {
                    updateImage(e.getPoint());
                    repaint();
    }

  • Why can't I programmatically align a picture to a graph?

    Labview 7.0; Mac or PC
    OK, so it sounds like a simple problem, right:
    - bottom line: I want a graphical plane (picture with transparent
    background) overlaid on an intensity vs XY data set (Intensity graph).
    And I want the two image planes to overlay properly, so I want to do
    the alignment programmatically (draw/plot areas of picture and
    intensity graphs to be the same size and in the same location).
    Here is the problem that I run into:
    - summary: Some of the (important) property node positional and size
    attributes of the intensity graph return strange values that therefore
    can not be used as input to positional properties of the picture.
    OK, more specifically, what I tried and saw:
    - create a picure, of any size, on a front panel. Make the background transparent, and make the label not-visible
    - create an intensity graph, of any size, on a front panel. Make the label not-visible.
    - make a property node for the intensity graph and another one for the picture
    - set the draw area of the picture = plot area of the intensity graph.
    OK, that was easy, and works fine (you can manually align the two to
    see that this works, but then mis-align the two to continue)
    - note that there is no property to identify the origin of the plot area of the intensity graph directly.
    - Hmmmm, maybe the scale marker bounds on the graph can be used to
    (somewhat closely,but maybe not exactly) identify the origin of plot
    area of the graph...
    - set the position>left property of the picture = X scale>marker>position>left
    - set the position>top property of the picture = Y scale>marker>position>top
    - IT WON"T BE ANYWHERE even close (the alignment is way off)
    It gets better:
    - on the front panel, move the graph up maybe 50 pixels, and to the right about 50 pixels
    - run the vi again and see that the picture moves to the right as expected, but has not moved up at all
    There's more, but I don't want to complicate the picture any more. I'll
    just summarize by saying that it appears that some of the intensity
    graph-components position/size properties change in value based on the
    number or types of properties requested.
    I haven't tried aligning the graph to the picture instead, but I'm
    guessing that I'm missing something stupidly simple in this example,
    and someone can help to restore my sanity.
    Thanks, in advance

    altenbach,
    Thanks for the reply. Sorry, I didn't realize how easy it is to attach
    a vi. OK, attached is the simple vi. I made the vi even simpler... it
    matches my text more exactly. Interestingly, the result is a little
    different: now, if you move the graph and rerun the picture moves
    accordingly... but still, the picture is not positioned as I'd expect.
    Also, thanks for note about scale changes (and associated plot area
    size changes)... I had thought of that, but hadn't figured out yet if
    it was going to be an issue for my application; and if so, how I'd deal
    with it.
    I'm not quite ready to upgrade all the existing code to Labview 8 -
    much of the code is fielded to customers so there is a business aspect
    to work out. But, I'm looking forward to starting to experiment with
    Labview 8.
    I'm not sure I appreciated your "image indicator" idea. Maybe you mean
    use either a picture for both graph and picture; or use graph for both
    graph and picture. This is not a bad idea based on other aspects of the
    application that I ran into. I wanted a picture to make use of the draw
    tools. But, I need to draw ovals and rectangles; rotate and pan them
    individually and as a group. I found that I had to build the oval and
    rectangle shapes (out of line segments) my self in order to get the
    rotation function. So, if I'm just using line segments (that I define)
    to build arbitrarily rotated ovals and rectangles, I could use an XY
    graph and get zoom and pan for free (so to speak).
    Thanks
    Attachments:
    overlay position test.vi ‏21 KB

  • Visa issues

    Hello,
    i have a vi that has 25 'draw oval's' in the bolck diagram , this is interfaced with a microcontroller via RS232. The microcontroller is sending data continiousl. when I run the VI There is a big delay in reception by thhe draw oval vi's . WHen I used the same vi but with simple booleans (Leds) instead iof draw oval it works fine. All I am trying to do is read three bytes of data , creat an image (any format) and then save them in a directory. Attached is the VI (downconverted to 2012v) that I am having problems in when run through VISA. ANy help will be appreciated.
    Regards
    Attachments:
    imagegen - Copy.vi ‏52 KB

    naserkhan wrote:
    thanksf for your reply. by 2nd while loop do you mean Producer/consumer technique? If yes then Can u give me some key tips to work on it.
    Greatlyappreciate your concern
    Producer/Consumer
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines

  • Error display

    the following code is an applett which allows the user to choose which shape they wish to view which works perfectly, the problem i am having is when the user enters a incorrect number (outside of 1-4) my error display ("Please enter 1, 2, 3 or 4", 20, 20); doesnt appear. if a number abve 4 is entered the original screen shows aain with nothing in the applet and then when a correct number is entered it shows the error message as well as the object, when 0 is entered it shows the error message but doesnt return to original screen to allow correct number to be entered.
    please help.
    import javax.swing.JOptionPane;
    import java.awt.*;
    import javax.swing.*;
    import java.applet.*;
    * create a shape then have it repeat 100x.
    * @author (Simon Orazi)
    * @version (26/05/07)
    public class Workshop11 extends JApplet
        String input;
        int choice;
        public void init()
            do
                input = JOptionPane.showInputDialog("Enter 1 to draw lines\n" + "Enter 2 to draw rectangles\n" +
                                      "Enter 3 to draw ovals\n" + "Enter 4 to draw polygons"); 
                choice = Integer.parseInt(input);
                //paint(Graphics g);
                repaint();
            }while (choice > 4);  
        public void paint(Graphics g)
            switch (choice)
                case 1:
                    if (choice == 1)
                    drawLine(g);
                    break;
                case 2:
                    if (choice == 2)
                    drawRectangle(g);
                    break;
                case 3:   
                    if (choice == 3)
                    drawOval(g);
                    break;
                case 4:
                    if (choice == 4)
                    drawPolygon(g);
                    break;
                default:
            }        g.drawString("Please enter 1, 2, 3 or 4", 20, 20);
        public void drawLine(Graphics g)
            for(choice=0; choice<100; choice++){g.drawLine(20+2*choice, 20+2*choice, 40+2*choice, 280+2*choice);}
        public void drawRectangle(Graphics g)
            for(choice=0; choice<100; choice++){g.drawRect(20+choice*2, 20+choice, 80+choice, 80);repaint();}
        public void drawOval(Graphics g)
            for(choice=0; choice<100; choice++){g.drawOval(20+2*choice, 20+2*choice, 12+2*choice, 75+2*choice);}
        public void drawPolygon(Graphics g)
            for(choice=0; choice<100; choice++)
                int[] xCoords = {60+2*choice, 100+2*choice, 140+2*choice, 140+2*choice,
                                 100+2*choice, 60+2*choice, 20+2*choice, 20+2*choice};
                int[] yCoords = {20+2*choice, 20+2*choice, 60+2*choice, 100+2*choice,
                                140+2*choice, 140+2*choice, 100+2*choice, 60+2*choice};
                g.drawPolygon(xCoords, yCoords, 8);
                repaint();
    }

    There are a number of problems here.
    1) If this line in init fails
    choice = Integer.parseInt(input);Which would happen if you put in a letter for example. Then it all bombs out. I'm a bit surprised that compiles actually... if it does.
    2) This
    while (choice > 4); Doesn't seem to be what you want to do.
    3) Init is called once when the applet is initialized (that's what init means). So you don't want code that you want to repeat in there.
    4) This
    switch (choice)
                case 1:
                    if (choice == 1)the if is redundant. I don't know what that's supposed to do. You have it repeating for the other ones as well. get rid of the if's that's what the switch is for.

  • Making clickable hex grids

    I try to implement MouseListener by using
    public class HexBoard extends Frame implements MouseListenerbut the error message says I need to define the class as a abstract class. After trying that, i still get a error message in main says my class constructor is wrong. can anyone here help me please
    import java.awt.*;
    import java.awt.event.*;
    public class HexBoard extends Frame {
        public static int board_size = 7;
        public static int width = 980;
        public static int height = 600;
        private static int cellSize = width / (board_size + 20);
        public static int radius = (cellSize + cellSize / 4) / 2;
        public static int center_x = width / 2 - radius / 4;
        public static int center_y = (height - radius) / 2;
        public static double[][] grids;
        public HexBoard() {
            grid();
            this.setSize(980, 600);
            this.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
        public void init() {
            grid();
        //addMouseListener(this);
        private void drawNeck(Graphics g, double x, double y, double r, int n, boolean filled) {
            Polygon p = new Polygon();
            for (int i = 0; i < n; i++) {
                p.addPoint((int) (x + r * Math.cos(i * 2 * Math.PI / n)),
                        (int) (y + r * Math.sin(i * 2 * Math.PI / n)));
            if (filled == true) {
                g.fillPolygon(p);
            } else {
                g.drawPolygon(p);
    //Draws a n-Eck polygon with the given parameter
        public void drawNeck(Graphics g, double x, double y, double r, int n) {
            drawNeck(g, x, y, r, n, false);
    //Draws a filled n-Eck polygon with the given parameter
        public void fillNeck(Graphics g, double x, double y, double r, int n) {
            drawNeck(g, x, y, r, n, true);
        //Draws oval
        public void draw_oval(Graphics g, double x, double y) {
            x = x - radius * Math.sqrt(2) * 0.5;
            y = y - radius * Math.sqrt(2) * 0.5;
            int x_value = (int) x;
            int y_value = (int) y;
            double r = radius * 1.5;
            int rr = (int) r;
            g.drawOval(x_value, y_value, rr, rr);
        //Draws oval
        public void draw_filloval(Graphics g, double x, double y) {
            x = x - radius * Math.sqrt(2) * 0.5;
            y = y - radius * Math.sqrt(2) * 0.5;
            int x_value = (int) x;
            int y_value = (int) y;
            double r = radius * 1.5;
            int rr = (int) r;
            g.fillOval(x_value, y_value, rr, rr);
    //here the paint method which needs to be modificated
        public void paint(Graphics g) {
            for (int i = 0; i < board_size * board_size; i++) {
                //draw_oval(g, grids[0], grids[i][1]);
    //draw_filloval(g, grids[i][0], grids[i][1]);
    drawNeck(g, grids[i][0], grids[i][1], radius, 6);
    // find the center of hexagon grids
    public void grid() {
    int count = 0;
    grids = new double[board_size * board_size][2];
    grids[0][1] = center_y;
    if (board_size % 2 != 0) {
    grids[0][0] = center_x - radius * (board_size + num_odd(board_size) - 1);
    } else if (board_size % 2 == 0) {
    System.out.printf("even");
    grids[0][0] = center_x - radius * (board_size + num_even(board_size) - 1) + radius / 2;
    for (int i = 1; i < board_size * board_size; i++) {
    count = count + 1;
    if (count == board_size) {
    count = 0;
    grids[i][0] = grids[i - board_size][0] + radius + radius / 2;
    grids[i][1] = grids[i - board_size][1] - radius * Math.sqrt(3) * 0.5;
    } else {
    grids[i][0] = grids[i - 1][0] + radius + radius / 2;
    grids[i][1] = grids[i - 1][1] + radius * Math.sqrt(3) * 0.5;
    // finds the number of odd numbers smaller than a bigger odd number
    public static int num_odd(int size) {
    int[] temp = new int[board_size];
    int num_odd = 0;
    int count = 0;
    for (int i = 0; i < size; i++) {
    temp[i] = count;
    if (temp[i] % 2 != 0) {
    num_odd = num_odd + 1;
    count = count + 1;
    return num_odd;
    // finds the number of even numbers smaller than a bigger even number
    public static int num_even(int size) {
    int[] temp = new int[board_size];
    int num_even = 0;
    int count = 0;
    for (int i = 0; i < size; i++) {
    temp[i] = count;
    if (temp[i] % 2 == 0) {
    num_even = num_even + 1;
    count = count + 1;
    System.out.printf("dd " + num_even);
    return num_even;
    public void changeSize(int size) {
    board_size = size;
    repaint();
    public void mouseReleased(MouseEvent e) {
    public static void main(String args[]) {
    HexBoard hex = new HexBoard();
    hex.setSize(width, height);
    hex.setVisible(true);
    }Edited by: gamewell on Apr 22, 2008 12:16 PM
    Edited by: gamewell on Apr 22, 2008 12:17 PM
    Edited by: gamewell on Apr 22, 2008 12:18 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    well, i didn't build the tile marix in the end. Instead, I calculated Euclidean distance between the hex grids center and a mouse Cursor point using nearest neighebor algorithm.
        public int CursorToGrid (int x, int y) {
            int grid_index = -1;
            double temp = Integer.MAX_VALUE;
            double distance[] = new double [board_size*board_size];
            // find the nearst neighbor using Euclidean distance
            for (int i = 0; i < board_size * board_size; i++) {
                distance[i] = Math.sqrt(Math.pow(grids[0]-x,2)+Math.pow(grids[i][1]-y,2));
    System.out.println(distance[i]);
    if (distance[i] < temp) {
    temp = distance[i];
    grid_index = i;
    // check if a click outsite the hex map
    if ( distance[grid_index] > radius) {
    grid_index = 10000;
    System.out.println("the grid " + grid_index);
    return grid_index;
    works:D                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

Maybe you are looking for

  • Regarding Condition record in CRM using field MATKL (Material Group)

    Hi All Currently we are working in SAP CRM 5.2 and it has been connected with backend ECC 6.0. This scenario is about Pricing which has been maintained in ECC and inturn flows to CRM with few filters in place. There are few customized Condition Table

  • HT201386 Why can't I add a title to a photo anymore?

    Why can't I add a title to a photo anymore in Iphoto editing? Thanks, Lpkaufman

  • LE_SHP_TAB_CUST_OVER

    Is there anyone ever implemented BAdI LE_SHP_TAB_CUST_OVER to enhance inbound delivery transaction..? I have implemented the BAdI and got some problem. I have created a TAB in VL02n, and I am also able to show the values in the table control in the n

  • Centro (verizon) goes straight to VM after on standby for many hours

    hi all.  my verizon centro has worked flawlesly for a year.  i did drop it a week ago but i don't think this started happening at the same time. every morning when i wake up, calls to my phone go straight to voicemail.  i can't quite figure it out. 

  • No Printer Job List and No AutoQuit

    I have a Canon i70 printer. When I print a document the Canon i70 application automatically opens on my computer. However, when the job finishes, the application does not automatically quit as it used to in previous versions of OS X. The other proble