2

单击按钮时,我想将矩形的形状更改为椭圆形。我必须在 actionPerformed 部分写什么代码?有没有其他方法可以轻松解决以下问题?

 
        public class Shapechange extends JFrame
        {
            public Shapechange()
            {
                setSize(300,400);
                setTitle("Shape Change");
                MyPanel pane=new MyPanel();
                add(pane);
            }
            public static void main(String[] args)
            {
                Shapechange s=new Shapechange();
                s.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                s.setVisible(true);
            }
        }
        class MyPanel extends JPanel 
        {
            JButton button;
            public  MyShape shape=new MyShape();
            public MyPanel()
            {
                button=new JButton("Click");
                add(button);
                button.addActionListener(new ActionListener() 
                {
                    @Override
                    public void actionPerformed(ActionEvent e) 
                    {
                      //what i do to chage shape from rect to oval
                    }
                });
            }
            @Override
            public void paintComponent(Graphics g)
            {
                shape.rectangledrawing(g);

} } class MyShape { public void rectangledrawing(Graphics g) { g.drawRect(100, 200, 250, 300 ); } public void ovaldrawing(Graphics g) { g.drawOval(100, 200, 250, 300); } }

提前致谢

4

1 回答 1

4

在您的代码中,您总是绘制矩形,尝试使用一些标志进行切换。示例代码:

public class Shapechange extends JFrame {
    public Shapechange() {
        setSize(300, 400);
        setTitle("Shape Change");
        MyPanel pane = new MyPanel(this);
        add(pane);
    }

    public static void main(String[] args) {
        Shapechange s = new Shapechange();
        s.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        s.setVisible(true);
    }
}

class MyPanel extends JPanel {
    JButton button;
    public MyShape shape = new MyShape();
    private boolean b = true;

    public MyPanel(final Shapechange shapechange) {
        button = new JButton("Click");
        add(button);
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                b = !b;
                shapechange.repaint();
            }
        });
    }

    @Override
    public void paintComponent(Graphics g) {
        if (b) {
            shape.rectangledrawing(g);
        } else {
            shape.ovaldrawing(g);
        }

    }
}

class MyShape {
    public void rectangledrawing(Graphics g) {
        g.drawRect(100, 200, 250, 300);
    }

    public void ovaldrawing(Graphics g) {
        g.drawOval(100, 200, 250, 300);
    }

}
于 2013-10-29T10:09:55.867 回答