[Java] Count 숫자카운트 만들기_Swing 구현

Jeini·2022년 12월 22일
0

📌 Code list

목록 보기
38/55
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();
    }
    //	Component 초기화
    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();
    }
}

profile
Fill in my own colorful colors🎨

0개의 댓글