gpt4 book ai didi

java - java中点击菜单项时如何改变形状

转载 作者:行者123 更新时间:2023-11-30 07:38:51 25 4
gpt4 key购买 nike

当用户使用 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中更改类的字段的状态,并根据该字段所保存的状态在paintComponent方法中进行绘图。
  • 例如,如果您只有两种不同类型的形状,则上述字段可以只是一个 boolean 值,可能称为 drawRectangle ,并在 actionPerformed 中将其更改为 true 或 false 并调用 repaint(); 。然后,您可以在paintComponent 中使用if block ,如果为真,则绘制一个矩形,如果不是,则绘制一个椭圆形。
  • 如果您希望能够绘制多个不同的形状,请创建一个枚举并将上面讨论的字段设为此枚举类型的字段。然后在paintComponent中使用switch语句来决定绘制哪个形状。
  • 如果您想同时显示不同的形状,那么您需要创建一个 Shape 集合,例如 ArrayList<Shape>并将 Shape 派生对象添加到此集合,然后使用 Graphics2D 对象在 PaintComponent 内的 for 循环中对其进行迭代,以绘制每个 Shape。我认为您现在不需要这个。
  • 别忘了调用 super.paintComponent(g);在您的方法重写中。

即,

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

关于java - java中点击菜单项时如何改变形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34977621/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com