Creating and incrementing a button in java

Problem:

Create a java panel that shows a button and increments it.

Output:



Prompt Picture Description

Solution:

package com.javaproblems.comJButtonDemo;

import javax.swing.JFrame;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class PushButtonPanel extends JPanel {

 private JButton pushButton;
 private JLabel outputLabel;
 private int count;
 
 public PushButtonPanel() {
  count = 0;
  outputLabel  = new JLabel("Count: " + count);
  pushButton = new JButton("Push me");
  
  add(pushButton);
  add(outputLabel);
  pushButton.addActionListener(new ButtonListener());
  
  setBackground(Color.cyan);
  setPreferredSize(new Dimension(300,200));
 }

 private class ButtonListener implements ActionListener {
  @Override
  public void actionPerformed(ActionEvent e) {
   count++;
   outputLabel.setText("Count: " + count);
  }
 }
 
}


No comments :

Post a Comment

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact