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");

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

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

	// add the object to the frame
	// display the frame (after the object is added)

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

	// 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:

	// 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:

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

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

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) {

This is an example from CSci 1211 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.