Cody Berry
Cody Berry

Reputation: 263

Not sure how to use swing to draw rectangles

I am practicing for a test I have coming up and I am looking through some practice questions. I have come across a question that is challenging me more than the others. I am needing to write a method, using swing it seems, that creates 100 rectangles of a given width and varying heights found through simple mathematics. I have made my array that holds each height and I have my width set. How might I go about creating these rectangles using swing? I would prefer that this question be answered in a way that tries to push me in the right direction (i.e. try using JLabel or something of that nature) rather than doing it for me. How would I ever learn it that way? I may end up with some follow up questions as well. Here is the code that makes my Array for heights and sets my width. It is probably assumed but my parameters are in pixels.

public void paintComponent() {
   int[] heights = new int[100];
   int width = 10
   int initialHeight = 100;
   for (int i=0; i<100; i++) {
      int usedHeight = height - i;
      heights[i] = usedHeight;
   }

Again, please do not do it for me. I just need to be pointed in the right direction. I assume I will be using swing in some way to do this.

Upvotes: 3

Views: 157

Answers (3)

roippi
roippi

Reputation: 25954

General approach:

  • Make a JFrame with a JPanel

  • Give it a layout (something simple like a GridLayout will probably work for this)

  • Add the Components to your container (I'll point you towards Rectangle) (or you can just use JPanels and set their border/fill color)

One of the hardest things to learn in Swing is layout managers, so expect to spend some time bashing your head against that wall until it gives way. Prepare to have swing draw all the rectangles on top of one another, draw them in a single column, and not draw them at all. Probably not in that order.

Upvotes: 2

kajacx
kajacx

Reputation: 12939

OK, first, you have some bugs in your current code (assuming height is decreasing):

public void paintComponent() {
  int[] heights = new int[100];
  int width = 10;
  int initialHeight = 100;
  for (int i=0; i<100; i++) {
    heights[i] = initialHeight;
    initialHeight--;
    //also heights[i] = 100-i;
  }
}

When usedHeight was declared inside the cycle, it existed ony during one 'cycle' of the cycle.

Second, if you want to understand how swing works, download 5+- already working examples and figure it out from code (worked for me just fine).

Upvotes: 1

gustafc
gustafc

Reputation: 28865

Basically, what you want to do is subclass JComponent and override paintComponent. The Graphics object passed to it lets you do what you need (hint).

Upvotes: 3

Related Questions