Problem:
Create a java panel that shows a button and increments it.
Output:
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