Actually: It needs to Increment the number of votes by one when you click on the candidate's name, and show the total of both candidates.
import javax.swing.*; import java.swing.JFrame; import java.awt.*; import java.awt.event.*; public class LabE extends JFrame implements PartyLabels { public LabE() { JPanel jp = new JPanel(); jp.setLayout( new GridLayout( 1, 2, 5, 5 )); AmericanButton abMcCain = new AmericanButton( REPUBLICAN, "McCain" ); AmericanButton abObama = new AmericanButton( DEMOCRAT, "Obama" ); jp.add( abMcCain ); jp.add( abObama ); add( jp ); theHandler handler = new theHandler(); abMcCain.addActionListener(handler); abObama.addActionListener(handler); } private class theHandler implements ActionListener{ public void actionPerformed(ActionEvent event){ int a; a = 0; int b; b = 0; if(event.getSource()== abMcCain) b++; System.out.println("McCain: " + b + event.getActionCommand()); else if(event.getSource()== abObama) a++; System.out.println("Obama: " + a + event.getActionCommand()); } } public static void main(String[] args) { LabE frame = new LabE(); frame.setTitle( "Candidates" ); frame.setLocationRelativeTo( null ); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); frame.setSize( 400, 200 ); frame.setVisible( true ); } }
class AmericanButton extends JButton implements PartyLabels { int party; String text; public AmericanButton( int party, String text ) { this.party = party; this.text = text; } protected void paintComponent( Graphics g ) { super.paintComponent( g ); // Color c = new Color( Color.white ); if ( party == REPUBLICAN ) { g.setColor( Color.red ); } else if ( party == DEMOCRAT ) { g.setColor( Color.blue ); } g.fillRect( 0, 0, getWidth(), getHeight() ); g.setColor( Color.white ); g.fillRect( 30, 30, getWidth()-60, getHeight()-60 ); Font f = new Font( "SansSerif", Font.BOLD, 20 ); if ( party == REPUBLICAN ) { g.setColor( Color.red ); } else if ( party == DEMOCRAT ) { g.setColor( Color.blue ); } g.setFont( f ); // Get font metrics for the current font FontMetrics fm = g.getFontMetrics(); // Find the center location to display int stringWidth = fm.stringWidth(text); int stringAscent = fm.getAscent(); // Get the position of the leftmost character in the baseline int xCoordinate = getWidth() / 2 - stringWidth / 2; int yCoordinate = getHeight() / 2 + stringAscent / 2; g.drawString(text, xCoordinate, yCoordinate); } }// this interface holds the labels for the parties. interface PartyLabels { public static final int DEMOCRAT = 0; public static final int REPUBLICAN = 1; }
thanks everyone!