2. Modify the program so that there are two candidates to vote for—Joe and Sam. To do this you need to do the following:
a. Add variables for Sam—a vote counter, a button, and a label.
b. Add a new inner class named Sam Button Listener to listen for clicks on the button for Sam. Instantiate an instance of the class when adding the Action Listener to the button for Sam.
c. Add the button and label for Sam to the panel. 代码如下:
//************************************************************
//Vote Counter Panel.java //Demonstrates a graphical user interface and event listeners to
//tally votes for two candidates, Joe and Sam.
//*************************************************** package lab4;
import java.awt.*;
import java.awt.event.*; import javax. swing. *;
public class VoteCounterPanel extends JPanel {
private int votesForJoe,votesForSam; private JButton joe,Sam;
private JLabel labelJoe,labelSam; public VoteCounterPanel() {
votesForJoe = 0; votesForSam = 0;
joe = new JButton(\ Sam = new JButton(\
joe.addActionListener(new JoeButtonListener()); Sam.addActionListener(new SamButtonListener());
labelJoe = new JLabel(\ labelSam = new JLabel(\ add(joe);
add(labelJoe); add(Sam);
add(labelSam);
setPreferredSize(new Dimension(300, 80)); setBackground(Color.cyan); }
private class JoeButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
votesForJoe++;
labelJoe.setText(\ } }
private class SamButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
votesForSam++;
labelSam.setText(\ } } }
3、Compile and run the program.
点击按钮后:
4、以重用的思想实现该界面的代码如下: package lab4;
import java.awt.Color; import java.awt.Dimension; import java.awt.event.*;
import javax.swing.*;
public class VoteCounter1 extends JFrame ActionListener{
private JPanel VoteCounterPanel; private int votesForJoe,votesForSam; private JButton joe,Sam;
private JLabel labelJoe,labelSam;
public VoteCounter1() {
votesForJoe = 0;
implements votesForSam = 0;
VoteCounterPanel=new JPanel(); joe = new JButton(\ Sam = new JButton(\ joe.addActionListener(this); Sam.addActionListener(this);
labelJoe = new JLabel(\for Joe: \+ votesForJoe); labelSam = new JLabel(\for Sam: \+ votesForSam); VoteCounterPanel.add(joe); VoteCounterPanel.add(labelJoe); VoteCounterPanel.add(Sam); VoteCounterPanel.add(labelSam);
VoteCounterPanel.setPreferredSize(new Dimension(300, 80));
VoteCounterPanel.setBackground(Color.cyan); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); getContentPane().add(VoteCounterPanel); pack();
setVisible(true); }
public void actionPerformed(ActionEvent event)
相关推荐: