2016-09-13 70 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個類的層次結構不一致:( –