A polygon button ?

Ok, i've created a polygon which is an extension of a Component.
When the polygon is clicked it needs to repaint but the background colour will have changed.
The problem is it doesnt seem to register my clicking of the polygon and the result is nothing happens.
Here is my code for the clicking and creation of the MouseListener...
import java.awt.*;
import java.lang.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
class MakeWindow extends Frame implements MouseListener
private AnswerBox answerBoxes [] = new AnswerBox [4];
public MakeWindow ()
super ("Who Wants To Be A Billionaire");
setLayout (null);
// Create the menu items.               **** Menu Items are created, i've just left them out here.
setBackground (Color.blue);
setVisible (true);
pack ();
show ();
} // MakeWindow constructor
// Creates windows for Money Ladder and Answer Boxes
public void paint (Graphics g)
answerBoxes [0] = new AnswerBox ('A');
answerBoxes [0].setText ("A: ");
answerBoxes [0].paint (g);
answerBoxes [0].addMouseListener (this);
public void mouseClicked (MouseEvent e)
Object src = e.getSource ();
if (src == answerBoxes [0])
answerBoxes [0].setSelected (true, 'A');
The code for my AnswerBox goes as follows......
import java.awt.*;
import java.lang.*;
public class AnswerBox extends Component
private String text;
private Color backColor;
private char Box;
public AnswerBox (char currBox)
super ();
text = "";
backColor = Color.black;
Box = currBox;
public void paint (Graphics g)
int xChange;
int yChange;
switch (Box)
case 'A':
xChange = 0;
yChange = 0;
break;
default:
xChange = 0;
yChange = 0;
break;
int xPoints [] = {140 + (xChange * 285), 120 + (xChange * 285), 140 + (xChange * 285), 290 + (xChange * 285), 310 + (xChange * 285), 290 + (xChange * 285) };
int yPoints [] = {380 + (yChange * 70), 400 + (yChange * 70), 420 + (yChange * 70), 420 + (yChange * 70), 400 + (yChange * 70), 380 + (yChange * 70) };
g.setColor (backColor);
g.fillPolygon (xPoints, yPoints, 6);
g.setColor (Color.white);
g.drawPolygon (xPoints, yPoints, 6);
g.drawString (text, 150 + (xChange * 285), 405 + (yChange * 70));
public void setText (String newText)
text = newText;
public void setSelected (boolean b, char currBox)
if (b)
backColor = Color.orange;
Box = currBox;
this.repaint ();
else
backColor = Color.black;
Box = currBox;
this.repaint ();
Here is the application code...
import java.awt.*;
import BuildCanvas.*;
public class User
public static void main (String [] args)
MakeWindow userInterface = new MakeWindow ();
userInterface.setSize (800, 600);
userInterface.setLocation (100, 100);
If someone could work through this it would be greatly appreciated, i dont have much programming experience so the problem is probably somehting very stupid.
Thanks
Andrew.

I never done a custom component before and, since I was a little bored this afternoon, I tried. Here is my result, feel free to use some of its code... Of course, it is not perfect, I was just fooling around!
To use it:
CircleButton cb = new CircleButton("Button 1");
cb.addActionListener(/*your action listener here*/);Enough blah, blah, here's the code...
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
public class CircleButton extends Component implements MouseListener {
   // Instance variables
   ActionListener actionListener;
   Color borderColor;
   Color foregroundColor;
   Color backgroundColor;
   Color originalBackgroundColor;
   String text;
   String actionCommand;
   Dimension preferredSize;
   // Constructors
   public CircleButton(String text) {
      super();
      this.text = text;
      borderColor = Color.black;
      foregroundColor = Color.black;
      backgroundColor = Color.white;
      originalBackgroundColor = backgroundColor;
      actionCommand = this.text;
      Font buttonFont = new Font("SansSerif",Font.BOLD,12);
      FontMetrics textMetrics = getFontMetrics(buttonFont);    
      int textWidth  = textMetrics.stringWidth(this.text);
      preferredSize = new Dimension(Math.max(30,textWidth + 10), Math.max(30, textWidth + 10));
      this.addMouseListener(this);
   public void paint(Graphics g) {
      Graphics2D g2 = (Graphics2D) g;
      g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); // For text antialiasing
      g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // For general antialiasing
      Color originalColor = g.getColor();
      int dim = Math.min(this.getWidth(), this.getHeight()) - 4;
      int horizontalOffset = Math.max(0, this.getWidth() / 2 - dim / 2);
      int verticalOffset = Math.max(0, this.getHeight() / 2 - dim / 2);
      g2.setPaint(new GradientPaint(0, dim, Color.red, dim, 0, Color.white, false));     
      g2.fillOval(horizontalOffset, verticalOffset, dim, dim);
      g2.setColor(borderColor);
      g2.drawOval(horizontalOffset, verticalOffset, dim, dim);
      Font buttonFont = new Font("SansSerif",Font.BOLD,12);
      FontMetrics textMetrics = getFontMetrics(buttonFont);    
      int textWidth  = textMetrics.stringWidth(this.text);
      int textHeight = textMetrics.getAscent();
      g2.setColor(foregroundColor);
      g2.drawString(text, this.getWidth() / 2 - textWidth / 2, this.getHeight() / 2 + textHeight / 2);
      g2.setColor(originalColor);
   public void addActionListener(ActionListener actionListener) {
      this.actionListener = actionListener;
   public Dimension getPreferredSize() {
      return preferredSize;
   public void setPreferredSize(Dimension newSize) {
       preferredSize = newSize;
   public Dimension getMinimumSize() {
      return getPreferredSize();
   // Implementation of MouseListener
   public void mousePressed(MouseEvent e) {}
   public void mouseReleased(MouseEvent e) {}
   public void mouseClicked(MouseEvent e) {
      actionListener.actionPerformed(new ActionEvent(this, 0, actionCommand));
   public void mouseEntered(MouseEvent e) {}
   public void mouseExited(MouseEvent e) {}
}

Similar Messages

  • Adding actionListener to a button

    pls i want to create an applet with buttons rectangle,circle,and polygon and having a textArea.when someone clicks on the rectangle buttons it draws a rectangle,on the circle buttons it draws a circle and on the polygon button it draws a polygon.pls i have already created the user interface how do i add the actionListeners to the respective buttons and reggister them.

    Hi,
    try something like this:
    JButton jButton1 = new JButton("yourbutton");
    jButton1.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent evt) {
                    someMethodThatDoesWhatYouNeed();
    });this is just a way to do it, there are other ways, just look around in the forum to discover them.
    JoY?TiCk

  • Windows on Retina display shows up icons too small

    Hi. I've recently installed bootcamp because I have to use a software that is specifically for Windows (Autodesk 3ds Max, pictured). When I tried to use the actual program, I find that the icons and the contents are displayed according to Apple's spectacular retina display. Yes, I love high resolution, but in this size... I can't really make out what they say nor click them accurately if I'm looking from a distance. Anyone knows how to make these icons and text bigger?

    that doesn't work. Boot camp works so that normally other icons and texts are big enough to be seen from afar. As you can see, the menu bar and the tool bar got changed to appropriate sizes. But other buttons (the polygon buttons on the left and content on the right. Not to mention the timeline bar below) did not get that increase. Though this is specific to an autodesk product, I think this question belongs more here, as it is about compatibility of applications on bootcamp

  • Interactive polygon-shaped buttons for web

    Hello everyone,
    I am a new enthusiastic subscriber of CC, and as every newcomer I have several questions. I will limit myself though to only one issue for now. Here is a link for an interactive architectural presentation I did:
    http://www.transsilta.com/ncc/auringonkeha/auringonkeha.html
    This file works nicely but has been built in Flash, and that's make impossible to be run on tablets and iOS. I want to rebuild it directly in html. As long as I have the full access to all CC programs, I will highly appreciate the advices from you:
    - which of the programs are appropriate to obtain this result (I am sure that I have to use several)?
    - how I can create an interactive polygon with fade-in and fade out effect and to use it as a button? This is essential because I have to mark precisely on the facade where is every apartment. A bounding box area does not help because the neighboring polygons will overlap on the corners if are bounding boxes, so is need such of polygons which interacts strictly within their perimeter.
    Thank you in advance for your help, I am waiting forward for your answers or even for some examples if possible. Once I get the point I am sure I can develop the learning process until I will able to rebuild the presentation.
    Cheers,
    Ville

    Hello K8,
    Thank you for your answer! I've been using for a while Swiffy convertor as a compromise, but the problem with it is that it doesn't work well on all browsers. To me would be the ideal solution, to work as before and only to convert the swf into html. But simply is not working as it might.
    Flash to html sounds good as a principle, but I am not using actually Flash but Swish, which does not create .fla documents, only directly swf. Do you have a recommendation for one of the possible scenarios:
    - to keep converting using Swiffy, but to improve html by adding some scripts to became compatible with all browsers. I have no idea what scripts, but maybe someone can help ( I am not a programmer)
    - to learn to use real Flash (I think is quite similar with Swish) and to export from there into html with a better coverage
    - to have better converter than Swiffy. Any recommendation?
    - to start to use Muse/Animate as intended, but I need a substantial help from someone to learn the basics.
    I am waiting for your or/and other users opinion and once I will make the right decision with your help I will work on it until everything will work great.
    Cheers,
    Ville

  • Is there a way to make polygone shapes/buttons?

    Greetz peepz,
    Is there a way to make polygone shapes and/or buttons? I would like to make more accurate dropshadows and imagemap-like buttons.

    Aaah, so it's part of the plan to make it posible in the future? To make dropshadows in PNG is ok, but when you want to use the dropshadow option on a transparent PNG it will put a dropshadow on the outer boarders of the imagesquare, that's kind of annoying. I want to animate a rotation of a polygone shape, but I'll skip the dropshadow for now then.

  • Polygon-shape buttons

    Hello everyone,
    I am a new enthusiastic subscriber of CC, and as every newcomer I have several questions. I will limit myself though to only one issue for now. Here is a link for an interactive architectural presentation I did:
    http://www.transsilta.com/ncc/auringonkeha/auringonkeha.html
    This file works nicely but has been built in Flash, and that's make impossible to be run on tablets and iOS. I want to rebuild it directly in html. As long as I have the full access to all CC programs, I will highly appreciate the advices from you:
    - which of the programs are appropriate to obtain this result (I am sure that I have to use several)?
    - how I can create an interactive polygon with fade-in and fade out effect and to use it as a button? This is essential because I have to mark precisely on the facade where is every apartment. A bounding box area does not help because the neighboring polygons will overlap on the corners if are bounding boxes, so is need such of polygons which interacts strictly within their perimeter.
    Thank you in advance for your help, I am waiting forward for your answers or even for some examples if possible. Once I get the point I am sure I can develop the learning process until I will able to rebuild the presentation.
    Cheers,
    Ville

    Hello K8,
    Thank you for your answer! I've been using for a while Swiffy convertor as a compromise, but the problem with it is that it doesn't work well on all browsers. To me would be the ideal solution, to work as before and only to convert the swf into html. But simply is not working as it might.
    Flash to html sounds good as a principle, but I am not using actually Flash but Swish, which does not create .fla documents, only directly swf. Do you have a recommendation for one of the possible scenarios:
    - to keep converting using Swiffy, but to improve html by adding some scripts to became compatible with all browsers. I have no idea what scripts, but maybe someone can help ( I am not a programmer)
    - to learn to use real Flash (I think is quite similar with Swish) and to export from there into html with a better coverage
    - to have better converter than Swiffy. Any recommendation?
    - to start to use Muse/Animate as intended, but I need a substantial help from someone to learn the basics.
    I am waiting for your or/and other users opinion and once I will make the right decision with your help I will work on it until everything will work great.
    Cheers,
    Ville

  • Cropping with magic lasso and wand and polygon tool, no crop button

    Thank you. I can see the green check mark at bottom of photo to finish a square crop. But where is the button after selecting an area with magnetic lasso or wand to crop, unless this s is not used for cropping? Tutorial doesn't  mention neither the button nor cropping.
    Note: I had to retype my question all over again, when I just clicked "submit question" and then this page pops up.

    Once, again, there is no program on earth that can do this. Many programs including PSE, can create transparent areas in an image but there is no digital image in existence that is not rectangular. When you use the magic extractor you are creating transparency, not cropping to a non-rectangular shape---the extractor does not crop your image in any way whatever. It's still exactly the same dimensions when you finish as it was when you entered the extractor. No version of Photoshop can do this, because it can't be done under current technology.
    You can crop an image or you can isolate an object with transparency but those are not both the same thing.

  • Creating a triangle using polygon class problem, URGENT??

    Hi i am creating a triangle using polygon class which will eventually be used in a game where by a user clicks on the screen and triangles appear.
    class MainWindow extends Frame
         private Polygon[] m_polyTriangleArr;
                       MainWindow()
                              m_nTrianglesToDraw = 0;
             m_nTrianglesDrawn = 0;
                             m_polyTriangleArr = new Polygon[15];
                             addMouseListener(new MouseCatcher() );
            setVisible(true);
                         class MouseCatcher extends MouseAdapter
                             public void mousePressed(MouseEvent evt)
                  Point ptMouse = new Point();
                  ptMouse = evt.getPoint();
                if(m_nTrianglesDrawn < m_nTrianglesToDraw)
                                int npoints = 3;
                        m_polyTriangleArr[m_nTrianglesDrawn]
                      = new Polygon( ptMouse[].x, ptMouse[].y, npoints);
    }When i compile my code i get the following error message:
    Class Expected
    ')' expectedThe two error messages are refering to the section new Polygon(....)
    line. Please help

    Cannot find symbol constructor Polygon(int, int, int)
    Can some one tell me where this needs to go and what i should generally
    look like pleaseI don't think it is a good idea to try and add the constructor that the compiler
    can't find. Instead you should use the constructor that already exists
    in the Polygon class: ie the one that looks like Polygon(int[], int[], int).
    But this requires you to pass two int arrays and not two ints as you
    are doing at the moment. As you have seen, evt.getPoint() only supplies
    you with a single pair of ints: the x- and y-coordinates of where the mouse
    button was pressed.
    And this is the root of the problem. To draw a triangle you need three
    points. From these three points you can build up two arrays: one containing
    the x-coordinates and one containing the y-coordinates. It is these two
    arrays that will be used as the first two arguments to the Polygon constructor.
    So your task is to figure out how you can respond to mouse presses
    correctly, and only try and add a new triangle when you have all three of its
    vertices.
    [Edit] This assumes that you expect the user to specify all three vertices of the
    triangle. If this isn't the case, say what you do expect.

  • How do I link one button to two slices?

    Hello,
    I need some help please. How do I link one button to two
    slices? or combine two slices to make one slice, or make a true
    polygon shape out of the slices, it will make the polygon shape but
    it leaves the the red guide lines and I cant work under that
    slice... if you understand. Will someone please help. Thank you so
    much.

    heathrowe wrote:
    > Did you Hide Slices?
    >
    > Select the Pointer Tool and click your Object? It should
    get selected.
    >
    > What happens when you mouse over the 'star' object? Do
    you get the 'object
    > selection' bounding area appear? Bounding area should
    appear red when you mouse
    > over it? Yes/No!
    >
    > Also, go to your Layer Panel and make sure that your
    object/Layer is not
    > 'locked'. Look for little 'padlock' icons next to the
    Layers. If you see it,
    > click it, to toggle it to 'off'.
    >
    > h
    >
    Also make sure you are not in PREVIEW mode in the document
    window.
    Jim Babbage - .:Community MX:. & .:Adobe Community
    Expert:.
    http://www.communityMX.com/
    CommunityMX - Free Resources:
    http://www.communitymx.com/free.cfm
    .:Adobe Community Expert for Fireworks:.
    Adobe Community Expert
    http://tinyurl.com/2a7dyp
    See my work on Flickr
    http://www.flickr.com/photos/jim_babbage/

  • How to make a custom form, buttons etc... please...

    I mean, how to make a form (for example, JFrame) with arbitrary form (geometry, for ex, round, oval, star like etc). I think you understand what i mean.
    Of course, i think i can use winApi, but it's only for windows. It doesn't suit for Java in this problem solution.
    That question also about cusomizing form of buttons, fields.. etc..
    i think, everything.
    What can java allows to cusomize and what not.
    Thanx!!

    I am just a learner and so i can just suggest you a strategy to implement Customized forms in JAVA. However i am sure that in practice it will work as far as Windows OS are concerned. Here is it:-
    The basic IDEA is to declare a native function in JAVA that makes JNI calls which will be further processed by Win32API and processed output will result into an elliptic or any polygonal shaped forms.
    To achieve declare some function as follows:
    public native void createEllipticalForm(formName formRefrance);
    create a Win32 Compiled DLL that manages this function as follows:
    (Mindwell, i havent stated what you call as pure-code but just a pseudo-code to the actual implementation)
    public native void createEllipticalForm(formName formRefrance)
    /* Search for the below stated Functions in Win32 API and work on
    them. I see a ray of success if you work with these functions properly.
    Further-more I assume that you are aware with concept of HANDLES */
    createEllipticRegion(); //WINDOWS.H
    showWindow(handleToTheForm); //WINDOWS.H
    Search for "createEllipticRegion() or showWindow()" on the GOOGLE to get the pure win32 API Code for Creating Customized Forms.
    Reply me in case any of you people get a solution based on my idea.
    [by VISH]

  • No option from Line button?

    I am watching this video tutorial, when the guy press the line button, four options: line, rectangle, oval and polygon options show up. When I press the same buttom on my Captivate, no such options showed up, just the line function. How can I get the four options like the guy in the video? I am using PC version of Captivate 5.5.
    Thanks.
    BTW, what happened to Adobe forum earlier, can't login or logout or post. (gave me a error message)

    Yes, normally you are supposed to click on that tiny triangle, but keeping the mouse button pressed long enough on the button will work as well. I always told the devs that it is such a pity that only one flyout menu is available in this toolbox, contrary to the other Adobe applications (like Photoshop) that do have a bunch of flyout menus and that seems easier to be detected than this unique one.
    Lilybiri

  • Polygon Applet?

    Please Help with this the applet is not working i tested the html file and it works fine, but there is something wrong with the applet. I am new to this stuff so I need your help. Much appreciated
    The requirements: Write an applet that lets the user click on six points. After the sixth point is clicked, the applet should draw a polygon with a vertex at each point the user clicked.
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.applet.Applet;
    public class assignment10 extends JApplet
         int i;
         int [] xCoords = new int[6];
         int [] yCoords = new int[6];
              Init Method
         public void init()
              getContentPane().setBackground(Color.white); // set the background color to white
              addMouseListener(new MyMouseListener()); // add the Mouse listener
         public void paint(Graphics g, int xCoords,int yCoords)
              super.paint(g);
              g.drawPolygon(xCoords, yCoords, 6);
         private class MyMouseListener extends MouseAdapter
              public void mousePressed(MouseEvent e)
                   for(i=0; i<5; i++) // fill the array
                        xCoords[i] = e.getX();
                        yCoords[i] = e.getY();
    if(i==5) // when the subscript i = 5, then reset to 0
                        i=0;

    You've got a lot to fix here. Some suggestions:
    1) For our benefit and yours, please use code tags whenever you post code. This will help your code retain its formatting, make it easier to read, and thus more likely that someone here will want to read it and help you. You simply highlight your pasted code and press the "Code" button before you post your message.
    2) Don't paint directly in the applet with a paint method. Paint instead in a JPanel that is somehow placed in the applet's contentPane, either directly or inside of another panel that is directly added. Then paint by overriding the JPanel's paintComponent method.
    3) Note that any time you override a method, be it paint, paintComponent, or any other method, the signature of the override must precisely match the signature of the method that it's overriding. Thus paint must have this signature: public void paint(Graphics g), and the same for paintComponent. public void paint(Graphics g, int x, int y) just won't work.
    4) If your paint method DID work in fact work, your drawPolygon wouldn't. Look at the API and you'll see that its method signature is not Graphics#drawPolygon(int, int, int). You need to use arrays with this method. Why not use the arrays that are held by the class? You will probably need two sets of arrays, one to hold the data to be used to paint with and one to build up this data as the mouse is being pressed, then swapped with the first array, the display array, when 6 points have been pressed.
    5) You have a for loop inside of your mousePressed method of the MouseAdapter. This will never work here as this logic is broken. You must think through what must happen here to fix this, and I think it best if you figure this out yourself.
    6) Let's continue on in this thread here, but in the future if you have Swing problems, you'll be best served to post the question in the Swing forum which is where the Swing gurus live. (Although this would probably be appropriate for the Java 2D forum also -- in the future you need to choose the one most appropriate of these and post only there).
    Much luck, and hope this helps!

  • Getting graphics to appear on button click

    hi guys
    could someone please look at my code and point out what i am doing wrong
    the applet below displays a christmas tree and 4 buttons.. when a button is clicked it should display another image from a different file in the same directory.. i have started to add the objects to actionPerformed but when i click on the "star" button a star does not appear.. i hope someone can help cuz one of the tutors in the java lab didnt have a clue
    applet................
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    import java.awt.BorderLayout;
    public class XmasTree2 extends Applet implements ActionListener
         Panel topP;
         Panel mainP;
         Button baub;
         Button pres;
         Button light;
         Button star;
         Color green;
         Object Triangle, Star;
         Polygon triangle1, triangle2, triangle3;
         public void init()
                   setSize(600,600);
                   baub = new Button("Bauble");
                   baub.setBackground(Color.cyan);
                   pres = new Button("Present");
                   pres.setBackground(Color.cyan);
                   light = new Button("Light");
                   light.setBackground(Color.cyan);
                   star = new Button("Star");
                   star.setBackground(Color.cyan);
                   add(baub);
                   add(pres);
                   add(light);
                   add(star);
                   baub.addActionListener(this);
                   pres.addActionListener(this);
                   light.addActionListener(this);
                   star.addActionListener(this);
                   repaint();
         public void paint(Graphics graf)
              triangle1 = new Polygon();
              triangle1.addPoint(300,50);
              triangle1.addPoint(175,220);
              triangle1.addPoint(425,220);
              triangle2 = new Polygon();
              triangle2.addPoint(300,150);
              triangle2.addPoint(100,325);
              triangle2.addPoint(500,325);
              triangle3 = new Polygon();
              triangle3.addPoint(300,250);
              triangle3.addPoint(50,400);
              triangle3.addPoint(550,400);
              green = Color.green;
              graf.setColor(green);
              graf.fillPolygon(triangle1);
              graf.fillPolygon(triangle2);
              graf.fillPolygon(triangle3);
              graf.setColor(new Color(204, 102, 0));
              graf.fillRect(280,400,40,100);
         public void actionPerformed( ActionEvent event )
              if (event.getSource() == star)
                         Star myStar = new Star();
              else if (event.getSource() == baub)
                         System.out.println ("baub");
              else if (event.getSource() == pres)
                         System.out.println ("pres");
              else if (event.getSource() == light)
                         System.out.println ("light");
         public void mousePressed(MouseEvent e)
         public void mouseReleased(MouseEvent e)
         public void mouseEntered(MouseEvent e)
         public void mouseExited(MouseEvent e)
         public void mouseMoved(MouseEvent e)
         public void mouseClicked(MouseEvent e)
         public void mouseDragged(MouseEvent e)
    }star class
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    import java.awt.BorderLayout;
    public class Star extends Applet
          Polygon sTriangle1, sTriangle2;
         public void paint(Graphics graf)
              sTriangle1 = new Polygon();
              sTriangle1.addPoint(50,50);
              sTriangle1.addPoint(20,100);
              sTriangle1.addPoint(80,100);
              sTriangle2 = new Polygon();
              sTriangle2.addPoint(50,120);
              sTriangle2.addPoint(20,70);
              sTriangle2.addPoint(80,70);
              graf.setColor(Color.yellow);
              graf.fillPolygon(sTriangle1);
              graf.fillPolygon(sTriangle2);
              System.out.println("st");
    }

    when i click on the "star" button a star does not appear
    Your idea for a separate Star class is very good. Your Star extends Applet so to have it
    appear and draw itself on your other applet you would have to add it as a component. But
    it would have a rectangular shape and then you have backgtound color and obscuration
    problems. You could do it this way; if you do, have Star extend Panel instead of Applet
    (Applet is a top-level container). Another way is to make Star a graphic class and have it
    draw itself into your graphics component, your (XT2) applet. An even more refined approach
    would be to do all the drawing in a separate class that extends Panel and add this graphic
    component to your applet (center section of a new BorderLayout). Then the applet has a
    button panel, action listener and a graphics component. MouseEvent code would go with the
    separate graphics class.
    Here are some suggestions/ideas for the Star class, in java:
    //  <applet code="XT2" width="600" height="600"></applet>
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    public class XT2 extends Applet implements ActionListener
        Panel topP;
        Panel mainP;
        Button baub;
        Button pres;
        Button light;
        Button star;
        Color green;
        Polygon triangle1, triangle2, triangle3;
        Star[] stars = new Star[0];  // zero-length array
        boolean addStar = false;
        public void init()
            setSize(600,600);
            initTriangles();
            baub = new Button("Bauble");
            baub.setBackground(Color.cyan);
            pres = new Button("Present");
            pres.setBackground(Color.cyan);
            light = new Button("Light");
            light.setBackground(Color.cyan);
            star = new Button("Star");
            star.setBackground(Color.cyan);
            add(baub);
            add(pres);
            add(light);
            add(star);
            baub.addActionListener(this);
            pres.addActionListener(this);
            light.addActionListener(this);
            star.addActionListener(this);
            addMouseListener(decorator);
    //        repaint();  // there's nothing to paint yet
        public void paint(Graphics graf)
            green = Color.green;  // this only needs to be done once
            graf.setColor(green);
            graf.fillPolygon(triangle1);
            graf.fillPolygon(triangle2);
            graf.fillPolygon(triangle3);
            graf.setColor(new Color(204, 102, 0));
            graf.fillRect(280,400,40,100);
            graf.setColor(new Color(200, 200, 55));
            // Let the Stars do the work.
            for(int j = 0; j < stars.length; j++)
                stars[j].draw(graf);
        /** Simplify paint method and avoid repitition. */
        private void initTriangles()
            triangle1 = new Polygon();
            triangle1.addPoint(300,50);
            triangle1.addPoint(175,220);
            triangle1.addPoint(425,220);
            triangle2 = new Polygon();
            triangle2.addPoint(300,150);
            triangle2.addPoint(100,325);
            triangle2.addPoint(500,325);
            triangle3 = new Polygon();
            triangle3.addPoint(300,250);
            triangle3.addPoint(50,400);
            triangle3.addPoint(550,400);
        public void actionPerformed( ActionEvent event )
            if (event.getSource() == star)
                // Keep this simple just for this example.
                // You may find a more elegant way to manage
                // user selections for decorating the tree.
                addStar = addStar ? false : true;  // toggle on/off
                System.out.println("addStar = " + addStar);
        /** Just for the sake of a simple example. */
        private MouseListener decorator = new MouseAdapter()
            public void mousePressed(MouseEvent e)
                Point p = e.getPoint();
                if(addStar)
                    Star aStar = new Star(p);
                    // Add the new Star to the stars array.
                    Star[] temp = new Star[stars.length+1];
                    System.arraycopy(stars, 0, temp, 0, stars.length);
                    temp[stars.length] = aStar;
                    stars = temp;
                    repaint();
    class Star
        Polygon sTriangle1, sTriangle2;
        public Star(Point p)
            // We only need to make this once
            // since the values are hard-coded.
            sTriangle1 = new Polygon();
            sTriangle1.addPoint(50,50);
            sTriangle1.addPoint(20,100);
            sTriangle1.addPoint(80,100);
            sTriangle2 = new Polygon();
            sTriangle2.addPoint(50,120);
            sTriangle2.addPoint(20,70);
            sTriangle2.addPoint(80,70);
            // Find the center of star.
            Rectangle bounds = new Rectangle(20, 50, 60, 70);
            double cx = bounds.getCenterX();
            double cy = bounds.getCenterY();
            // Translate star over Point p.
            int tx = (int)(p.x - cx);
            int ty = (int)(p.y - cy);
            sTriangle1.translate(tx, ty);
            sTriangle2.translate(tx, ty);
        public void draw(Graphics graf)
            graf.setColor(Color.yellow);
            graf.fillPolygon(sTriangle1);
            graf.fillPolygon(sTriangle2);
            System.out.println("st");
    }

  • Buttons having shape of Sector

    I want to draw three Buttons of Sector shape and arrange them in form of a circle.
    Sector angle must be 120 degree for all the three Buttons.Please help!

    ...hm, okay, i put something together... keep in mind it's pretty late... and maybe i should have let that last bottle of wine be, but anyway, perhaps this will help:
    public class TestFrame extends JFrame {
        private JPanel _cPane;
        private Ellipse2D _oval=new Ellipse2D.Double(40,40,100,100);
        int[] xs={90,90,133,140,140};
        int[] ys={40,90,115,115,40};
        private Area _sector1=new Area(new Polygon(new int[]{90,90,133,140,140}, new int[]{40,90,115,115,40}, 5));
        private Area _sector2=new Area(new Polygon(new int[]{90,90,47,40,40}, new int[]{40,90,115,115,40}, 5));
        private Area _sector3=new Area(new Polygon(new int[]{40,47,90,133,140}, new int[]{140,115,90,115,140}, 5));
        private int _inside=0;
        public static void main(String[] args) {
            new TestFrame();
        public TestFrame() {
            super();
            init();
            initFrame();
        private void init() {
            Area rhs = new Area(_oval);
            _sector1.intersect(rhs);
            _sector2.intersect(rhs);
            _sector3.intersect(rhs);
            _cPane=new JPanel(){
                public void paint(Graphics g) {
                    super.paint(g);
                    Graphics2D g2=(Graphics2D)g;
                    g2.setColor(Color.RED);
                    g2.fill(_oval);
                    g2.setColor(Color.BLUE);
                    g2.draw(_sector1);
                    g2.draw(_sector2);
                    g2.draw(_sector3);
                    g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,0.5f));
                    g2.setColor(Color.yellow);
                    if (_inside==1)
                        g2.fill(_sector1);
                    else if (_inside==2)
                        g2.fill(_sector2);
                    else if (_inside==3)
                        g2.fill(_sector3);
            _cPane.addMouseMotionListener(new MouseMotionAdapter(){
                public void mouseMoved(MouseEvent e) {
                    Point point = e.getPoint();
                    if (_sector1.contains(point))
                        _inside=1;
                    else if (_sector2.contains(point))
                        _inside=2;
                    else if (_sector3.contains(point))
                        _inside=3;
                    else _inside=0;
                    repaint();
        private void initFrame() {
            setSize(200, 200);
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            setLocation((screenSize.width - getWidth()) / 2, (screenSize.height - getHeight()) / 2);
            setContentPane(_cPane);
            setVisible(true);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }It's not as bad as it seem, although i hardcoded the coordinates (you should not, but as i said, it's pretty late already). The example above will highlight a sector as soon as you move your mouse above it - i guess you won't have trouble handling a click accordingly, i just thought this would be a bit more visible.

  • Illustrator CS3 : making a transparent polygone

    Hi everybody,
    This is my first topic in this forum.
    I want to know if there is any way to make a colored transparent polygone using illustrator CS3 or by any other adobe's family softs ?
    Thank you

    There's a polygon tool under the rectangle tool in the toolbar. Click and hold on the rectangle to see a sub-toolbar. The polygon tool looks like a hexagon. Click-and drag to start drawing a polygon. Press the up and down arrows before you let go of the mouse button to add or remove sides.
    You can fill the polygon using the Color or Swatches panels. That's also where you can set the stroke colour. The stroke thickness is set in the Stroke panel.
    You'll have to give a more thorough explanation of what you mean by transparent, but transparency is usually set in the Transparency panel (whodathunkit?).
    Also, what are you doing with this graphic? Are you adding the polygon to existing art in Illustrator, importing the polygon into another program, saving an image for a web page, printing, or something else?

Maybe you are looking for