2016-01-24 59 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(); –

相关问题