//------------------------------------------------------------------------------------------------- // // CalcComponent2.java // // written by: Simon Parsons // last modified: 6th September 2012 // // An object that does some very basic arithmetic operations. It does these operations on // random numbers so that we don't have to handle input for now import java.awt.*; // Use the awt library import java.awt.event.*; import java.awt.geom.*; import javax.swing.*; // Use the swing library import java.util.Random; // Get random numbers import java.lang.Number.*; // Need this for Integer // The CalcComponent class is a subclass of JComponent and defines an object that listens // for actions (in this case multiple button presses). public class CalcComponent2 extends JComponent implements ActionListener { int a; int b; int result = 0; JButton buttons[]; Random randomGenerator = new Random(); // Need this to generate random numbers. // Set up buttons and add a listener for each. The first four buttons (should) // implement some arithmetic operations, the last resets the calculator. public CalcComponent2() { a = randomGenerator.nextInt(10); b = randomGenerator.nextInt(10); buttons = new JButton[5]; buttons[0] = new JButton("+"); buttons[1] = new JButton("-"); buttons[2] = new JButton("*"); buttons[3] = new JButton("/"); buttons[4] = new JButton("Again!"); setLayout(new FlowLayout()); for(int i=0; i<5; i++){ add(buttons[i]); buttons[i].addActionListener(this); } } // How to put the values of a, b and result onto the screen. // We use an Integer object to convert the values of the variables // into the string format we need for output. // // Note that we are treating the output here in the same way we handled // the ellipses, that is as if they were graphics elements. public void paintComponent(Graphics g){ Integer aInt = a; Integer bInt = b; g.drawString("a = " + aInt.toString(), 125, 95); g.drawString("b = " + bInt.toString(), 125, 115); Integer rInt = result; g.drawString(rInt.toString(), 152, 140); } // Do the relevant operation on the numbers public void actionPerformed(ActionEvent e){ // This is the + button, so add the numbers up. if(e.getSource() == buttons[0]){ addUp(a, b); } if(e.getSource() == buttons[1]){ ; } if(e.getSource() == buttons[2]){ ; } if(e.getSource() == buttons[3]){ ; } // This is the Again! button, so reset a, b and result. if(e.getSource() == buttons[4]){ a = randomGenerator.nextInt(10); b = randomGenerator.nextInt(10); result = 0; } repaint(); } // A function to sum up two integers, writing the outcome into // the attribute result. public void addUp(int x, int y){ result = x + y; } }