Results 1 to 2 of 2
  1. #1
    Josisco is offline Member
    Join Date
    Oct 2010
    Posts
    2
    Rep Power
    0

    Default Keeping a graphic central

    Hi, I'm just trying some basic stuff with AWT and Swing. I've drawn a square and I want to have it placed in the centre. I've worked out where I think the centre should be but it seems some way off.

    Java Code:
    package testing;
    
    import javax.swing.JFrame;
    public class SquareViewer
    {
        public static void main(String[] args)
        {
            int FRAME_WIDTH = 300;
            int FRAME_HEIGHT = 300;
    
            JFrame frame = new JFrame();
            frame.setSize(FRAME_WIDTH,FRAME_HEIGHT);
            frame.setTitle("A Square");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
            SquareComponent component = new SquareComponent(frame.getWidth(),frame.getHeight());
            frame.add(component);
    
            frame.setVisible(true);
        }
    }
    Java Code:
    package testing;
    
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.geom.Rectangle2D;
    import javax.swing.JComponent;
    
    public class SquareComponent extends JComponent
    {
        private static int width, height;
        private static double x, y, w, h;
    
        SquareComponent(int w, int h)
        {
            width = w;
            height = h;
        }
    
        public void paintComponent(Graphics g)
        {
            Graphics2D g2 = (Graphics2D) g;
            Rectangle2D.Double square = new Rectangle2D.Double();
    
            w = width * 0.2;
            h = height * 0.2;
            if(w>h)
                w=h;
            else
                h=w;
            x = (width-w)/2;
            y = (height-w)/2;
    
            square.setRect(x,y,w,h);
            g2.draw(square);
        }
    }
    Any help would be appreciated :)

  2. #2
    Horcrux7 is offline Member
    Join Date
    Sep 2010
    Posts
    33
    Rep Power
    0

    Default

    The problem is that the size of the frame include also the size of the title and the border. It is not the size your SquareComponent. Use getSize() inside of SquareComponent instead of the size in the constructor.
    Volker Berlin
    www.inetsoftware.de

Similar Threads

  1. import javax.speech.Central
    By nassir in forum Advanced Java
    Replies: 5
    Last Post: 03-02-2010, 04:29 AM
  2. Problem with keeping values into an arrayList
    By Daniel Silvester in forum New To Java
    Replies: 0
    Last Post: 12-02-2009, 01:14 AM
  3. Java Keeping Text in One Place
    By xpngamer in forum New To Java
    Replies: 1
    Last Post: 04-09-2009, 06:27 AM
  4. Replies: 1
    Last Post: 03-23-2009, 03:08 PM
  5. Replies: 1
    Last Post: 08-27-2008, 04:27 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •