Swing example with two buttons

import java.awt.*;
import java.applet.*;
import javax.swing.*; // Using swing
import java.awt.event.*; // using listeners

public class SecondSwing extends JPanel {
    private JLabel label;
    private JButton button1;
    private JButton button2;
    // the counter for button clicks
    int count = 0;

    // this is an application: need main
    public static void main(String[] args) {

	// setting up the frame, give it a title
	JFrame fr = new JFrame("First swing example");
	fr.setSize(500,100);
	fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

	// get the frame's content pane:
	Container cp = fr.getContentPane();

	// create and initialize a SecondSwing object
	SecondSwing ss = new SecondSwing();
	ss.init();

	// add the object to the frame
	cp.add(ss);
	
	// display the frame (after the object is added)
	fr.setVisible(true);
    }

    // the method initializes the FirstSwing object
    public void init() {
	// note: label is now instance variable:
	label = new JLabel();
	putLabelText();
	add(label);

	// adding a button and a button listener
	button1 = new JButton("Add 1 to the counter");
	// add the listener to the button
	button1.addActionListener(new ButtonListener(this,1));
	// add the button to SecondSwing:
	add(button1);

	// adding a button and a button listener
	button2 = new JButton("Subtract 1 from the counter");
	// add the listener to the button
	button2.addActionListener(new ButtonListener(this,-1));
	// add the button to SecondSwing:
	add(button2);	
    }

    public void putLabelText() {
	label.setText("counter = " + count);
    }

    public void update(int increment) {
	count += increment;
	putLabelText();
    }
}


class ButtonListener implements ActionListener {
    private SecondSwing swing;
    int increment;

    public ButtonListener(SecondSwing swing, int i) {
	this.swing = swing; // save a reference to the object
	increment = i;
    }

    // for any action on the button
    public void actionPerformed(ActionEvent e) {
	swing.update(increment);
    }
}

This is an example from CSci 2101 course.

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.