1

I made a class called Robit (bad spelling on purpose) and it defines a square with the paint(Graphics g) method. I'm extending JFrame and all that works fine i just cant get the squares to paint

import java.awt.*;

public class Robit {

int[] location = new int[4];
double[] vectors = new double[2];
Color mainColor;

    public Robit(Color color, int x) {
        mainColor = color;
        switch (x) {
            case 0:
                location[0] = 50;
                break;
            case 1:
                location[0] = 700;
                break;
            default:
                location[0] = 350;
                break;
        }
        location[1] = 400;
        location[2] = 50;
        location[3] = 50;

    }

    public void paint(Graphics g) {
        g.setColor(mainColor);
        g.fillRect(location[0], location[1], location[2], location[3]);

    }
    public int getX() {
        return location[0];
    }

    public int getY() {
        return location[1];
    }

}

`thats the class im instantiating, heres where i make it import java.awt.Color; import javax.swing.*;

public class Frame extends JFrame {
    public Frame(){
        setLayout(null);


        Robit r1 = new Robit(Color.red, 0);
        Robit r2 = new Robit(Color.blue, 1);


    }
}

and the main class

import javax.swing.JFrame;

public class App {

    public static void main(String[] args) {
        Frame f = new Frame();
        f.setSize(800, 450);
        f.setResizable(false);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);

    }
}
  • `setLayout(null);` Java GUIs have to work on different OS', screen size, screen resolution etc. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). `public class Frame extends JFrame..` That's a poor name for a custom class since there is a `java.awt.Frame`. How about `RobitsFrame` instead? – Andrew Thompson Feb 10 '15 at 00:44

1 Answers1

0

You are not calling the paint method on your Robit class. Try the following:

public class Frame extends JFrame {
   protected Robit r1;
   protected Robit r2;
   public Frame(){
       setLayout(null);

      r1 = new Robit(Color.red, 0);
      r2 = new Robit(Color.blue, 1);
   }

   public void paint(Graphics g)
   {
      super.paint(g);
      r1.paint(g);
      r2.paint(g); 
   }
}
Jayfray
  • 415
  • 3
  • 12