java继承和多态

时间:2016-04-21 18:02:03

标签: java inheritance polymorphism

这是我的第一个问题,如果我犯错误,请道歉。 试图更好地理解oop(继承,多态,抽象)我想象下面的练习:在带有BorderLayout的JPanel中,我添加了一个JPanel,它包含两个JRadioButton和一个扩展JPanel的抽象面板。抽象小组可以指向2个不同的具体孩子......但它并没有像我预期的那样工作。 。当我选择控制台上的矩形按钮时,打印"矩形触发事件"但是矩形对象的paint组件没有被执行,当我选择控制台上的椭圆形按钮时,会打印出#34;椭圆形的火灾事件"和#34;画椭圆形画椭圆形"这意味着执行椭圆形按钮的paint组件。请帮我理解我做错了什么?为什么不执行矩形的paintComponent? 我再说一遍,我的目标是练习和理解oop,而不是绘制椭圆和矩形。 这是我的代码

public class MyGeometry extends JPanel{
private MyShape shape;
private JPanel shapeControl = new JPanel();
private JRadioButton rbtOval = new JRadioButton("Oval");
private JRadioButton rbtRectangle = new JRadioButton("Rectangle");

MyGeometry(){
    setLayout(new BorderLayout());
    // setting radio buttons
    ButtonGroup shapeButton = new ButtonGroup();
    shapeButton.add(rbtOval);
    shapeButton.add(rbtRectangle);
    rbtOval.setSelected(true);
    shapeControl.add(rbtOval);
    shapeControl.add(rbtRectangle);

    //Initialize shape to avoid null pointer exception
    final MyOval oval = new MyOval();
    final MyRectangle rectangle = new MyRectangle();
    shape = oval;

    //add components to the panel
    add(shapeControl, BorderLayout.NORTH);
    add(shape);

    //add event handling
    rbtOval.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            shape = oval;
            shape.repaint();
            System.out.println("Oval fires event");
        }
    });
    rbtRectangle.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            shape = rectangle;
            shape.repaint();
            System.out.println("Rectangle fires event");
        }
    });
}


public Dimension getPreferredSize(){
    return new Dimension(500, 500);
}

public abstract class MyShape extends JPanel{
    public abstract String dummyString();
    public void paintComponent(Graphics g){
        super.paintComponent(g);
    }
}
public class MyOval extends MyShape{
    public String dummyString(){
        return "Draw oval";
    }
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        g.drawOval(50, 50, 100, 80);
        String textOval = "paint oval " + dummyString();
        System.out.println(textOval);
    }
}
public class MyRectangle extends MyShape{
    public String dummyString(){
        return "Draw rectangle";
    }
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        g.drawRect(50, 50, 100, 80);
        String textRectangle = "paint rectangle " + dummyString();
        System.out.println(textRectangle);
    }
}

}

2 个答案:

答案 0 :(得分:0)

  

不执行矩形对象的paint组件

您所做的只是在JPanel上设置一个字段,而不是更改JPanel本身。我怀疑你打算删除椭圆并添加矩形。

答案 1 :(得分:0)

你的OOP是健全的;你的秋千不是。

您开始将shape设置为oval。此形状已添加到您的JPanel中。该矩形从未添加到JPanel中。即使你设置shape = rectangle,然后告诉它绘制,Swing也知道你的rectangle没有父组件,因此永远不会被绘制。所以告诉repaint()致电paintComponent()