2013-01-22 30 views
0

我想讓用戶選擇他們想要在我的GUI上繪製的形狀。我有一個按鈕的選擇:圓形,方形和矩形。我的actionListener在向我的控制檯打印字符串時起作用,但它不會在我的GUI上顯示該形狀。我如何使用actionCommand在我的面板上繪製該形狀。這個actionPerformed如何與我的按鈕交互?

public void paintComponent(Graphics g) { 
    g2D = (Graphics2D) g; 
    //Rectangle2D rect = new Rectangle2D.Double(x, y, x2-x, y2-y); 
    //g2D.draw(rect); 
     repaint(); 
} 

public void actionPerformed(ActionEvent arg0) { 
    if(arg0.getActionCommand().equals("Rect")){  
     System.out.println("hello"); 
     Rectangle2D rect = new Rectangle2D.Double(x, y, x2-x, y2-y); 
     g2D.draw(rect); //can only be accessed within paintComponent method 
     repaint(); 
    } 

回答

3

如果你首先畫你的矩形,然後要求重繪矩形將消失。

您應該將您的新形狀存儲在一個臨時變量中並將其呈現在paintComponent中。

private Rectangle2D temp; 

// inside the actionPerformed 
    temp = new Rectangle2D.Double(x, y, x2-x, y2-y); 
    repaint(); 

// inside the paintComponent 
    if(temp != null) { 
     g2D.draw(temp); 
    } 
2

將rect設置爲field nto局部變量。在actionPerformed創建適當的rect並調用repaint()。然後調用paintComponent()。它應該是這樣的

public void paintComponent(Graphics g) { 
    g2D = (Graphics2D) g; 
    g2D.draw(rect); 
} 
+1

也考慮'super.paintComponent(g)'。 – trashgod