Key to CSE190L Sample Midterm handout #16 Spring 2007 1. Statement Output -------------------------------------------------- var1.method1(); Water 1/Tea 2/Water 2 var2.method1(); Water 1/Milk 2 var3.method1(); Water 1/Water 2 var4.method1(); Water 1/Milk 2 var5.method1(); compiler error var1.method2(); Tea 2/Water 2 var2.method2(); Milk 2 var3.method2(); Water 2 var4.method2(); Milk 2 var1.method3(); compiler error var2.method3(); Milk 3 var3.method3(); compiler error ((Water)var5).method1(); Water 1/Water 2 ((Cola)var3).method3(); Cola 3 ((Water)var5).method2(); Water 2 ((Milk)var6).method2(); runtime error ((Tea)var4).method3(); Milk 3 ((Tea)var3).method3(); runtime error ((Tea)var1).method3(); Tea 3 ((Water)var6).method3(); compiler error 2. One possible solution appears below. public class RectanglePanel extends JPanel { private Point p1; private Point p2; private int innerCount; private int outerCount; public RectanglePanel() { setBackground(Color.CYAN); } public void recordClick(Point p) { if (p1 == null) p1 = p; else if (p2 == null) { p2 = p; if (p1.x > p2.x) { int temp = p1.x; p1.x = p2.x; p2.x = temp; } if (p1.y > p2.y) { int temp = p1.y; p1.y = p2.y; p2.y = temp; } } else if (inRectangle(p)) innerCount++; else outerCount++; repaint(); } private boolean inRectangle(Point p) { return p.x >= p1.x && p.x <= p2.x && p.y >= p1.y && p.y <= p2.y; } public void reset() { p1 = null; p2 = null; innerCount = 0; outerCount = 0; repaint(); } public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; g2.drawString("count = " + outerCount,0, getHeight()); if (p1 != null && p2 != null) { g2.setPaint(Color.RED); Rectangle2D r = new Rectangle2D.Double(p1.x, p1.y, p2.x - p1.x + 1, p2.y - p1.y + 1); g2.fill(r); g2.setPaint(Color.BLACK); g2.drawString("count = " + innerCount, p1.x, p2.y); } } } 3. One possible solution appears below. public class RectangleFrame { private JFrame frame; private RectanglePanel panel; public RectangleFrame() { frame = new JFrame(); frame.setSize(500, 200); frame.setTitle("Rectangle fun"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); panel = new RectanglePanel(); frame.add(panel, BorderLayout.CENTER); panel.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { panel.recordClick(e.getPoint()); } }); JButton b = new JButton("reset"); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { panel.reset(); } }); JPanel p = new JPanel(); p.add(b); frame.add(p, BorderLayout.SOUTH); } public void start() { frame.setVisible(true); } }
Stuart Reges
Last modified: Fri May 4 12:16:06 PDT 2007