Circle JButton

Hi everybody,
I'm doing a constraints solver program for my studies and I have made a graphical interface but I want to make it more funny by adding JButton but not rectangular .
If somebody have an idea to help me...
Thanks

This question has been asked before. Learn how to search the forum.
http://forum.java.sun.com/thread.jsp?forum=31&thread=227950

Similar Messages

  • Problem with displaying objects in GUI

    I'm just going through a small book on Java programming and the goal is to press a button to show a shape (ie: circle) and then to press a button to hide that same shape.
    My idea was to simply add it in but change the visibility to true and false. Now, I get it to show perfectly but I can't get it to hide (ie: setVisiblity to false) for some reason. The problem lies in the actionPerformed method of the CommandMain class. I'm at a loss as to why I can't simply change the visibility of the object to true and false.
    I've include the relevant code below
    Thanks for all your help in advance.
    ================= COMMANDMAIN.JAVA =================
    public class CommandMain extends JFrame implements ActionListener
    {     JButton circleButton = new JButton("Make Circle");
         JButton squareButton = new JButton("Make Square");
         JButton undoButton = new JButton("Undo Last");
         JButton exitButton = new JButton("Exit");
         private static Vector objectList = new Vector(); // Stores objects in order
    JPanel container = new JPanel();
         Button newCircle;     // Used to add a Circle object to the vector     
         Button newSquare;
         Button newShape;
    Button objectToHide;
    // CONSTRUCTOR
    // PURPOSE: Used to set up all the buttons on our Panel
         public CommandMain()
         {     setSize(400,400);
         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              // Add interactive ability to buttons
              circleButton.addActionListener(this);
    squareButton.addActionListener(this);
    undoButton.addActionListener(this);
              exitButton.addActionListener(this);
              // Add them so we can see them on the panel
    this.container.add(circleButton);
    this.container.add(squareButton);
    this.container.add(undoButton);
              this.container.add(exitButton);
    setContentPane(container);
    setVisible(true);
         // PURPOSE: Used to create an instance of itself so we can see the frame
    public static void main(String args[]) throws IOException
    {    CommandMain window = new CommandMain();     }
         // PURPOSE: Used to perform actions based on the button picked by the user
    public void actionPerformed(ActionEvent picked)
    {     Object choice = picked.getSource();
    if(choice == circleButton)     // CIRCLE WAS SELECTED
    {     newShape = new Button("Circle");          
                   Button newCircle = newShape.getShape();
                   this.container.add(newCircle);     // Add it to my container
                   newShape.execute();
    objectList.add(newShape);     // Add the object to my Vector
                   setContentPane(container);
    repaint();     // Redraw the GUI because it changed
    else if(choice == undoButton) // UNDO WAS SELECTED
    {     if(objectList.size() > 0)     // Check to ensure we don't overstep the boundaries
    {     System.out.println("UNDO Pressed");
                        objectToHide = (Button)objectList.elementAt(objectList.size()-1);
                        objectToHide.hideShape(); // <-- NOT WORKING
                        objectList.removeElementAt(objectList.size()-1);
                        setContentPane(container);
                        repaint();
    } // End if(objectList.size() > 0)
    } // End undoButton
              else if(choice == exitButton) // EXIT WAS SELECTED
              {     System.out.println("Goodbye: Application exiting");
                   dispose();
                   System.exit(0);          
              else // No idea what button was selected
    {         System.out.println("ERROR: Invalid option");     }
    ========================== BUTTON.JAVA ==================
    import java.awt.*;
    import javax.swing.*;
    public class Button extends JPanel
    {     String objectShape;
         Button()
         Button(String shape)
         {     this.objectShape = shape; }
         public void execute()
         {     setVisible(true);     }
         public void hideShape()
         {     System.out.println("hideShape called");
              super.setVisible(false);
         public Button getShape()
         {     if(this.objectShape.equals("Circle"))
              {     System.out.println("Making a circle");     
                   Circle newCircle = new Circle();
                   return newCircle;
              else if(this.objectShape.equals("Square"))
              {     System.out.println("Making a square");     
                   Square newSquare = new Square();
                   return newSquare;
              return null;

    This will do the job, read and learn
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class CommandMain extends JFrame implements ActionListener
         Shape    shape;
         JPanel   pan          = new JPanel();
         JPanel   but          = new JPanel();
         JButton  circleButton = new JButton("Make Circle");
         JButton  squareButton = new JButton("Make Square");
         JButton  undoButton   = new JButton("Undo Last");
         JButton  exitButton   = new JButton("Exit");
    public CommandMain()
         super();
         setBounds(6,6,700,400);     
         addWindowListener(new WindowAdapter()
        {     public void windowClosing(WindowEvent ev)
                   dispose();     
                   System.exit(0);
         pan.setBackground(Color.pink);
         getContentPane().add("Center",pan);
         but.add(circleButton);
         but.add(squareButton);
         but.add(undoButton);
         but.add(exitButton);
         circleButton.addActionListener(this);
         squareButton.addActionListener(this);
         undoButton.addActionListener(this);
         exitButton.addActionListener(this);
         getContentPane().add("South",but);
         setVisible(true);
    public void actionPerformed(ActionEvent a)
         if (a.getSource() == circleButton)
              pan.add(new Shape("Circle"));
              pan.revalidate();
         if (a.getSource() == squareButton)
              pan.add(new Shape("Square"));
              pan.revalidate();
         if (a.getSource() == undoButton && pan.getComponentCount() > 0)
               pan.remove(pan.getComponentCount()-1);
              pan.revalidate();
              pan.repaint();
         if (a.getSource() == exitButton)
              dispose();     
              System.exit(0); 
    public class Shape extends JComponent
         String shape;
    public Shape(String shape)
         this.shape = shape;
         setPreferredSize(new Dimension(20,20));
    public void paintComponent(Graphics g)
         super.paintComponent(g);
         if (shape.equals("Circle"))
              g.drawOval(0,0,getWidth()-1,getHeight()-1);
         if (shape.equals("Square"))
              g.drawRect(0,0,getWidth()-1,getHeight()-1);     
    public static void main (String[] args)
         new CommandMain();  
    }       Noah

  • How to get the color of a point?

    Hi.
    I have a JPanel with some black circles draw on it (with drawOval() method), now i need to scan all the JPanel and search the black points and the withe ones.
    I couldn't do this
    i can found any method that give me the properties of a point in a JPanel.
    can anyone tell where to look for this?, any method that controls the properties of a point?
    PD: if is necessary, i can change the JPanel for a Canvas
    TKS

    hi. i make what you told me, but the getRGB() method is always giving me -1 as return.
    here is my code, it's simple but i only need to make a matriz with this circles.
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Container;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.image.BufferedImage;
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class GUI extends JFrame{
         private JPanel panel;
         private JFrame frame;
         public GUI () {
              frame = new JFrame("Puntos Espaciales.");
              JButton button = new JButton("Draw Circle");
              JButton button2 = new JButton("1");
              Container con = frame.getContentPane();
              panel = new JPanel();
              panel.setBorder(BorderFactory.createTitledBorder("Hello"));
              panel.setBackground(Color.WHITE);
              con.add(panel, BorderLayout.CENTER);
              con.add(button, BorderLayout.SOUTH);
              con.add(button2, BorderLayout.EAST);
              frame.setSize(800,600);
              frame.setVisible(true);
              button.addActionListener(new ActionListener() {
                  public void actionPerformed(ActionEvent event) {
                     Graphics g = panel.getGraphics();
                     g.setColor(Color.BLACK);
                       g.fillOval(50, 50, 50, 50);
              button2.addActionListener(new ActionListener() {
                  public void actionPerformed(ActionEvent event) {
                     BufferedImage image = new BufferedImage(panel.getWidth(), panel.getHeight(), BufferedImage.TYPE_INT_RGB);
                     Graphics2D g2d = image.createGraphics();
                     panel.paint( g2d );
                     g2d.dispose();
                     System.out.println("5,5" + image.getRGB(5, 5));
                     System.out.println("50,50" + image.getRGB(50, 50));
         public static void main(String[] args) {
              GUI gui = new GUI();
    }tks for your help
    PD: sorry for the delay

  • I have aproblem in my code

    this is aprogram to paint different shape by using only the drawline method its composed of two classes one contain the frame and buttons and the other contain the panel for drawing I dont know why when I run the programe I get this erorr messags and wats this error message mean ?
    Exception in thread "main" java.lang.NullPointerException
         at paint.Paint.<init>(Paint.java:56)
         at paint.Paint.main(Paint.java:37
    package paint;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JPanel;
    import javax.swing.JTextArea;
    public class Paint {
        JFrame frame = new JFrame();
        JPanel panel = new JPanel();
        JButton line = new JButton("Line");
        JButton triangle = new JButton("Triangle");
        JButton rectangle = new JButton("Rectangle");
        JButton regularpolygon = new JButton("Regular Polygon");
        JTextArea regularpolygonno = new JTextArea(2,4);
        JButton circle = new JButton("Circle");
        JButton ellipse = new JButton("Ellipse");
        JButton polyline = new JButton("Polyline");
        JButton polygon = new JButton("Polygon");
        JMenuBar mbar = new JMenuBar();
        JMenu file = new JMenu("File");
        JMenuItem save = new JMenuItem("Save");
        JMenuItem load = new JMenuItem("Load");
        ppanel PaintPanel;
        int result;
        public static void main(String[] args) {
                Paint p = new Paint();
        public Paint (){
            mbar.add(file);
            file.add(load);
            file.add(save);
            panel.setPreferredSize(new Dimension(50, 100));
            panel.setBackground(Color.YELLOW);
            panel.add(line);
            panel.add(triangle);
            panel.add(rectangle);
            panel.add(regularpolygon);
            panel.add(regularpolygonno);
            panel.add(polyline);
            panel.add(polygon);
            panel.add(circle);
            panel.add(ellipse);
            PaintPanel.setPreferredSize(new Dimension(600, 600));
            frame.setTitle("Paint");
            frame.setSize(1200,1200);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setJMenuBar(mbar);
            frame.add(panel, BorderLayout.WEST);
            frame.add(PaintPanel, BorderLayout.EAST);
            frame.pack();
            frame.setVisible(true);
            line.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e) {
                line_actionPerformed(e);
            triangle.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e) {
                triangle_actionPerformed(e);
            rectangle.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e) {
                rectangle_actionPerformed(e);
            regularpolygon.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e) {
                regularpolygon_actionPerformed(e);
            circle.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e) {
                circle_actionPerformed(e);
            ellipse.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e) {
                ellipse_actionPerformed(e);
            polyline.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e) {
                polyline_actionPerformed(e);
            polygon.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e) {
                polygon_actionPerformed(e);
        public void actionPerformed(ActionEvent e) {
                if(e.getActionCommand()=="Load"){
                System.out.println("A Seat Reserved");            
        private void line_actionPerformed(ActionEvent e) {
        result=1;
        System.out.println(result);
        private void triangle_actionPerformed(ActionEvent e) {
        result=2;
        System.out.println(result);
        private void regularpolygon_actionPerformed(ActionEvent e) {
        result=3;
        System.out.println(result);
        private void circle_actionPerformed(ActionEvent e) {
        result=4;
        System.out.println(result);
        private void ellipse_actionPerformed(ActionEvent e) {
        result=5;
        System.out.println(result);
        private void rectangle_actionPerformed(ActionEvent e) {
        result=6;
        System.out.println(result);
        private void polyline_actionPerformed(ActionEvent e) {
        result=7;
        System.out.println(result);
        private void polygon_actionPerformed(ActionEvent e) {
        result=8;
        System.out.println(result);
        public int callresult(){
                return result;
    }

    this code is just acompelete for the second class in 2nd replay
        @Override public void paintComponent(Graphics g ){
        super.paintComponents(g);
        for(i=0 ; i< al.size(); i++){
                if (drawLines[4] == 1){
    pressed = false;
    if(pressed1 == 1 && drawLines[i][4] != 1){
    pressed1 = 0;
    g.drawLine(drawLines[i][0],drawLines[i][1],xplgn,yplgn);
    System.out.println("problem here1");
    }else
    g.drawLine(drawLines[i][0],drawLines[i][1],drawLines[i][2],drawLines[i][3]);
    }else if (drawLines[i][4] == 2 ){
    pressed = false;
    pressed1 = 0;
    g.drawLine(drawLines[i][0],drawLines[i][1],drawLines[i][2],drawLines[i][1]);
    g.drawLine(drawLines[i][2],drawLines[i][1],drawLines[i][2],drawLines[i][3]);
    g.drawLine(drawLines[i][2],drawLines[i][3],drawLines[i][0],drawLines[i][3]);
    g.drawLine(drawLines[i][0],drawLines[i][3],drawLines[i][0],drawLines[i][1]);
    }else if(drawLines[i][4] == 3){
    pressed = false;
    pressed1 = 0;
    for(int l=0;l<drawLines[i][5]; l++){
    double r =Math.sqrt(Math.pow(drawLines[i][0]-drawLines[i][2],2)+Math.pow(drawLines[i][1]-drawLines[i][3],2)) ;
    double x11 = r*Math.cos((2*pi/drawLines[i][5])*(l));
    double y11 = r*Math.sin((2*pi/drawLines[i][5])*(l));
    double x22 = r*Math.cos((2*pi/drawLines[i][5])*(l+1));
    double y22 = r*Math.sin((2*pi/drawLines[i][5])*(l+1));
    int sumx1 = drawLines[i][0]+(int)x11;
    int sumy1 = drawLines[i][1]+(int)y11;
    int sumx2 = drawLines[i][0]+(int)x22;
    int sumy2 = drawLines[i][1]+(int)y22;
    g.drawLine(sumx1,sumy1,sumx2,sumy2);
    }else if(drawLines[i][4] == 4) {
    pressed = false;
    pressed1 = 0;
    int n =360;
    for(int l=0;l<n; l++){
    double r =Math.sqrt(Math.pow(drawLines[i][0]-drawLines[i][2],2)+Math.pow(drawLines[i][1]-drawLines[i][3],2)) ;
    double x11 = r*Math.cos((2*pi/n)*(l));
    double y11 = r*Math.sin((2*pi/n)*(l));
    double x22 = r*Math.cos((2*pi/n)*(l+1));
    double y22 = r*Math.sin((2*pi/n)*(l+1));
    int sumx1 = drawLines[i][0]+(int)x11;
    int sumy1 = drawLines[i][1]+(int)y11;
    int sumx2 = drawLines[i][0]+(int)x22;
    int sumy2 = drawLines[i][1]+(int)y22;
    g.drawLine(sumx1,sumy1,sumx2,sumy2);
    }else if(drawLines[i][4] == 5) {
    pressed = false;
    pressed1 = 0;
    int n =360;
    for(int l=0;l<n; l++){
    double a = Math.abs(drawLines[i][0] - drawLines[i][2]);
    double b = Math.abs(drawLines[i][1] - drawLines[i][3]);
    double x11 = a*Math.cos((2*pi/n)*(l));
    double y11 = b*Math.sin((2*pi/n)*(l));
    double x22 = a*Math.cos((2*pi/n)*(l+1));
    double y22 = b*Math.sin((2*pi/n)*(l+1));
    int sumx1 = drawLines[i][0]+(int)x11;
    int sumy1 = drawLines[i][1]+(int)y11;
    int sumx2 = drawLines[i][0]+(int)x22;
    int sumy2 = drawLines[i][1]+(int)y22;
    g.drawLine(sumx1,sumy1,sumx2,sumy2);
    }else if(drawLines[i][4] == 6){
    pressed = false;
    pressed1 = 0;
    int n =4;
    for(int l=0;l<n; l++){
    double r =Math.sqrt(Math.pow(drawLines[i][0]-drawLines[i][2],2)+Math.pow(drawLines[i][1]-drawLines[i][3],2)) ;
    double x11 = r*Math.cos((pi/n)-(2*pi/n)*(l));
    double y11 = r*Math.sin((pi/n)-(2*pi/n)*(l));
    double x22 = r*Math.cos((pi/n)-(2*pi/n)*(l+1));
    double y22 = r*Math.sin((pi/n)-(2*pi/n)*(l+1));
    int sumx1 = drawLines[i][0]+(int)x11;
    int sumy1 = drawLines[i][1]+(int)y11;
    int sumx2 = drawLines[i][0]+(int)x22;
    int sumy2 = drawLines[i][1]+(int)y22;
    g.drawLine(sumx1,sumy1,sumx2,sumy2);
    }else if(drawLines[i][4] == 7){
    pressed1 = 0;
    if(pressed == false){
    g.drawLine(drawLines[i][0],drawLines[i][1],drawLines[i][2],drawLines[i][3]);
    pressed = true;
    }else {
    g.drawLine(drawLines[i][0],drawLines[i][1],drawLines[i][2],drawLines[i][3]);
    } else if (drawLines[i][4] == 8) {
    pressed = false;
    if(pressed1 == 0){
    g.drawLine(drawLines[i][0],drawLines[i][1],drawLines[i][2],drawLines[i][3]);
    xplgn = drawLines[i][0];
    yplgn = drawLines[i][1];
    pressed1 = 1;
    }else {
    g.drawLine(drawLines[i][0],drawLines[i][1],drawLines[i][2],drawLines[i][3]);

  • HELP: disabling  the corresponding buttons

    I'm on the last step of this program. Basically what i'm having trouble with is as follows:
    �     When the circle gets all the way to an edge, disable the corresponding button. When it moves back in, enable the button again.
    I have put in BOLD where my errors occur. It seems to be simple placement of { } brackets but everytime I place one somewhere code is interrupted in another location.
    //   CirclePanel.java
    //   A panel with a circle drawn in the center and buttons on the
    //   bottom that move the circle.
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class CirclePanel extends JPanel
        private final int CIRCLE_SIZE = 50;
        private int x,y;
        private Color c, r, o, bl, b;
        CirclePanel circlePanel;
        // Set up circle and buttons to move it.
        public CirclePanel(int width, int height)
        circlePanel = this;
         // Set coordinates so circle starts in middle
         x = (width/2)-(CIRCLE_SIZE/2);
         y = (height/2)-(CIRCLE_SIZE/2);
         c = Color.green;
         r = Color.red;
         o = Color.orange;
         bl = Color.black;
         b = Color.blue;
         // Need a border layout to get the buttons on the bottom
         this.setLayout(new BorderLayout());
         // Create buttons to move the circle
         JButton left = new JButton("Left");
         left.setMnemonic ('L');
         left.setToolTipText ("Moves the circle in the left direction 20 pixels");
         JButton right = new JButton("Right");
         right.setMnemonic ('R');
         right.setToolTipText ("Moves the circle in the right direction 20 pixels");
         JButton up = new JButton("Up");
         up.setMnemonic ('U');
         up.setToolTipText ("Moves the circle upward 20 pixels");
         JButton down = new JButton("Down");
         down.setMnemonic ('D');
         down.setToolTipText ("Moves the circle in the downward direction 20 pixels");
         // Add listeners to the buttons
         left.addActionListener(new MoveListener(-20,0));
         right.addActionListener(new MoveListener(20,0));
         up.addActionListener(new MoveListener(0,-20));
         down.addActionListener(new MoveListener(0,20));
         // Need a panel to put the buttons on or they'll be on
         // top of each other.
         JPanel buttonPanel = new JPanel();
         buttonPanel.add(left);
         buttonPanel.add(right);
         buttonPanel.add(up);
         buttonPanel.add(down);
         //Creates a button for each new color
         JButton red = new JButton("Red");
         JButton orange = new JButton("Orange");
         JButton black = new JButton("Black");
         JButton blue = new JButton("Blue");
         // Add listeners to the color buttons
         red.addActionListener(new ColorListener(r));
         orange.addActionListener(new ColorListener(o));
         black.addActionListener(new ColorListener(bl));
         blue.addActionListener(new ColorListener(b));
         //Adds the color buttons to the panel
         JPanel colorPanel = new JPanel();
         colorPanel.add(red);
         colorPanel.add(orange);
         colorPanel.add(black);
         colorPanel.add(blue);
         // Add the button panel to the bottom of the main panel
         this.add(buttonPanel, "South");
         this.add(colorPanel, "North");
        // Draw circle on CirclePanel
        public void paintComponent(Graphics page)
         super.paintComponent(page);
         page.setColor(c);
         page.fillOval(x,y,CIRCLE_SIZE,CIRCLE_SIZE);
        *// Class to listen for button clicks that move circle.*
        *private class MoveListener implements ActionListener*
        *private int dx;*
        *private int dy;*   <--- Syntax Error { Expected
       *     if (x > -60 )*
       *          left.setEnabled(true);*
    *      if (x < -60)*
    *          left.setEnabled(false);*  <--- Syntax Error } Expected
         // Parameters tell how to move circle at click.
         public MoveListener(int dx, int dy)
             this.dx = dx;
             this.dy = dy;
         // Change x and y coordinates and repaint.
         public void actionPerformed(ActionEvent e)
             x += dx;
             y += dy;
             repaint();
        // Listens for button clicks that change the circles color
        private class ColorListener implements ActionListener
             Color circleColor;
         // Constructor
         public ColorListener(Color buttonColor)
              circleColor = buttonColor;
         // Repaints the circle according to which button is pushed
         public void actionPerformed(ActionEvent e)
              c = circleColor;
             circlePanel.repaint();
    }

    I've just posted a reply in the programming forum (after you were redirected here)

  • Draw circles in swing..

    hello.
    I'm making a program that draws circles in a frame and has some buttons in another program.
    However, there are some stack overflow errors..
    help please~
    [error messages]
    Exception in thread "main" java.lang.StackOverflowError
    at java.util.Hashtable.get(Hashtable.java:336)
    at javax.swing.UIDefaults.getFromHashtable(UIDefaults.java:142)
    at javax.swing.UIDefaults.get(UIDefaults.java:130)
    at javax.swing.MultiUIDefaults.get(MultiUIDefaults.java:44)
    at javax.swing.UIDefaults.getColor(UIDefaults.java:380)
    at javax.swing.UIManager.getColor(UIManager.java:590)
    at javax.swing.LookAndFeel.installColors(LookAndFeel.java:58)
    at javax.swing.LookAndFeel.installColorsAndFont(LookAndFeel.java:92)
    at javax.swing.plaf.basic.BasicPanelUI.installDefaults(BasicPanelUI.java:49)
    at javax.swing.plaf.basic.BasicPanelUI.installUI(BasicPanelUI.java:39)
    at javax.swing.JComponent.setUI(JComponent.java:652)
    at javax.swing.JPanel.setUI(JPanel.java:131)
    at javax.swing.JPanel.updateUI(JPanel.java:104)
    at javax.swing.JPanel.<init>(JPanel.java:64)
    at javax.swing.JPanel.<init>(JPanel.java:87)
    at javax.swing.JPanel.<init>(JPanel.java:95)
    at DrawCircle.<init>(DrawCircle.java:7)
    at DrawCircle.<init>(DrawCircle.java:6)
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
    public class GUI{
         DrawCircle circle = new DrawCircle(100,100,50);
         private JButton UpButton, DownButton, LeftButton, RightButton, IncreaseButton, DecreaseButton, InputButton;
         public void drawframe(){
                    final JFrame CircleFrame = new JFrame("Frame for Circle");
                    CircleFrame.getContentPane().add(circle);
                    CircleFrame.setSize(200,200);
              CircleFrame.setVisible(true);
              UpButton = new JButton("UP");
              UpButton.addActionListener(new ActionListener()     {
                   public void actionPerformed(ActionEvent e){
                                circle.up();
                                    if(circle.getY() - circle.getR() <= 0) {
                                        JOptionPane.showMessageDialog( CircleFrame, "Out of window");
                                        circle.setY(circle.getY() +10);
              RightButton = new JButton("RIGHT");
              RightButton.addActionListener(new ActionListener()     {
                   public void actionPerformed(ActionEvent e)     {
                                circle.right();
                                    if(circle.getX() + circle.getR() >= 500) {
                                        JOptionPane.showMessageDialog( CircleFrame, "Out of window");
                                        circle.setX(circle.getX() -10);
              LeftButton = new JButton("LEFT");
              LeftButton.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent e){
                                circle.left();
                                    if(circle.getX() - circle.getR() <= 0) {
                                        JOptionPane.showMessageDialog( CircleFrame, "Out of window");
                                        circle.setX(circle.getX() +10);
              DownButton = new JButton("DOWN");
              DownButton.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent e){
                                circle.down();
                                    System.out.println(circle.getY());
                                    if(circle.getY() + circle.getR() >= 500) {
                                        JOptionPane.showMessageDialog( CircleFrame, "Out of window");
                                        circle.setY(circle.getY() -10);
              IncreaseButton = new JButton("INCREASE");
              IncreaseButton.addActionListener(new ActionListener()     {
                   public void actionPerformed(ActionEvent e)     {
                                circle.increase();
                                    if(circle.getY() + circle.getR() >= 500) {
                                        JOptionPane.showMessageDialog( CircleFrame, "Out of window");
                                        circle.setR(circle.getR() -10);     
                                    } else if(circle.getX() + circle.getR() >= 500) {
                                        JOptionPane.showMessageDialog( CircleFrame, "Out of window");
              DecreaseButton = new JButton("decrease");
                        DecreaseButton.addActionListener(new ActionListener(){
                                public void actionPerformed(ActionEvent e)     {           
                                    circle.decrease();
              JPanel ButtonPanel = new JPanel();
              ButtonPanel.add(IncreaseButton);
              ButtonPanel.add(DecreaseButton);
              ButtonPanel.add(DownButton);
              ButtonPanel.add(LeftButton);
              ButtonPanel.add(RightButton);
              ButtonPanel.add(UpButton);
              ButtonPanel.setLayout(new BoxLayout(ButtonPanel, BoxLayout.Y_AXIS));
                    JFrame mainFrame = new JFrame("GUI for Circle Drawing");
              mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
                    mainFrame.add(ButtonPanel);
                    mainFrame.pack();
              mainFrame.setVisible(true);
         public static void main(String [] args)     {
              GUI intf = new GUI();
              intf.drawframe();
    }and the DrawCircle Class is
    import java.awt.*;
    import javax.swing.*;
    public class DrawCircle extends JPanel{
         private int x, y, r;
            DrawCircle circle = new DrawCircle(100, 100, 50);
         public DrawCircle( int x , int y , int r){
              this.x = x;
              this.y = y;
              this.r = r;
         public int getR(){
              return r;
         public int getX(){
              return x;
         public int getY(){
              return y;
         public void setX(int x)     {
              this.x = x;
                    repaint();
         public void setY(int y)     {
              this.y = y;
                    repaint();
         public void setR(int r)     {
              this.r = r;
                    repaint();
         public void paint(Graphics g){
              g.clearRect(0,0,400,400);
                    g.drawOval(x-r, y-r, r*2, r*2);
            public void up() {
              circle.setY(circle.getY() -10);
            public void down() {
                    circle.setY(circle.getY() +10);
            public void right() {
                    circle.setX(circle.getX() +10);
            public void left() {
                    circle.setX(circle.getX() -10);
            public void increase() {
                    circle.setR(circle.getR() +10);     
            public void decrease() {
                    circle.setR(circle.getR() -10);     
              

    The problem is that you're constructing a new DrawCircle each time you construct a new DrawCircle, resulting in infinite recursion causing a stack overflow.
    This line:DrawCircle circle = new DrawCircle(100, 100, 50);in your DrawCircle class is causing the problem, do you need it? Remove it and replace references to 'circle' in the class with 'this'.

  • Jbutton, listener and so

    hi!
    When I press my Jbutton, it steps to it's actionlistener, this is ok. :) But in the first part of the AListener's source I want to put a new JPanel into my window(frame etc), containing 'please wait, work is in progress' or so. And after this code I call other functions which does many stuff which needs time and so, and when they're finished I want to put the original Panel back to the window. My main problem is, that somehow it doesn't put my 'please-wait' panel into the frame. However until the whole progress is done, the button keeps 'clicked' (it's color is grey), and when the progrss is done, then i get my original panel back. So I hope I made myself clear, pls help me.
    thanks
    athalay
    So before the much-time-needed things I want to put up a please-wait-panel, and when they're done, I want it to be removed. (Or put a red circle somewhere, when it's during progress, and put a green one when it's done etc...)

    Is there a reason that you want to use a JPanel instead of a modal JDialog or JProgressBar?
    It's hard to tell what the problem is, but it might make a difference on how you're putting the new panel in the frame. Have you tried removing the old panel and then adding the new one, or are you just trying to add the new one on top? I'm not sure if this makes a difference, but it could. Also, running all of your other methods in a Thread might help too so you have more control over what they're doing. It's easier to get them to yeild some processing to repaint and stuff like that if it's in a thread.
    Also, search the Swing forum for answers too. I'm sure something like this has been asked before.
    If you want to know more about the JProgressBar, check this out:
    http://java.sun.com/docs/books/tutorial/uiswing/components/progress.html

  • Create a object in form of circle, line, triangle or other shapes

    i am trying to make a program that creates simple objects, its just a hobby. the problem is i am trying to make an object that is only a line(for now). i mean i want to have an object that can be in a shape of anything in any angle. i like to be able to create a straight line from top left corner to bottom right corner, but i do not want to draw it, i want it to be an object like JButton but in different shapes. how ever i cannot do that. i have already wrote a little test program to show every one what i have, it s not my actual code just a sample.
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JButton;
    import javax.swing.JLayeredPane;
    import java.awt.BorderLayout;
    import javax.swing.JLabel;
    import java.awt.Color;
    import javax.swing.event.MouseInputListener;
    import java.awt.event.MouseEvent;
    import javax.swing.JComponent;
    import javax.swing.AbstractButton;
    import java.awt.Graphics;
    import java.awt.Dimension;
    import java.awt.Polygon;
    import java.awt.Graphics2D;
    import java.awt.BasicStroke;
    import java.awt.RenderingHints;
    import java.awt.geom.Area;
    public class FractalTest extends JFrame
         public static final int H=600;
         public static final int W=600;
         public static final Dimension dim = new Dimension(H,W);
         private int[] joinInt = new int[]{BasicStroke.JOIN_MITER,BasicStroke.JOIN_ROUND,BasicStroke.JOIN_BEVEL};
         private int[] capInt = new int[]{BasicStroke.CAP_BUTT,BasicStroke.CAP_ROUND,BasicStroke.CAP_SQUARE};
         public FractalTest(){
              super("Test");
                    //two test lines
              Polygon p = new Polygon();
              p.addPoint(150,150);
              p.addPoint(450,450);
              Polygon s = new Polygon();
              s.addPoint(450,150);
              s.addPoint(150,450);
              setBackground(Color.YELLOW);
              setLayout(new BorderLayout());
                    //status bar at buttom
              JLabel info = new JLabel("info");
                    //creating JPanel holder of lines
              JPanelCanvas test = new JPanelCanvas();
              test.setBackground(Color.BLACK);
              test.setSize(dim);
              test.setLayout(new BorderLayout());
                    //creating lines
              TestComponent t1 = new TestComponent(p,2f,"Polygon P");
              TestComponent t2 = new TestComponent(s,5f,"Polygon S");
                    //setting JLables for status info
              t1.setInfoDisplay(info);
              t2.setInfoDisplay(info);
              test.setInfoDisplay(info);
              test.add(t1,BorderLayout.CENTER);
              test.add(t2,BorderLayout.CENTER);
              add(test,BorderLayout.CENTER);
              add(info,BorderLayout.SOUTH);
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              setSize(dim);
              setVisible(true);
              repaint();
         public static void main(String[] args){new FractalTest();}
         private class TestComponent extends AbstractButton implements MouseInputListener
              private float thickness;
              private Polygon polygon;
              private String name=null;
              private JLabel jl=null;
              public TestComponent(Polygon p,float t,String name){
                   super();
                   thickness=t;
                   polygon=p;
                   setContentAreaFilled(false);
                   this.name=name;
                   setSize(FractalTest.dim);
                   setVisible(true);
                   addMouseListener(this);
              public void paint(Graphics g){
                   super.paintComponent(g);
                   Graphics2D g2 = (Graphics2D)g;
                   g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
                   g2.setStroke(new BasicStroke(thickness,capInt[0],joinInt[0]));
                   g2.setPaint(Color.GREEN);
                   g2.drawPolygon(polygon);
              public boolean contains(int x, int y){
                   int Ax=polygon.xpoints[0];
                   int Ay=polygon.ypoints[0];
                   int Bx=polygon.xpoints[1];
                   int By=polygon.ypoints[1];
                   int m=(By-Ay)/(Bx-Ax);
                   int s1=(m<=0)?+1:-1;
                   int s2=(m<=0)?-1:+1;
                   Polygon p = new Polygon();
                   p.addPoint(Ax+1,Ay+(int)(s1*thickness));
                   p.addPoint(Bx+1,By+(int)(s1*thickness));
                   p.addPoint(Bx-1,By+(int)(s2*thickness));
                   p.addPoint(Ax-1,Ay+(int)(s2*thickness));
                   return p.contains(x,y);
              public void setInfoDisplay(JLabel jl){this.jl=jl;}
              public void mouseEntered(MouseEvent e){jl.setText(name);}
              public void mouseExited(MouseEvent e){jl.setText("Polygon");}
              public void mouseDragged(MouseEvent e){}
              public void mouseMoved(MouseEvent e){}
              public void mouseClicked(MouseEvent e){}
              public void mousePressed(MouseEvent e){}
              public void mouseReleased(MouseEvent e){}
         private class JPanelCanvas extends JPanel implements MouseInputListener
              private JLabel jl;
              public JPanelCanvas(){}
              public void setInfoDisplay(JLabel jl){this.jl=jl;}
              public void mouseEntered(MouseEvent e){jl.setText("Canvas");}
              public void mouseExited(MouseEvent e){jl.setText("info");}
              public void mouseDragged(MouseEvent e){}
              public void mouseMoved(MouseEvent e){}
              public void mouseClicked(MouseEvent e){}
              public void mousePressed(MouseEvent e){}
              public void mouseReleased(MouseEvent e){}
    }if u see the code, the problem is each of the lines are covering the hole frame not just the green line, and i have to use the contains() method to limit the function but i do not want to do that. i just want it to be an object with out need of drawing any lines. just creating and object with the background color. so for example a JPanel in circular form that is only a circle no extra area around it.
    if u run the application and run it u will see the JPanel behind the green lines is not accessible by the mouse, the status JLabel shows the name of object can be reached by mouse at the moment and canvas(JPanel) will never be invoked. if the mouse is still on line objects the status name will stay on Polygon and it never changes to canvas.
    thanks everyone in advance

    Hi,
    try searching [www.java2s.com].plenty of sample programs are available.I have a faint memory of seeing a code that loads image files in desired placehoders like polygons n stuff. I guess you could replace the image component by some other component. Hope this helps

  • Problem with JButtons Text field not updating

    Im working on a program (which has its full code included below incase its part of the problem) which wants to change a Jbutton's name during a program. The way I'm trying to make it change is by having a string, "test", be called "before update". then have the jbuttons text equal test. then, in an actionlistener, it changes string test to equal "after update". This doesn't update the Jbuttons text.
    I don't get any errors when I press the button, but the buttons name is not updating. Whats causing the buttons name not to be updated?
    Thanks for help in advance.
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*; 
    public class TicTac extends JFrame {
    public int Teamplaying = 0;
    public int CrossA, CrossB, CrossC, CrossD, CrossF, CrossG, CrossH, CrossI, CircleA, CircleB, CircleC, CircleD, CircleE, CircleF, CircleG, CircleH, CirclI, TLB, TMB, TRB, MLB, MMB, MRB, LLB, LMB, LRB = 0;
    String test = "Before Update";
        public TicTac() {
             JPanel TicTac = new JPanel();
             TicTac.setLayout(new GridLayout(3,4));
                  TicTac.add(new JButton(test));
                  TicTac.add(new JLabel("a"));
                  TicTac.add(new JLabel("a"));
                  TicTac.add(new JLabel("a"));
                  TicTac.add(new JLabel("a"));
                  TicTac.add(new JLabel("a"));
                  TicTac.add(new JLabel("a"));
                  TicTac.add(new JLabel("a"));
                  TicTac.add(new JLabel("a"));
                  TicTac.add(new JLabel("a"));
                  TicTac.add(new JLabel("a"));
                  TicTac.add(new JLabel("a"));
                  TicTac.add(new JLabel("a"));
                  TicTac.add(new JLabel("a"));
                  setContentPane(TicTac);
             pack();
             setTitle("Add Numbers Together TicTac");
             setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             setLocationRelativeTo(null);
        class TopLeftBox implements ActionListener {
             public void actionPerformed(ActionEvent e) {
             String test = "After update";
             if (Teamplaying == 0) {
                  CrossA = CrossA + 1;
                  CrossD = CrossD + 1;
                  CrossG = CrossG + 1;
             else {
                  CircleA = CircleA + 1;
                  CircleB = CircleB + 1;
         public static void main(String[]args) {
        TicTac Toe = new TicTac();
        Toe.setVisible(true);
    }

    1) Strings are immutable meaning you can't change them.
    2) Even if you could, the two test strings are completely different variables.
    3) To change JButton text, you should call its setText method.
    4) For a JButton to perform an action on button press, it needs to have an actionlistener added to it via the addActionListener(...) method.
    5) Please read, study, and review the Sun Swing tutorials. You will benefit greatly from having a solid foundation in Swing basics before you try coding in Swing.
    Good luck.
    Edit: a small example code (SSCCE, if you will):
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class Frame extends JFrame
        public Frame()
            JPanel panel = new JPanel();
            JButton button = new JButton("Before Update");
            button.addActionListener(new ButtonListener()); // add actionlistener here
            panel.add(button);
            setContentPane(panel);
            pack();
            setTitle("Frame");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setLocationRelativeTo(null);
        private class ButtonListener implements ActionListener
            public void actionPerformed(ActionEvent e)
                // get the button that called this action
                JButton button = (JButton)e.getSource();
                // update the button's text
                button.setText("After update");
        public static void main(String[] args)
            SwingUtilities.invokeLater(new Runnable()
                @Override
                public void run()
                    new Frame().setVisible(true);               
    }Edited by: Encephalopathic on Apr 28, 2008 9:26 PM

  • Different Shapes for JButtons

    Hello everyone,
    Can anyone tell me how I can create JButtons in different shapes, like circles/ovals? I know we can use setSize, but this will not curve the edges. Any ideas?
    Thanks,
    BJ

    Do can do, see API..... You will need to create your own custom control by displaying a graphic with the rounded image. Search forum for displaying an image.

  • Getting a circle to become a button

    I have an image of a circle I was wondering if anyone knew how I could make this a button?
    Ellipse2D.Double head1 = new Ellipse2D.Double( 80, 30, 65, 100 );
          graphics2D.setPaint( Color.red );
          graphics2D.fill(head1);

    you can subclass a JButton and put the code above in the paint method

  • Adding a circle to an certain panel on the screen.

    Hi guys (and gals),
    How hard can it be to add a circle to a place on the appliction with out the whole sceen (inc lable, buttons ect) being overwritten with grey and the circle it top left! :-) But I am pulling my hair out over this one. I would like to add it to a panel if poss? (or can these only have awt things added to them?)
    Thanks everybody.
    Tom
    Here is the code :
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import java.awt.geom.*;
    import java.awt.event.MouseEvent;
    import com.borland.jbcl.layout.*;
    * <p>Title: </p>
    * <p>Description: </p>
    * <p>Copyright: Copyright (c) 2002</p>
    * <p>Company: </p>
    * @author unascribed
    * @version 1.0
    public class Frame1_AboutBox extends JDialog implements ActionListener, MouseListener {
    Ellipse2D circle = new Ellipse2D.Double();
    JPanel panel1 = new JPanel();
    JPanel panel2 = new JPanel();
    JPanel insetsPanel1 = new JPanel();
    JPanel insetsPanel2 = new JPanel();
    JPanel insetsPanel3 = new JPanel();
    JButton button1 = new JButton();
    JLabel imageLabel = new JLabel();
    JLabel label1 = new JLabel();
    JLabel label2 = new JLabel();
    JLabel label3 = new JLabel();
    JLabel label4 = new JLabel();
    BorderLayout borderLayout2 = new BorderLayout();
    FlowLayout flowLayout1 = new FlowLayout();
    GridLayout gridLayout1 = new GridLayout();
    String product = "LED-MAX";
    String version = "1.0";
    String copyright = "Copyright (c) 2002 Tom Coombs";
    String comments = "Beta";
    XYLayout xYLayout1 = new XYLayout();
    XYLayout xYLayout2 = new XYLayout();
    JPanel jPanel1 = new JPanel();
    XYLayout xYLayout3 = new XYLayout();
    public Frame1_AboutBox(Frame parent) {
    super(parent);
    enableEvents(AWTEvent.WINDOW_EVENT_MASK);
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    pack();
    //Component initialization
    private void jbInit() throws Exception {
    //imageLabel.setIcon(new ImageIcon(Frame1_AboutBox.class.getResource("[Your Image]")));
    this.setTitle("About");
    this.getContentPane().setLayout(xYLayout2);
    this.setResizable(false);
    panel1.setLayout(xYLayout1);
    panel2.setLayout(borderLayout2);
    insetsPanel1.setLayout(flowLayout1);
    insetsPanel2.setLayout(flowLayout1);
    insetsPanel2.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
    gridLayout1.setRows(4);
    gridLayout1.setColumns(1);
    label1.setText(product);
    label2.setText(version);
    label3.setText(copyright);
    label4.setText(comments);
    insetsPanel3.setLayout(gridLayout1);
    insetsPanel3.setBorder(BorderFactory.createEmptyBorder(10, 60, 10, 10));
    button1.setText("Ok");
    button1.addActionListener(this);
    jPanel1.setBackground(Color.lightGray);
    jPanel1.setLayout(xYLayout3);
    insetsPanel2.add(imageLabel, null);
    panel2.add(insetsPanel2, BorderLayout.WEST);
    this.getContentPane().add(panel1, new XYConstraints(0, 0, -1, -1));
    insetsPanel3.add(label1, null);
    insetsPanel3.add(label2, null);
    insetsPanel3.add(label3, null);
    insetsPanel3.add(label4, null);
    panel1.add(jPanel1, new XYConstraints(14, 105, 362, 139));
    panel2.add(insetsPanel3, BorderLayout.CENTER);
    insetsPanel1.add(button1, null);
    panel1.add(insetsPanel1, new XYConstraints(0, 263, 400, -1));
    panel1.add(panel2, new XYConstraints(0, 0, 400, -1));
    panel1.
    circle.setFrameFromCenter( 50, 50, 70, 70 );
    System.out.println ( "circle added" );
    addMouseListener(this);
    //Overridden so we can exit when window is closed
    protected void processWindowEvent(WindowEvent e) {
    if (e.getID() == WindowEvent.WINDOW_CLOSING) {
    cancel();
    super.processWindowEvent(e);
    //Close the dialog
    void cancel() {
    dispose();
    //Close the dialog on a button event
    public void actionPerformed(ActionEvent e) {
    if (e.getSource() == button1) {
    cancel();
    public void paint(Graphics g)
    Graphics2D g2d = (Graphics2D)g;
    g2d.draw(circle);
    public void mouseClicked(MouseEvent e){
    if (circle.contains(e.getX(), e.getY()))
    System.out.println ( "You clicked inside the circle" );
    else System.out.println ( "You MISSED the circle" );
    public void mousePressed(MouseEvent e){}
    public void mouseReleased(MouseEvent e){}
    public void mouseEntered(MouseEvent e){}
    public void mouseExited(MouseEvent e){}

    To draw the circle behind all controls, use
    public void paint(Graphics g) {
       Graphics2D g2d = (Graphics2D)g;
       g2d.draw(circle);
       super.paint(g);
    }Does this solve the problem?
    regards,
    Bram

  • Help with circle applet

    I don't know why my compiler keeps saying: cannot resolve symbol - method addActionListener (java.awt.event.ActionListener)
    Here is the code. There could be other errors too.
    import java.applet.Applet;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.geom.Ellipse2D;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    public class CircleApplet
        public CircleApplet()
            circle = new Ellipse2D.Double();
            final JTextField xCenterField = new JTextField(5);
            final JTextField yCenterField = new JTextField(5);
            final JTextField RadiusField = new JTextField (5);
            JButton drawButton = new JButton("Draw");
            class DrawButtonListener implements ActionListener
                public void actionPerformed(ActionEvent event)
                    double xCenter = Double.parseDouble(xCenterField.getText());
                    double yCenter = Double.parseDouble(yCenterField.getText());
                    double Radius = Double.parseDouble(RadiusField.getText());
                    circle.setFrame(xCenter, yCenter,
                    Radius, Radius);
            ActionListener listener = new DrawButtonListener();
            drawButton.addActionListner(listener);
            JLabel xCenterLabel = new JLabel("Input the x cordinate of the circle = ");
            JLabel yCenterLabel = new JLabel("Input the y cordinate of the circle = ");
            JLabel RadiusLabel = new JLabel("Input the raduis of the circle = ");
            JPanel panel = new JPanel();
            panel.add(xCenterLabel);
            panel.add(xCenterField);
            panel.add(yCenterLabel);
            panel.add(yCenterField);
            panel.add(RadiusLabel);
            panel.add(RadiusField);
            panel.add(drawButton);
            JFrame frame = new JFrame();
            frame.setContentPane(panel);
            frame.pack();
            frame.show();
        public void paint(Graphics g)
          Graphics2D g2 = (Graphics2D)g;
          g2.draw(circle);
        private Ellipse2D.Double circle;
    }

    Basically all I want to do is have the user be able to input the x and y coordinates of the circle and its radius. The problem is the book I have doesn't show any examples with circles. It only shows it with a rectangle and it already has the coordinates defined and the user just clicks on the empty applet screen to decided where the rectangle is going to go.
    here is the code with no syntax errors but won't display a circle after the user enter in the coordinates and radius.
    import java.applet.Applet;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.geom.Ellipse2D;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    public class Ex_p4
        public Ex_p4()
            circle = new Ellipse2D.Double();
            final JTextField xCenterField = new JTextField(5);
            final JTextField yCenterField = new JTextField(5);
            final JTextField RadiusField = new JTextField (5);
            JButton drawButton = new JButton("Draw");
            class DrawButtonListener implements ActionListener
                public void actionPerformed(ActionEvent event)
                    double xCenter = Double.parseDouble(xCenterField.getText());
                    double yCenter = Double.parseDouble(yCenterField.getText());
                    double Radius = Double.parseDouble(RadiusField.getText());
                    circle.setFrame(xCenter, yCenter,
                    Radius, Radius);
            ActionListener listener = new DrawButtonListener();
            drawButton.addActionListener(listener);
            JLabel xCenterLabel = new JLabel("Input the x cordinate of the circle = ");
            JLabel yCenterLabel = new JLabel("Input the y cordinate of the circle = ");
            JLabel RadiusLabel = new JLabel("Input the raduis of the circle = ");
            JPanel panel = new JPanel();
            panel.add(xCenterLabel);
            panel.add(xCenterField);
            panel.add(yCenterLabel);
            panel.add(yCenterField);
            panel.add(RadiusLabel);
            panel.add(RadiusField);
            panel.add(drawButton);
            JFrame frame = new JFrame();
            frame.setContentPane(panel);
            frame.pack();
            frame.show();
        public void paint(Graphics g)
          Graphics2D g2 = (Graphics2D)g;
          g2.draw(circle);
        private Ellipse2D.Double circle;
    }

  • JLabel and JButton

    I got my clock hands issue figured out, now I am trying to get a JButton and JLabels and JTextboxes in. I think I have the code for the labels right, but nothing shows up....any suggestions or places for me to look for help?
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.swing.*;
    public class clocky extends Frame {
         public static void main(String args[])
                   Frame frame = new clocky();
                   frame.addWindowListener(new WindowAdapter(){
                   public void windowClosing(WindowEvent we){
                             System.exit(0);
                   frame.setSize(300, 300);
                   frame.setVisible(true);
         private void createButton()
              JButton button = new JButton("Show Time");
         private void labels()
         JLabel hourLabel = new JLabel("Hour: ", JLabel.LEFT);
         hourLabel.setVerticalAlignment(JLabel.TOP);
         JLabel minLabel = new JLabel("Minute: ", JLabel.LEFT);
         minLabel.setVerticalAlignment(JLabel.TOP);
         final int centerX = 150;
         final int centerY = 180;
         Shape circle = new Ellipse2D.Double(50, 80, 200, 200);
         public void paint(Graphics g)
              Graphics2D ga = (Graphics2D)g;
              ga.draw(circle);
              //mins hand 6
              //ga.drawLine(150, 90, centerX, centerY); //00     +90 -90
              ga.drawLine(240, 180, centerX, centerY); //15      +90 +90
              //ga.drawLine(150, 270, centerX, centerY); //30      -90 +90
              //ga.drawLine(60, 180, centerX, centerY); //45      -90 -90
         //hrs hand 2.66666666
              ga.drawLine(150, 140, centerX, centerY); //00          +40 -40
              //ga.drawLine(190, 180, centerX, centerY); //15           +40 +40
              //ga.drawLine(150, 220, centerX, centerY); //30           -40 +40
              //ga.drawLine(110, 180, centerX, centerY); //45           -40 -40
    }

    >
    I got my clock hands issue figured out, now I am trying to get a JButton and JLabels and JTextboxes in. I think I have the code for the labels right, >You have methods to create buttons and labels, but nothing calls those methods, and even if hey were called, the created components are added to no container, and are lost at the end of the method.
    >
    ..but nothing shows up....>Wrong, the clock face painted directly to the JFrame shows. And that brings me to the second point. If you added those components to a frame that overrides paint, they will disappear. Once you override paint, it is up to you to paint everything that needs painting.
    This is why I would rethink your entire strategy. Override paintComponent(Graphics) in a ClockFace that extends JPanel. ClockFace should also set or override the preferred size. Then add the ClockFace object to another JPanel(s) (e.g. mainPanel) containing the JButton(s), JLabel(s) and ClockFace. Finally, add an EmptyBorder around mainPanel, and set it as the content pane of the JFrame.
    And please remember to use the 'code' tags to keep code formatted. To achieve that, select the code and click the CODE button seen on the Plain Text tab of the message posting form.

  • Drawing a circle

    Hi Friends,
    I have the following requirement. I am relatively new to Java
    1. Draw a circle
    2. Draw a rectange at the center of the circle
    3. Draw lines from the top edge of the circle to various points in the circle.
    4. Convert this graphic into a gif or a png image.
    Can this be achieved using Java 2D. If yes, can you pls provide me some sample code if possible.
    Thanks a lot for your help.

    You can also use the TextLayout class for displaying text.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.font.*;
    import java.awt.geom.*;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import java.net.*;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    public class GraphicsTest
        public static void main(String[] args)
            GraphicsPanel panel = new GraphicsPanel();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(panel.getUIPanel(), "North");
            f.getContentPane().add(panel);
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
    class GraphicsPanel extends JPanel
        Font font;
        String text;
        public GraphicsPanel()
            font = new Font("lucida bright regular", Font.PLAIN, 22);
            text = "centered text";
            setBackground(Color.white);
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            int w = getWidth();
            int h = getHeight();
            int cx = w/2;
            int cy = h/2;
            int dia = Math.min(w,h)*7/8;
            g2.setPaint(Color.blue);
            g2.draw(new Ellipse2D.Double(cx - dia/2, cy - dia/2, dia, dia));
            g2.setPaint(Color.orange);
            g2.draw(new Rectangle2D.Double(cx - dia/4, cy - dia/4, dia/2, dia/2));
            g2.setPaint(Color.blue);
            double theta = -Math.PI/2;
            double
                x1 = cx,
                y1 = cy + (dia/2) * Math.sin(theta),
                x2,
                y2 = cy + (dia/4) * Math.sin(theta);
            g2.draw(new Line2D.Double(x1, y1, x1, y2));
            theta = -Math.PI*3/4;
            x1 = cx + (dia/2) * Math.cos(theta);
            y1 = cy + (dia/2) * Math.sin(theta);
            x2 = cx + (dia/4) * Math.sqrt(2) * Math.cos(-Math.PI*5/4);
            y2 = cy + (dia/4) * Math.sqrt(2) * Math.sin(-Math.PI*5/4);
            g2.draw(new Line2D.Double(x1, y1, x2, y2));
            theta = -Math.PI/4;
            x1 = cx + (dia/2) * Math.cos(theta);
            y1 = cy + (dia/2) * Math.sin(theta);
            x2 = cx + (dia/4) * Math.sqrt(2) * Math.cos(Math.PI/4);
            y2 = cy + (dia/4) * Math.sqrt(2) * Math.sin(Math.PI/4);
            g2.draw(new Line2D.Double(x1, y1, x2, y2));
            g2.setFont(font);
            FontRenderContext frc = g2.getFontRenderContext();
            float textWidth = (float)font.getStringBounds(text, frc).getWidth();
            LineMetrics lm = font.getLineMetrics(text, frc);
            float x = (w - textWidth)/2;
            float y = (h + lm.getHeight())/2 - lm.getDescent();
            g2.drawString(text, x, y);
        public JPanel getUIPanel()
            JButton save = new JButton("save");
            save.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    saveImage();
            JPanel panel = new JPanel();
            panel.add(save);
            return panel;
        private void saveImage()
            int w = getWidth();
            int h = getHeight();
            BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2 = bi.createGraphics();
            paint(g2);
            g2.dispose();
            try
                ImageIO.write(bi, "png", new File("test.png"));
            catch(IOException ioe)
                System.out.println("IOE: " + ioe.getMessage());
    }

Maybe you are looking for

  • !! Projects VANISHED. Complete iMovie failure. Genius Bar at a loss. HELP!!

    I bought a brand new iMac 2.4 Ghz two weeks ago, SPECIFICALLY so I could "upgrade" to imovie 08 and cut movies of my son. iMovie worked FLAWLESSLY for the first 10 days, no problems whatsoever. I created several projects, using video clips from my iP

  • Creative cloud is annoying me.

    Firstly, the things you need to know about the problem Im on an iMac 27" running 10.9.1 I really want my CS 6 apps to update, because they need to update first before they can run I really dont want to re-install it I really cant wait for an answer S

  • PM Order with External Service PR Currency

    When we requisition an External Service through the PM Order using control key PM03, the system automatically generates the PR for the selected external service. The currency for this PR is set to the default currency automatically and we are unable

  • Viewing flash web content on N97

    I've just got myself the new N97 (love it, btw). The web browsing is far better than what it was on the N95. (personal opinion). The only problem: I can't view flash web content. I can find the Flash player, but I'm talking about embedded flash video

  • What are the alternate methods of transferring data between apps built on ios

    Hi All, What could be the alternate methods of transferring data between apps built on ios? Please comment. Thanks Pankaj