import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Counter extends JFrame implements ActionListener {
private JButton btnPlus;
private JButton btnMinus;
private JButton btnDefault;
private JLabel lblNum;
public Counter() {
init();
setDisplay();
addListeners();
showFrame();
}
private void init() {
btnPlus = new JButton("plus");
btnMinus = new JButton("minus");
btnDefault = new JButton("default");
lblNum = new JLabel("0", JLabel.CENTER);
lblNum.setFont(new Font(Font.DIALOG, Font.BOLD, 60));
}
private void setDisplay() {
JPanel pnlSouth = new JPanel(new GridLayout(0, 2));
pnlSouth.add(btnPlus);
pnlSouth.add(btnMinus);
add(btnDefault, BorderLayout.NORTH);
add(lblNum, BorderLayout.CENTER);
add(pnlSouth, BorderLayout.SOUTH);
}
private void addListeners() {
btnPlus.addActionListener( this );
btnMinus.addActionListener(this);
btnDefault.addActionListener(this);
}
private void showFrame() {
setTitle("counter");
setSize(300, 400);
setLocation(100, 0);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent ae) {
Object source = ae.getSource();
String strNum = "0";
if(source != btnDefault) {
int num = Integer.parseInt(lblNum.getText());
if (source == btnPlus) {
num++;
}
if (source == btnMinus) {
num--;
}
strNum = String.valueOf(num);
}
lblNum.setText(strNum);
}
public static void main(String[] args) {
new Counter();
}
}