为什么我的线条画不出来?(代码如下)

小冷不冷 发布于 2012/05/13 10:57
阅读 497
收藏 0

我想画一个网格  但是怎么显示不出来?

 

import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Yard extends JFrame {
 private static final long serialVersionUID = 1L;
 
 private static final int ROWS = 150;
 private static final int COLS = 120;
 private static final int BLOCK_SIZE = 5;
 
 public static void main(String[] args) {
  new Yard().lunch();
 }
 
 public void lunch(){
  setLocation(260, 70);
  setSize((ROWS + 6)*BLOCK_SIZE, (COLS + 10)*BLOCK_SIZE);
  
  myJPanel mjp = new myJPanel();
  add(mjp);
  setVisible(true);
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 }
 
 class myJPanel extends JPanel{
  private static final long serialVersionUID = 1L;

  public myJPanel() {
   Canvas canvas = new Canvas();
   canvas.setSize(ROWS * BLOCK_SIZE, COLS * BLOCK_SIZE);
   canvas.setBackground(Color.GREEN);
   add(canvas,BorderLayout.CENTER);
  }
  
  public void print(Graphics g) {
   Color c = g.getColor();
   g.fillRect(0, 0,ROWS * BLOCK_SIZE, COLS * BLOCK_SIZE);
   g.setColor(Color.BLACK);
   
   for(int i = 1;i < ROWS;i++){
    g.drawLine(0, i*BLOCK_SIZE, COLS*BLOCK_SIZE, i*BLOCK_SIZE);
   }
   for(int i = 0;i < COLS;i++){
    g.drawLine(BLOCK_SIZE*i, 0, i*BLOCK_SIZE, ROWS*BLOCK_SIZE);
   }
   
   g.setColor(c);
  }
 }

}


 

加载中
0
Monkey
Monkey
public class NewClass {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(3);
        BufferedImage image = new BufferedImage(25, 25, BufferedImage.TYPE_INT_RGB);
        Rectangle rect = new Rectangle(0, 0, 25, 25);
        Graphics2D g = image.createGraphics();
        g.setColor(Color.GREEN);
        g.fill(rect);
        g.setColor(Color.BLACK);
        g.setStroke(new BasicStroke(0.5f));
        g.draw(rect);
        final TexturePaint paint = new TexturePaint(image, rect);
        frame.setContentPane(new JPanel() {

            public void paint(Graphics g) {
                super.paint(g);
                Graphics2D g2d = (Graphics2D) g;
                Paint paint1 = g2d.getPaint();
                g2d.setPaint(paint);
                g2d.fill(new Rectangle(0, 0, getWidth(), getHeight()));
                g2d.setPaint(paint1);
            }
        });
        frame.setVisible(true);
    }
}
0
JustForFly
JustForFly

将你的 public void print(Graphics g)  改为 public void  paintComponent (Graphics g)。

然后你会发现你的绿色背景色把你的网格遮挡了,你需要再去调整下你的代码。  

0
小冷不冷
小冷不冷
谢谢  我已经弄好了
返回顶部
顶部