2016-01-24 61 views
1

我在更改用戶使用JFrame單擊java菜單項時顯示的形狀時出現問題。任何人都可以建議我如何解決這個問題?下面是我的代碼:如何在java中單擊菜單項時更改形狀

public class PlayingWithShapes implements ActionListener 
{ 
    protected JMenuItem circle = new JMenuItem("Circle"); 
    protected String identifier = "circle"; 
    public PlayingWithShapes() 
    { 
    JMenuBar menuBar = new JMenuBar(); 
    JMenu shapes = new JMenu("Shapes"); 
    JMenu colors = new JMenu("Colors"); 

    circle.addActionListener(this); 
    shapes.add(circle); 
    menuBar.add(shapes); 
    menuBar.add(colors); 
    JFrame frame = new JFrame("Playing With Shapes"); 
    frame.setSize(600,400); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setVisible(true); 
    frame.add(new Shapes()); 
    frame.setJMenuBar(menuBar); 
} 

public static void main(String args[]) 
{ 
    Runnable runnable = new Runnable() { 
     @Override 
     public void run() { 
      new PlayingWithShapes(); 
     } 
    }; 
    EventQueue.invokeLater(runnable); 

} 

我要上一圈菜單項

@Override 
public void actionPerformed(ActionEvent click) { 

    if(click.getSource() == circle){ 
     Shapes shape = new Shapes(); 

    } 
} 

public class Shapes extends JPanel 
{ 

我怎樣才能再調用矩形點擊時改變形狀的圓?

@Override 
    public void paintComponent(Graphics shapes) 
    { 
     circle(shapes); 
    } 

    public void circle(Graphics shapes) 
    { 
     shapes.setColor(Color.yellow); 
     shapes.fillOval(200,100, 100, 100); 
    } 
    public void rectangle(Graphics shapes) 
    { 
     shapes.setColor(Color.MAGENTA); 
     shapes.fillRect(200,100,100,100); 
    } 

} 

} 

任何幫助,非常感謝。

+0

問題標籤改變了:你的問題,真可謂無關的NetBeans(IDE的)和所有與Swing做(圖形庫)。 –

回答

1

建議:

  • 不要你的actionPerformed中創建一個新的形狀的JPanel,因爲這實現了什麼。
  • 而是在actionPerformed中改變類的字段的狀態,並將繪圖基於paintComponent方法在該字段所持有的狀態中。例如,如果只有兩種不同類型的形狀,上面的字段可能只是一個布爾值,可能被稱爲drawRectangle,並且在actionPerformed中,您會將其更改爲true或false,並呼叫repaint();。然後在你使用paintComponent中的一個if塊,如果它是真的,則繪製一個Rectangle,如果沒有,則繪製一個橢圓。
  • 如果您想要繪製多個不同形狀的能力,請創建一個枚舉並在該枚舉類型的字段上方討論該字段。然後在paintComponent中使用switch語句來決定繪製哪個形狀。
  • 如果你想同時顯示不同的形狀,那麼你需要創建一個Shape集合,如ArrayList<Shape>,並將Shape-derived對象添加到這個集合中,然後在for循環中遍歷它paintComponent使用Graphics2D對象繪製每個Shape。我不認爲你現在需要這個。
  • 不要忘記在您的方法覆蓋內調用super.paintComponent(g);

@Override 
public void paintComponent(Graphics g) { 
    super.paintComponent(g); 
    if (drawRectangle) { 
     rectangle(g); 
    } else { 
     circle(g); 
    } 
} 
+0

謝謝你的回覆。是的,我正在考慮布爾,但可悲的是我有4個形狀。你能舉一個枚舉的例子嗎? –

+0

@JayGorio:先嚐試一下,然後告訴我們你的嘗試。您不會後悔嘗試,我相信您可以做到這一點。 –

+0

謝謝,但我得到這個錯誤; super.paintComponent(); –

相關問題