2016-09-13 73 views
-1
import javax.swing.*; 
import java.awt.*; 

public class CGLinesGrid extends JFrame { 
    public CGLinesGrid() { 
     super ("Exercise 4"); 
     setSize (500, 500); 
     setVisible(true); 
    } 

    public void paint (Graphics g) { 

     for (int i = 1; i<=9 ; i++) { 
      g.drawLine(70, 30+i*40, 390, 30+i*40);    
      g.drawLine(30+i*40, 70, 30+i*40, 390); 
     } 
     for (int i = 1; i<=9 ; i++) { 
      g.drawOval(70, 20+i*40, 40, 10+i*30); 
     } 
    } 

    public static void main (String[] args) { 
     CGLinesGrid draw = new CGLinesGrid(); 
     draw.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    } 
} 
+2

这是什么问题? – ChiefTwoPencils

+0

我创建了一个8x8网格。我想把椭圆放在它们里面。你能帮我吗? :( –

+1

不要重写'paint',你应该重写'paintComponent'方法 – RealSkeptic

回答

0

找到解决方案之前的几件事情。

首先,由于@RealSkeptic说,从来没有从您的组件内调用paint()方法。始终使用paintComponent(Graphics g)方法。

其次,调用paintComponent()方法时,一定要调用的paintComponent方法使用

super.paintComponent(g); 

第三它的父类的的paintComponent()方法不应该直接在JFrame调用,使用JPanel

现在解决方案。

你想要一个8x8的正方形网格,每个正方形都有一个圆圈。

最简单的方法是使用一个JPanel,它有一个GridLayout并将64 JLabel添加到它。然后,每个JLabel将在该广场上打印一个正方形和圆圈。

从底部开始,我们需要创建一个打印出正方形和圆形的JLabel:

class SquareWithCircleLabel extends JLabel { 
    @Override 
    public void paintComponent(Graphics g) { 
     //notice the call to its parent method 
     super.paintComponent(g); 

     //draw the square and circle 
     g.drawRect(0, 0, this.getWidth(), this.getHeight()); 
     g.drawOval(1, 1, this.getWidth() - 1, this.getHeight() - 1); 
    } 
} 

接下来我们需要一个JPanel包含在8×8格所有这些JLabel S:

class PaintPanel extends JPanel { 
    PaintPanel() { 
     //give it a 8 x 8 GridLayout 
     setLayout(new GridLayout(8, 8)); 

     //add 81 labels to the JPanel and they will automatically be formatted into a 9 x 9 grid because of our GridLayout 
     for (int i = 0; i < 64; i++) { 
      add(new SquareWithCircleLabel()); 
     } 
    } 
} 

现在我们需要在构造函数中只是这个JPanel添加到我们的JFrame

add(new PaintPanel()); 

完整的代码如下所示:

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

public class CGLinesGrid extends JFrame { 
    public CGLinesGrid() { 
     super ("Exercise 4"); 
     setSize (500, 500); 
     add(new PaintPanel()); 
     setVisible(true); 
    } 

    public static void main (String[] args) { 
     CGLinesGrid draw = new CGLinesGrid(); 
     draw.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    } 

    class PaintPanel extends JPanel { 
     PaintPanel() { 
      setLayout(new GridLayout(9, 9)); 
      for (int i = 0; i < 81; i++) { 
       add(new SquareWithCircleLabel()); 
      } 
     } 
    } 

    class SquareWithCircleLabel extends JLabel { 
     @Override 
     public void paintComponent(Graphics g) { 
      super.paintComponent(g); 

      g.drawRect(0, 0, this.getWidth(), this.getHeight()); 
      g.drawOval(1, 1, this.getWidth() - 1, this.getHeight() - 1); 
     } 
    } 

} 
+0

Sir Yitzih,你给的代码doesn' t工作在我的Java?Idk为什么。在添加的2个类中存在错误 –

+0

@DarrelDelaCruz你得到了什么错误? – yitzih

+0

它说2个类的层次结构不一致:( –