当用户使用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);
}
我想在点击圆圈menuItem
时将形状更改为圆形@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 :(得分:1)
建议:
drawRectangle
,并且在actionPerformed中您将其更改为true或false并调用{{1 }}。然后在paintComponent中使用if块,如果是true则绘制一个Rectangle,否则使用椭圆。repaint();
,并将Shape派生的对象添加到此集合中,然后在其中迭代paintComponent中的for循环使用Graphics2D对象绘制每个Shape。我认为你现在不需要这个。ArrayList<Shape>
。即,
super.paintComponent(g);