开发者

problem getting the grid right and no background Color

This is my code that attempts to make 400 x 400 grid but outputs the following:

problem getting the grid right and no background Color

No doubt this not a 400 x 400 grid.

I am unable to detect where i have got my logic wrong. I have highlighted the part responsible for drawing.

import javax.swing.*;
import java.awt.*;

class tester1 extends JPanel {
 tester1() {
  setPreferredSize(new Dimension(400,400));
  this.setBackground(Color.black);
  JFrame fr = new JFrame();
  fr.add(this);
  fr.pack();
  fr.setVisible(true);
  fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  repaint();
 }

  public void paintComponent(Graphics g) {   // <----- part responsible for drawing
   g.setColor(Color.red); 
     for(int x = 0 ; x <= 400 ; x += 10 ) {
       g.drawLine( x , 0 , 400 , x );
     }
     for(int y = 0 ; y <= 400 ; y += 10 ) {
       g.drawLine( y , 0 , y , 400 );
     }
  }   开发者_开发知识库// <---- till here

  public static void main(String args[]) {
     new tester1();
  }
 }

What mistake have I made in paintComponent method ?

Also in the output why don't I get BLACK color as the background, when I have written this.setBackground(Color.black)?


Call super.paintComponent() before you do any painting in order for the background to be painted black.

As far as the lines go: You have your x and y coordinated mixed up. It should be: (int x1, int y1, int x2, int y2)

Specifically look at:

 g.drawLine( x , 0 , 400 , x );

And ask yourself why you are varying one X and one Y and holding the other X and other Y constant.

Where as here:

 g.drawLine( y , 0 , y , 400 );

You are holding both Ys constant and changing both of the Xs (Hint: your other statement should look like this one.).


I think your current output is v. pretty, but anyway..

import javax.swing.*;
import java.awt.*;

class tester1 extends JPanel {
 tester1() {
  setPreferredSize(new Dimension(400,400));
  this.setBackground(Color.black);
  JFrame fr = new JFrame();
  fr.add(this);
  fr.pack();
  fr.setVisible(true);
  fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  repaint();
 }

  public void paintComponent(Graphics g) {
   // as mentioned by jzd
   super.paintComponent(g);
   g.setColor(Color.red);
     for(int x = 0 ; x <= getWidth() ; x += 10 ) {
       // as mentioned by ditkin
       g.drawLine( x , 0 , x , getHeight() );
     }
   g.setColor(Color.yellow);
     for(int y = 0 ; y <= getHeight() ; y += 10 ) {
       // also this
       g.drawLine( 0 , y , getWidth() , y );
     }
  }

  public static void main(String args[]) {
     new tester1();
  }
 }

BTW - unless you call setResizable(false) on the frame, use getHeight() / getWidth() when painting.

Screenshot

problem getting the grid right and no background Color


I believe that this line:

g.drawLine( x , 0 , 400 , x );

Should read:

g.drawLine( x , 0 , x, 400);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜