2014-02-28 104 views
0

我正試圖在JFrame內的JPanel內繪製矩形。我想使用paintComponents(Graphics g)方法並重寫它,但由於某種原因,矩形沒有像我期望的那樣出現在JPanel中。任何幫助,將不勝感激。如何在JPanel中繪製矩形

public class RectangleFrame extends JFrame implements ActionListener { 
    JPanel buttonPanel; 
    JButton saveImage; 
    JButton clearImage; 
    JCheckBox intersections; 
    JCheckBox union; 
    JPanel drawingArea; 



public RectangleFrame() 
{ 
    super(); 
    setTitle("Rectangles"); 
    setSize(600,600); 
    setResizable(false); 
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

    buttonPanel = new JPanel(); 
    buttonPanel.setBorder(BorderFactory.createLineBorder(Color.black)); 
    this.add(buttonPanel, BorderLayout.SOUTH); 

    intersections = new JCheckBox("Draw Intersections"); 
    buttonPanel.add(intersections); 

    union = new JCheckBox("Draw Union"); 
    buttonPanel.add(union); 

    saveImage = new JButton("Save Image"); 
    saveImage.setMargin(new Insets(0,0,0,0)); 
    buttonPanel.add(saveImage); 

    clearImage = new JButton("Clear Image"); 
    clearImage.setMargin(new Insets(0,0,0,0)); 
    buttonPanel.add(clearImage); 

    drawingArea = new JPanel(); 
    drawingArea.setBorder(BorderFactory.createLineBorder(Color.blue)); 
    this.add(drawingArea, BorderLayout.CENTER); 
} 
} 

     class RectanglePanel extends JPanel 
{ 
public RectanglePanel() 
{ 
    super(); 
} 



@Override 
public void paintComponent(Graphics g) 
{ 
    super.paintComponent(g); 

    g.setColor(Color.BLUE); 
    g.fillRect(25,25,100,30);  
} 


} 

這裏是一個單獨的類我的主要方法:

public class SwingRectangle 
{ 

/** 
* @param args 
*/ 
public static void main(String[] args) 
{ 
    // TODO Auto-generated method stub 
    RectangleFrame frame = new RectangleFrame(); 
    RectanglePanel panel = new RectanglePanel(); 
    frame.setVisible(true); 

} 

} 
+0

你在哪裏添加'RectanglePanel'到框架? –

+0

我相信你想要覆蓋的方法是paintComponent(Graphics g)(沒有's')。確保你再調用super.paintComponent(g)。 paintComponent(g)是JComponent上的一個方法。 paintComponents(g)是Container上的一個方法。 –

+0

在回答完成後刪除問題的新趨勢是什麼?我最近在SO上看過幾次。 – whiskeyspider

回答

4

你沒有添加RectanglePanel到你的框架。

drawingArea = new JPanel(); 

應該

drawingArea = new RectanglePanel(); 

其他景點:

  • 你仍然需要重寫paintComponent而不是通過paintComponents作爲@大衛建議,以便+1他
  • 面板創建在SwingRectangle未使用