Key to CSE190L Sample Midterm handout #15
Spring 2007
1. Statement Output
--------------------------------------------------
var1.method1(); Frodo 1/Bilbo 1
var2.method1(); Bilbo 1
var3.method1(); Gandalf 1
var4.method1(); compiler error
var5.method1(); Frodo 1/Bilbo 1
var6.method1(); compiler error
var1.method2(); Gandalf 2/Frodo 1/Bilbo 1
var2.method2(); Gandalf 2/Bilbo 1
var3.method2(); Gandalf 2/Gandalf 1
var4.method2(); compiler error
var5.method2(); Gandalf 2/Frodo 1/Bilbo 1
var6.method2(); compiler error
((Bilbo)var1).method3(); compiler error
((Gandalf)var1).method2(); Gandalf 2/Frodo 1/Bilbo 1
((Frodo)var4).method1(); runtime error
((Gandalf)var6).method2(); Gandalf 2/Gandalf 1
((Gandalf)var4).method1(); Bilbo 1
((Frodo)var6).method3(); runtime error
((Frodo)var3).method3(); runtime error
((Frodo)var5).method3(); Frodo 3
2. One possible solution appears below.
public class ShapePanel extends JPanel {
private boolean drawingCircles;
private Point point1;
private ArrayList circles;
private ArrayList lines;
public ShapePanel() {
drawingCircles = true;
setBackground(Color.GREEN);
circles = new ArrayList();
lines = new ArrayList();
}
public void recordClick(Point p) {
if (drawingCircles)
circles.add(new Ellipse2D.Double(p.x - 10, p.y - 10, 20,
20));
else if (point1 == null)
point1 = p;
else {
lines.add(new Line2D.Double(point1, p));
point1 = null;
}
repaint();
}
public void drawCircles() {
drawingCircles = true;
}
public void drawLines() {
drawingCircles = false;
point1 = null;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setPaint(Color.RED);
for (Ellipse2D circle : circles)
g2.fill(circle);
g2.setPaint(Color.BLUE);
for (Line2D line : lines)
g2.draw(line);
}
}
3. One possible solution appears below.
public class ShapeFrame {
private JFrame frame;
private ShapePanel panel;
public ShapeFrame() {
frame = new JFrame();
frame.setSize(400, 300);
frame.setTitle("Shape Maker");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new ShapePanel();
frame.add(panel, BorderLayout.CENTER);
panel.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
panel.recordClick(e.getPoint());
}
});
JRadioButton b1 = new JRadioButton("circles", true);
JRadioButton b2 = new JRadioButton("lines", false);
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
panel.drawCircles();
}
});
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
panel.drawLines();
}
});
JPanel p = new JPanel();
p.add(b1);
p.add(b2);
ButtonGroup group = new ButtonGroup();
group.add(b1);
group.add(b2);
frame.add(p, BorderLayout.NORTH);
}
public void start() {
frame.setVisible(true);
}
}