单击 java 中的菜单项时如何更改形状

how to change shapes when clicking menu items in java

我在更改用户使用 JFrame 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);
    }

}

}

非常感谢任何帮助。

建议:

  • 不要在您的 actionPerformed 中创建一个新的 Shapes JPanel,因为这没有任何效果。
  • 而是在 actionPerformed 中更改 class 字段的状态,并使 paintComponent 方法中的绘图基于该字段保持的状态。
  • 例如,如果您只有两种不同类型的形状,上面的字段可以简单地是一个布尔值,也许称为 drawRectangle,并且在 actionPerformed 中您将其更改为 true 或 false 并调用 repaint();。然后在 paintComponent 中使用 if 块,如果为真则绘制矩形,否则为椭圆形。
  • 如果你想拥有绘制多个不同形状的能力,创建一个枚举并将上面讨论的字段设为该枚举类型的字段。然后在 paintComponent 中使用 switch 语句来决定绘制哪个形状。
  • 如果你想同时显示不同的形状,那么你需要创建一个 Shape 的集合,例如 ArrayList<Shape> 并将 Shape-derived 个对象添加到这个集合中,然后使用 Graphics2D 对象在 paintComponent 内的 for 循环中迭代它以绘制每个 Shape。我认为你现在不需要这个。
  • 不要忘记在您的方法覆盖中调用 super.paintComponent(g);

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